@rizom/brain 0.2.0-alpha.145 → 0.2.0-alpha.146

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.
@@ -162,7 +162,7 @@
162
162
  "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n",
163
163
  "export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport { toJSONSchema } from \"../core/json-schema-processors.js\";\nexport { fromJSONSchema } from \"./from-json-schema.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n",
164
164
  "import { z } from \"@brains/utils/zod\";\n\nconst canonicalContentVisibilitySchema: z.ZodEnum<{\n public: \"public\";\n shared: \"shared\";\n restricted: \"restricted\";\n}> = z.enum([\"public\", \"shared\", \"restricted\"]);\n\nexport type ContentVisibility = z.infer<\n typeof canonicalContentVisibilitySchema\n>;\nexport type RawContentVisibility = ContentVisibility | \"private\";\n\nexport const contentVisibilitySchema: z.ZodPipe<\n z.ZodOptional<\n z.ZodUnion<\n readonly [\n typeof canonicalContentVisibilitySchema,\n z.ZodLiteral<\"private\">,\n ]\n >\n >,\n z.ZodTransform<ContentVisibility, RawContentVisibility | undefined>\n> = z\n .union([canonicalContentVisibilitySchema, z.literal(\"private\")])\n .optional()\n .transform((value): ContentVisibility => {\n if (value === undefined) return \"public\";\n if (value === \"private\") return \"restricted\";\n return value;\n });\n\nexport function normalizeContentVisibility(\n visibility: RawContentVisibility | undefined,\n): ContentVisibility {\n return contentVisibilitySchema.parse(visibility);\n}\n\nconst visibleContentVisibilitiesByScope: Record<\n ContentVisibility,\n ContentVisibility[]\n> = {\n public: [\"public\"],\n shared: [\"public\", \"shared\"],\n restricted: [\"public\", \"shared\", \"restricted\"],\n};\n\nexport function getVisibleContentVisibilities(\n scope: ContentVisibility,\n): ContentVisibility[] {\n return visibleContentVisibilitiesByScope[scope];\n}\n\nexport function isVisibleWithinScope(\n visibility: ContentVisibility | undefined,\n scope: ContentVisibility,\n): boolean {\n return getVisibleContentVisibilities(scope).includes(visibility ?? \"public\");\n}\n\n/**\n * Map a caller's permission level to the content-visibility scope they may see.\n * public → public (only public content)\n * trusted → shared (public + shared)\n * anchor → restricted (public + shared + restricted)\n *\n * Defaults to \"public\" when no permission level is provided, so missing\n * context fails closed.\n */\nexport function permissionToVisibilityScope(\n level: \"anchor\" | \"trusted\" | \"public\" | undefined,\n): ContentVisibility {\n if (level === \"anchor\") return \"restricted\";\n if (level === \"trusted\") return \"shared\";\n return \"public\";\n}\n\n/**\n * Whether a caller at `level` is allowed to author or update an entity at\n * `visibility`. A user may only write content at a visibility they themselves\n * can read — otherwise they could ghost-write content into a higher trust\n * level than their permission, which is a write-side escalation vector.\n *\n * public → may write \"public\"\n * trusted → may write \"public\" | \"shared\"\n * anchor → may write \"public\" | \"shared\" | \"restricted\"\n */\nexport function canWriteVisibility(\n level: \"anchor\" | \"trusted\" | \"public\" | undefined,\n visibility: ContentVisibility,\n): boolean {\n return isVisibleWithinScope(visibility, permissionToVisibilityScope(level));\n}\n",
165
- "import { z } from \"@brains/utils/zod\";\nimport {\n contentVisibilitySchema,\n type ContentVisibility,\n type RawContentVisibility,\n} from \"./visibility\";\n\n/**\n * Entity type for unstructured notes (the \"note\" entity type).\n * Used as a sentinel for the default catch-all markdown file shape —\n * no typed frontmatter schema required, content is the entire file body.\n */\nexport const NOTE_ENTITY_TYPE = \"note\";\n\n/**\n * Embedding job data - minimal data for job queue\n * Content is NOT stored to avoid large base64 data in job queue\n * (which would end up in dashboard hydration props JSON)\n * Handler fetches fresh content from entity when processing\n */\nexport interface EmbeddingJobData {\n id: string;\n entityType: string;\n /** Hash of content at job creation time - for staleness detection */\n contentHash: string;\n operation: \"create\" | \"update\";\n}\n\n/**\n * Options for entity mutation operations (create, update, upsert)\n */\nexport interface EntityMutationEventContext {\n conversationId?: string;\n channelId?: string;\n runId?: string;\n toolCallId?: string;\n}\n\nexport interface EntityJobOptions {\n priority?: number;\n maxRetries?: number;\n eventContext?: EntityMutationEventContext;\n}\n\nexport {\n contentVisibilitySchema,\n normalizeContentVisibility,\n getVisibleContentVisibilities,\n isVisibleWithinScope,\n permissionToVisibilityScope,\n canWriteVisibility,\n} from \"./visibility\";\nexport type { ContentVisibility, RawContentVisibility } from \"./visibility\";\n\n/**\n * Options for entity creation (extends EntityJobOptions with deduplication)\n */\nexport interface CreateEntityOptions extends EntityJobOptions {\n deduplicateId?: boolean;\n}\n\n/**\n * Result of an entity mutation that triggers an embedding job.\n * When skipped is true, content was unchanged — no DB write, no event, no embedding job.\n */\nexport interface EntityMutationResult {\n entityId: string;\n jobId: string;\n skipped: boolean;\n}\n\n/**\n * Input for adapter-validated direct creation from finalized markdown.\n */\nexport interface CreateEntityFromMarkdownInput {\n entityType: string;\n id: string;\n markdown: string;\n}\n\n/**\n * Data for storing an embedding for an entity\n */\nexport interface StoreEmbeddingData {\n entityId: string;\n entityType: string;\n embedding: Float32Array;\n contentHash: string;\n}\n\n/**\n * Base entity schema that all entities must extend\n */\nexport const baseEntitySchema: z.ZodObject<{\n id: z.ZodString;\n entityType: z.ZodString;\n content: z.ZodString;\n created: z.ZodString;\n updated: z.ZodString;\n visibility: typeof contentVisibilitySchema;\n metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;\n contentHash: z.ZodString;\n}> = z.object({\n id: z.string(),\n entityType: z.string(),\n content: z.string(),\n created: z.string().datetime(),\n updated: z.string().datetime(),\n visibility: contentVisibilitySchema,\n metadata: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n});\n\nconst canonicalContentVisibilityParserSchema: z.ZodEnum<{\n public: \"public\";\n shared: \"shared\";\n restricted: \"restricted\";\n}> = z.enum([\"public\", \"shared\", \"restricted\"]);\n\n/** Zod 4-owned parser base for entity schemas whose registration slot is structural. */\nexport const baseEntityParserSchema: z.ZodObject<{\n id: z.ZodString;\n entityType: z.ZodString;\n content: z.ZodString;\n created: z.ZodString;\n updated: z.ZodString;\n visibility: z.ZodPipe<\n z.ZodOptional<\n z.ZodUnion<\n readonly [\n typeof canonicalContentVisibilityParserSchema,\n z.ZodLiteral<\"private\">,\n ]\n >\n >,\n z.ZodTransform<ContentVisibility, RawContentVisibility | undefined>\n >;\n metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;\n contentHash: z.ZodString;\n}> = z.object({\n id: z.string(),\n entityType: z.string(),\n content: z.string(),\n created: z.string().datetime(),\n updated: z.string().datetime(),\n visibility: z\n .union([canonicalContentVisibilityParserSchema, z.literal(\"private\")])\n .optional()\n .transform((value): ContentVisibility => {\n if (value === undefined) return \"public\";\n if (value === \"private\") return \"restricted\";\n return value;\n }),\n metadata: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n});\n\n/** Shared empty frontmatter schema for entity types with no typed frontmatter. */\nexport const emptyFrontmatterSchema: z.ZodObject<Record<string, never>> =\n z.object({});\n\nexport type EntitySchema<T> = z.ZodType<T, unknown>;\n/** @deprecated Use EntitySchema<T>. */\nexport type EntitySchemaParser<T> = EntitySchema<T>;\n\nexport type UnknownEntitySchema = EntitySchema<unknown>;\nexport type FrontmatterSchema = z.ZodObject<z.ZodRawShape>;\n\n/**\n * Base entity type - generic to support typed metadata\n * TMetadata defaults to Record<string, unknown> for backward compatibility\n */\nexport interface BaseEntity<TMetadata = Record<string, unknown>> {\n id: string;\n entityType: string;\n content: string;\n created: string;\n updated: string;\n visibility: ContentVisibility;\n metadata: TMetadata;\n /** SHA256 hash of content for change detection */\n contentHash: string;\n}\n\n/**\n * Entity input type for creation - allows partial entities with optional system fields\n * contentHash is excluded because it's computed automatically by the entity service\n */\nexport type EntityInput<T extends BaseEntity> = Omit<\n T,\n \"id\" | \"created\" | \"updated\" | \"contentHash\" | \"visibility\"\n> & {\n id?: string;\n created?: string;\n updated?: string;\n visibility?: RawContentVisibility;\n};\n\n/**\n * Search result type\n */\nexport interface SearchResult<T extends BaseEntity = BaseEntity> {\n entity: T;\n score: number;\n excerpt: string;\n}\n\n/**\n * Normalized system_create input shape used by plugin create interceptors.\n */\nexport interface CreateCoverImageInput {\n generate?: boolean | undefined;\n prompt?: string | undefined;\n}\n\nexport interface CreateFromAttachmentInput {\n kind: \"entity-attachment\";\n sourceEntityType: string;\n sourceEntityId: string;\n attachmentType: string;\n}\n\nexport interface CreateFromUploadInput {\n kind: \"upload\";\n id: string;\n}\n\nexport interface CreateFromConversationMessageInput {\n kind: \"conversation-message\";\n messageId?: string | undefined;\n}\n\nexport type CreateFromInput =\n | CreateFromAttachmentInput\n | CreateFromUploadInput\n | CreateFromConversationMessageInput;\n\nexport type CreateTransform = \"extract-markdown\" | \"preserve\";\n\nexport interface CreateInput {\n entityType: string;\n prompt?: string;\n title?: string;\n content?: string;\n url?: string;\n from?: CreateFromInput;\n transform?: CreateTransform;\n replace?: boolean;\n sourceEntityType?: string;\n sourceEntityId?: string;\n sourceEntityIds?: string[];\n targetEntityType?: string;\n targetEntityId?: string;\n coverImage?: boolean | CreateCoverImageInput;\n}\n\n/**\n * Minimal caller context forwarded to plugin create interceptors.\n */\nexport interface CreateExecutionContext {\n interfaceType: string;\n userId: string;\n channelId?: string;\n channelName?: string;\n}\n\n/**\n * Result returned to system_create when a plugin fully handles creation.\n */\nexport const createResultAttachmentSchema: z.ZodObject<{\n mediaType: z.ZodString;\n url: z.ZodString;\n downloadUrl: z.ZodOptional<z.ZodString>;\n previewUrl: z.ZodOptional<z.ZodString>;\n filename: z.ZodOptional<z.ZodString>;\n sizeBytes: z.ZodOptional<z.ZodNumber>;\n source: z.ZodOptional<\n z.ZodObject<{\n entityType: z.ZodOptional<z.ZodString>;\n entityId: z.ZodOptional<z.ZodString>;\n attachmentType: z.ZodOptional<z.ZodString>;\n }>\n >;\n}> = z.object({\n mediaType: z.string(),\n url: z.string(),\n downloadUrl: z.string().optional(),\n previewUrl: z.string().optional(),\n filename: z.string().optional(),\n sizeBytes: z.number().optional(),\n source: z\n .object({\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n attachmentType: z.string().optional(),\n })\n .optional(),\n});\n\nexport type CreateResultAttachment = z.infer<\n typeof createResultAttachmentSchema\n>;\n\nexport type CreateResult =\n | {\n success: true;\n data: {\n entityId?: string;\n jobId?: string;\n status: string;\n attachment?: CreateResultAttachment;\n };\n }\n | { success: false; error: string };\n\n/**\n * Plugin create interceptors can either fully handle creation,\n * or continue with a rewritten normalized input.\n */\nexport type CreateInterceptionResult =\n | { kind: \"handled\"; result: CreateResult }\n | { kind: \"continue\"; input: CreateInput };\n\nexport type CreateInterceptor = (\n input: CreateInput,\n executionContext: CreateExecutionContext,\n) => Promise<CreateInterceptionResult>;\n\nexport interface UploadSaveInput {\n upload: CreateFromUploadInput;\n title?: string;\n}\n\nexport type UploadSaveHandler = (\n input: UploadSaveInput,\n executionContext: CreateExecutionContext,\n) => Promise<CreateResult>;\n\nexport interface UploadSaveHandlerRegistration {\n entityType: string;\n mediaTypes: string[];\n handler: UploadSaveHandler;\n}\n\n/**\n * Called before an entity is persisted (on create or update). Throws to reject\n * the write with an operator-facing error. Use this for cross-entity invariants\n * the per-entity Zod schema cannot express.\n */\nexport type PersistValidator<T extends BaseEntity = BaseEntity> = (\n entity: T,\n context: { operation: \"create\" | \"update\" },\n) => Promise<void>;\n\n/**\n * Minimal event bus contract used by entity-service for lifecycle events.\n * Kept structural to avoid coupling this package to a concrete messaging service.\n */\nexport interface EntityEventBus {\n send(request: {\n type: string;\n payload: Record<string, unknown>;\n sender: string;\n target?: string;\n metadata?: Record<string, unknown>;\n broadcast?: boolean;\n }): Promise<unknown>;\n}\n\n/**\n * Interface for entity adapter - handles conversion between entities and markdown\n * following the hybrid storage model\n *\n * @template TEntity - The full entity type\n * @template TMetadata - The metadata type (defaults to Record<string, unknown>)\n */\nexport interface EntityAdapter<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n> {\n entityType: string;\n\n /**\n * One declarative sentence describing what this entity type is. This is the\n * data the model reads to select `entityType`, replacing hardcoded example\n * phrasings in system instructions. Required: every type must define itself.\n */\n purpose: string;\n\n schema: EntitySchema<TEntity>;\n\n // Convert entity to markdown content (may include frontmatter for entity-specific fields)\n toMarkdown(entity: TEntity): string;\n\n // Extract entity-specific fields from markdown\n // Returns Partial<TEntity> as core fields come from database\n fromMarkdown(markdown: string): Partial<TEntity>;\n\n // Extract metadata from entity for search/filtering - now strongly typed\n extractMetadata(entity: TEntity): TMetadata;\n\n // Parse frontmatter metadata from markdown\n parseFrontMatter<TFrontmatter>(\n markdown: string,\n schema: { parse(data: unknown): TFrontmatter },\n ): TFrontmatter;\n\n // Generate frontmatter for markdown\n generateFrontMatter(entity: TEntity): string;\n\n /** Optional: Zod schema for frontmatter fields. Used by CMS config generation. */\n frontmatterSchema?: z.ZodObject<z.ZodRawShape>;\n\n /** Optional: Declares this entity type is a singleton (one file, e.g., identity/identity.md). Used by CMS to generate files collection. */\n isSingleton?: boolean;\n\n /** Optional: Whether this entity has a free-form markdown body below frontmatter. Defaults to true. When false, CMS omits the body widget. */\n hasBody?: boolean;\n\n /** Returns a markdown body template with section headings for this entity type. Empty string for free-form entities. */\n getBodyTemplate(): string;\n\n /** Optional: Declares that this entity type supports cover images via coverImageId in frontmatter */\n supportsCoverImage?: boolean;\n\n /** Optional: Extract coverImageId from entity content/frontmatter */\n getCoverImageId?(entity: TEntity): string | undefined;\n\n /**\n * Optional: build the markdown content and metadata for a queued-generation stub.\n * When undefined, this entity type does not support prompt-based queued creation\n * via system_create; the tool will reject the call rather than silently degrade.\n * The returned metadata must satisfy this entity's metadata schema (with\n * status set to \"generating\"); central code only stamps id/timestamps/visibility.\n */\n buildStub?(input: { id: string; title: string }): {\n content: string;\n metadata: TMetadata;\n };\n}\n\n/**\n * Sort field specification for multi-field sorting\n */\nexport interface SortField {\n /** Field to sort by - \"created\", \"updated\", or a metadata field name */\n field: string;\n /** Sort direction */\n direction: \"asc\" | \"desc\";\n /** Sort NULL values before non-NULL values (default: false / SQLite default) */\n nullsFirst?: boolean;\n}\n\n/**\n * List entities options\n * Generic over metadata type for type-safe filtering\n */\nexport interface ListOptions<TMetadata = Record<string, unknown>> {\n limit?: number;\n offset?: number;\n /** Multi-field sorting - supports system fields (created, updated) and metadata fields */\n sortFields?: SortField[];\n filter?: {\n // Typed metadata filter - partial match on metadata fields\n metadata?: Partial<TMetadata>;\n visibilityScope?: ContentVisibility;\n };\n /** Filter to only entities with metadata.status = \"published\" */\n publishedOnly?: boolean;\n}\n\n/**\n * Search options\n */\nexport interface SearchOptions {\n limit?: number;\n offset?: number;\n types?: string[];\n excludeTypes?: string[];\n sortBy?: \"relevance\" | \"created\" | \"updated\";\n sortDirection?: \"asc\" | \"desc\";\n /** Score multipliers per entity type - applied after initial search */\n weight?: Record<string, number>;\n visibilityScope?: ContentVisibility;\n /** Include queued/failed generation stubs in search results (default: false) */\n includeUngenerated?: boolean;\n /** Minimum relevance score to return. Omit for no score cutoff. */\n minScore?: number;\n}\n\n/**\n * Configuration for entity type registration\n */\nexport interface EntityTypeConfig {\n /** Score multiplier for search results (default: 1.0) */\n weight?: number;\n /** Whether to generate embeddings for this entity type (default: true).\n * Set to false for entity types with non-textual content (e.g., images). */\n embeddable?: boolean;\n /** Whether this entity type may be used as source material for derived projections (default: true).\n * Set to false for projection outputs that would create feedback loops. */\n projectionSource?: boolean;\n /** Publish semantics for status-bearing entity types. Statuses listed here\n * represent publication commitment/execution states and require the\n * `publish` entity action when entered or modified. */\n publish?: {\n publishStatuses: string[];\n };\n}\n\n/**\n * Core entity service interface for read-only operations\n * Used by core plugins that need entity access but shouldn't modify entities\n */\nexport interface GetEntityRequest {\n entityType: string;\n id: string;\n /**\n * Optional visibility scope. Undefined fails closed to \"public\" — callers\n * with elevated access must opt up explicitly.\n */\n visibilityScope?: ContentVisibility;\n}\n\nexport type GetEntityRawRequest = GetEntityRequest;\n\nexport interface ListEntitiesRequest {\n entityType: string;\n options?: ListOptions | undefined;\n}\n\nexport interface CountEntitiesRequest {\n entityType: string;\n options?: Pick<ListOptions, \"publishedOnly\" | \"filter\"> | undefined;\n}\n\nexport interface CreateEntityRequest<T extends BaseEntity> {\n entity: EntityInput<T>;\n options?: CreateEntityOptions | undefined;\n}\n\nexport interface CreateEntityFromMarkdownRequest {\n input: CreateEntityFromMarkdownInput;\n options?: CreateEntityOptions | undefined;\n}\n\nexport interface UpdateEntityRequest<T extends BaseEntity> {\n entity: T;\n options?: EntityJobOptions | undefined;\n}\n\nexport interface DeleteEntityRequest {\n entityType: string;\n id: string;\n}\n\nexport interface UpsertEntityRequest<T extends BaseEntity> {\n entity: T;\n options?: EntityJobOptions | undefined;\n}\n\nexport interface EntitySearchRequest {\n query: string;\n options?: SearchOptions | undefined;\n}\n\nexport interface SearchWithDistancesRequest {\n query: string;\n}\n\n/**\n * Context passed to all DataSource operations\n * Contains internal state that should not be mixed with user query parameters\n */\nexport interface BaseDataSourceContext {\n /**\n * Whether to filter to only published/complete content\n * Set by site-builder: true for production, false for preview\n */\n publishedOnly?: boolean;\n\n /**\n * Scoped entity service that auto-applies publishedOnly filter\n * Datasources should use this instead of their injected entityService\n * to ensure consistent filtering behavior across environments\n */\n entityService: EntityService;\n}\n\nexport type DataSourceSchema<T> = z.ZodType<T, unknown>;\n\n/**\n * DataSource Interface\n *\n * Provides data for templates through fetch, generate, or transform operations.\n * DataSources are registered in the DataSourceRegistry and referenced by templates\n * via their dataSourceId property.\n */\nexport interface DataSource {\n /**\n * Unique identifier for this data source\n */\n id: string;\n\n /**\n * Human-readable name for this data source\n */\n name: string;\n\n /**\n * Optional description of what this data source provides\n */\n description?: string;\n\n /**\n * Optional: Fetch existing data\n * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)\n * DataSources validate output using the provided schema\n * @param query - Query parameters for fetching data\n * @param outputSchema - Schema for validating output data\n * @param context - Context with environment\n */\n fetch?: <T>(\n query: unknown,\n outputSchema: z.ZodSchema<T>,\n context: BaseDataSourceContext,\n ) => Promise<T>;\n\n /**\n * Optional: Generate new content\n * Used by data sources that create content (e.g., AI-generated content, reports)\n */\n generate?: <T>(request: unknown, schema: z.ZodSchema<T>) => Promise<T>;\n\n /**\n * Optional: Transform content between formats\n * Used by data sources that convert content (e.g., markdown to HTML, data formatting)\n */\n transform?: <T>(\n content: unknown,\n format: string,\n schema: z.ZodSchema<T>,\n ) => Promise<T>;\n}\n\n/**\n * DataSource capabilities for discovery and validation\n */\nexport interface DataSourceCapabilities {\n canFetch: boolean;\n canGenerate: boolean;\n canTransform: boolean;\n}\n\nexport interface ICoreEntityService {\n // Read-only operations\n getEntity<T extends BaseEntity>(request: GetEntityRequest): Promise<T | null>;\n\n /**\n * Get entity without content resolution (raw)\n * Used internally to avoid recursion when resolving image references\n */\n getEntityRaw<T extends BaseEntity>(\n request: GetEntityRawRequest,\n ): Promise<T | null>;\n\n listEntities<T extends BaseEntity>(\n request: ListEntitiesRequest,\n ): Promise<T[]>;\n\n search<T extends BaseEntity = BaseEntity>(\n request: EntitySearchRequest,\n ): Promise<SearchResult<T>[]>;\n\n // Entity type information\n getEntityTypes(): string[];\n hasEntityType(type: string): boolean;\n\n // Entity counts\n countEntities(request: CountEntitiesRequest): Promise<number>;\n /**\n * Group counts by entity type. Fails closed: undefined visibilityScope\n * filters to public-only counts so aggregate insights cannot reveal\n * non-public entity existence.\n */\n getEntityCounts(\n visibilityScope?: ContentVisibility,\n ): Promise<Array<{ entityType: string; count: number }>>;\n\n /** Get configuration for a specific entity type */\n getEntityTypeConfig(type: string): EntityTypeConfig;\n\n /** Get weight map for all registered entity types with non-default weights */\n getWeightMap(): Record<string, number>;\n}\n\n/**\n * Entity service interface for managing brain entities\n */\nexport interface IEntitiesNamespace {\n /** Register a new entity type with schema and adapter */\n register<TEntity extends BaseEntity>(\n entityType: string,\n schema: EntitySchema<TEntity>,\n adapter: EntityAdapter<TEntity>,\n config?: EntityTypeConfig,\n ): void;\n\n /**\n * Get the adapter for an entity type.\n *\n * Returns the structural `EntityAdapter<BaseEntity>` view — namespace\n * consumers don't narrow by entity type. For typed access tied to a\n * specific `TEntity`, use the underlying `EntityRegistry.getAdapter<T>`\n * directly (see `entity-serializer.ts`).\n */\n getAdapter(entityType: string): EntityAdapter<BaseEntity> | undefined;\n\n /** Extend an adapter's frontmatterSchema with additional fields */\n extendFrontmatterSchema(\n type: string,\n extension: z.ZodObject<z.ZodRawShape>,\n ): void;\n\n /** Get effective frontmatter schema (base + extensions) for an entity type */\n getEffectiveFrontmatterSchema(\n type: string,\n ): z.ZodObject<z.ZodRawShape> | undefined;\n\n /** Update an existing entity */\n update<TEntity extends BaseEntity>(\n entity: TEntity,\n ): Promise<{ entityId: string; jobId: string }>;\n\n /** Register a data source for dynamic content */\n registerDataSource(dataSource: DataSource): void;\n\n /** Register a create interceptor for this plugin's entity type */\n registerCreateInterceptor(\n entityType: string,\n interceptor: CreateInterceptor,\n ): void;\n\n /** Register a raw-upload durable save handler for this plugin's entity type */\n registerUploadSaveHandler(registration: UploadSaveHandlerRegistration): void;\n}\n\nexport interface EmbeddingBackfillResult {\n queued: number;\n skipped: number;\n}\n\nexport interface EmbeddingFailureReference {\n entityId: string;\n entityType: string;\n contentHash: string;\n}\n\nexport interface EmbeddingIndexStats {\n missingEmbeddings: number;\n staleEmbeddings: number;\n failedEmbeddings: number;\n /** Entities whose type generates embeddings (non-embeddable types excluded). */\n embeddableEntities: number;\n /** Embeddable entities whose embedding is present and current. */\n embeddedEntities: number;\n}\n\nexport interface IndexReadinessOptions {\n timeoutMs: number;\n intervalMs?: number;\n}\n\nexport interface IndexReadinessStatus extends EmbeddingIndexStats {\n ready: boolean;\n degraded: boolean;\n activeEmbeddingJobs: number;\n}\n\nexport interface EntityService extends ICoreEntityService {\n // Mutations\n createEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n ): Promise<EntityMutationResult>;\n createEntityFromMarkdown(\n request: CreateEntityFromMarkdownRequest,\n ): Promise<EntityMutationResult>;\n updateEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n ): Promise<EntityMutationResult>;\n deleteEntity(request: DeleteEntityRequest): Promise<boolean>;\n upsertEntity<T extends BaseEntity>(\n request: UpsertEntityRequest<T>,\n ): Promise<EntityMutationResult & { created: boolean }>;\n storeEmbedding(data: StoreEmbeddingData): Promise<void>;\n backfillMissingEmbeddings(): Promise<EmbeddingBackfillResult>;\n isIndexReady(): boolean;\n awaitIndexReady(\n options: IndexReadinessOptions,\n ): Promise<IndexReadinessStatus>;\n\n // Serialization\n serializeEntity(entity: BaseEntity): string;\n deserializeEntity(markdown: string, entityType: string): Partial<BaseEntity>;\n\n // Counts\n countEmbeddings(): Promise<number>;\n\n // Diagnostics\n searchWithDistances(\n request: SearchWithDistancesRequest,\n ): Promise<Array<{ entityId: string; entityType: string; distance: number }>>;\n\n // Lifecycle\n initialize(): Promise<void>;\n\n // Job status\n getAsyncJobStatus(jobId: string): Promise<{\n status: \"pending\" | \"processing\" | \"completed\" | \"failed\";\n error?: string;\n } | null>;\n}\n\n/**\n * Entity Registry interface for managing entity types and their schemas/adapters\n */\nexport interface EntityRegistry {\n registerEntityType<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n >(\n type: string,\n schema: UnknownEntitySchema,\n adapter: EntityAdapter<TEntity, TMetadata>,\n config?: EntityTypeConfig,\n ): void;\n\n getSchema(type: string): UnknownEntitySchema;\n\n getAdapter<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n >(\n type: string,\n ): EntityAdapter<TEntity, TMetadata>;\n\n hasEntityType(type: string): boolean;\n\n validateEntity(type: string, entity: unknown): BaseEntity;\n\n getAllEntityTypes(): string[];\n\n /** Get configuration for a specific entity type */\n getEntityTypeConfig(type: string): EntityTypeConfig;\n\n /** Get weight map for all registered entity types with non-default weights */\n getWeightMap(): Record<string, number>;\n\n registerCreateInterceptor(type: string, interceptor: CreateInterceptor): void;\n\n getCreateInterceptor(type: string): CreateInterceptor | undefined;\n\n registerUploadSaveHandler(registration: UploadSaveHandlerRegistration): void;\n\n getUploadSaveHandler(\n mediaType: string,\n ): UploadSaveHandlerRegistration | undefined;\n\n registerPersistValidator(type: string, validator: PersistValidator): void;\n\n getPersistValidator(type: string): PersistValidator | undefined;\n\n /**\n * Extend an adapter's frontmatterSchema with additional fields.\n * Used by plugins to add domain-specific fields (e.g., professional-site adds tagline to profile).\n * Extensions are merged into the effective schema returned by getEffectiveFrontmatterSchema().\n */\n extendFrontmatterSchema(\n type: string,\n extension: z.ZodObject<z.ZodRawShape>,\n ): void;\n\n /**\n * Get the effective frontmatter schema for an entity type,\n * with all registered extensions merged in.\n * Returns undefined if the adapter has no frontmatterSchema.\n */\n getEffectiveFrontmatterSchema(\n type: string,\n ): z.ZodObject<z.ZodRawShape> | undefined;\n}\n\n/**\n * Database configuration for entity service\n */\nexport type { DbConfig as EntityDbConfig } from \"@brains/contracts\";\n",
165
+ "import { z } from \"@brains/utils/zod\";\nimport {\n contentVisibilitySchema,\n type ContentVisibility,\n type RawContentVisibility,\n} from \"./visibility\";\n\n/**\n * Entity type for unstructured notes (the \"note\" entity type).\n * Used as a sentinel for the default catch-all markdown file shape —\n * no typed frontmatter schema required, content is the entire file body.\n */\nexport const NOTE_ENTITY_TYPE = \"note\";\n\n/**\n * Embedding job data - minimal data for job queue\n * Content is NOT stored to avoid large base64 data in job queue\n * (which would end up in dashboard hydration props JSON)\n * Handler fetches fresh content from entity when processing\n */\nexport interface EmbeddingJobData {\n id: string;\n entityType: string;\n /** Hash of content at job creation time - for staleness detection */\n contentHash: string;\n operation: \"create\" | \"update\";\n}\n\n/**\n * Options for entity mutation operations (create, update, upsert)\n */\nexport interface EntityMutationEventContext {\n conversationId?: string;\n channelId?: string;\n runId?: string;\n toolCallId?: string;\n}\n\nexport interface EntityJobOptions {\n priority?: number;\n maxRetries?: number;\n eventContext?: EntityMutationEventContext;\n}\n\nexport {\n contentVisibilitySchema,\n normalizeContentVisibility,\n getVisibleContentVisibilities,\n isVisibleWithinScope,\n permissionToVisibilityScope,\n canWriteVisibility,\n} from \"./visibility\";\nexport type { ContentVisibility, RawContentVisibility } from \"./visibility\";\n\n/**\n * Options for entity creation (extends EntityJobOptions with deduplication)\n */\nexport interface CreateEntityOptions extends EntityJobOptions {\n deduplicateId?: boolean;\n}\n\n/**\n * Result of an entity mutation that triggers an embedding job.\n * When skipped is true, content was unchanged — no DB write, no event, no embedding job.\n */\nexport interface EntityMutationResult {\n entityId: string;\n jobId: string;\n skipped: boolean;\n}\n\n/**\n * Input for adapter-validated direct creation from finalized markdown.\n */\nexport interface CreateEntityFromMarkdownInput {\n entityType: string;\n id: string;\n markdown: string;\n}\n\n/**\n * Data for storing an embedding for an entity\n */\nexport interface StoreEmbeddingData {\n entityId: string;\n entityType: string;\n embedding: Float32Array;\n contentHash: string;\n}\n\n/**\n * Base entity schema that all entities must extend\n */\nexport const baseEntitySchema: z.ZodObject<{\n id: z.ZodString;\n entityType: z.ZodString;\n content: z.ZodString;\n created: z.ZodString;\n updated: z.ZodString;\n visibility: typeof contentVisibilitySchema;\n metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;\n contentHash: z.ZodString;\n}> = z.object({\n id: z.string(),\n entityType: z.string(),\n content: z.string(),\n created: z.string().datetime(),\n updated: z.string().datetime(),\n visibility: contentVisibilitySchema,\n metadata: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n});\n\nconst canonicalContentVisibilityParserSchema: z.ZodEnum<{\n public: \"public\";\n shared: \"shared\";\n restricted: \"restricted\";\n}> = z.enum([\"public\", \"shared\", \"restricted\"]);\n\n/** Zod 4-owned parser base for entity schemas whose registration slot is structural. */\nexport const baseEntityParserSchema: z.ZodObject<{\n id: z.ZodString;\n entityType: z.ZodString;\n content: z.ZodString;\n created: z.ZodString;\n updated: z.ZodString;\n visibility: z.ZodPipe<\n z.ZodOptional<\n z.ZodUnion<\n readonly [\n typeof canonicalContentVisibilityParserSchema,\n z.ZodLiteral<\"private\">,\n ]\n >\n >,\n z.ZodTransform<ContentVisibility, RawContentVisibility | undefined>\n >;\n metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;\n contentHash: z.ZodString;\n}> = z.object({\n id: z.string(),\n entityType: z.string(),\n content: z.string(),\n created: z.string().datetime(),\n updated: z.string().datetime(),\n visibility: z\n .union([canonicalContentVisibilityParserSchema, z.literal(\"private\")])\n .optional()\n .transform((value): ContentVisibility => {\n if (value === undefined) return \"public\";\n if (value === \"private\") return \"restricted\";\n return value;\n }),\n metadata: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n});\n\n/** Shared empty frontmatter schema for entity types with no typed frontmatter. */\nexport const emptyFrontmatterSchema: z.ZodObject<Record<string, never>> =\n z.object({});\n\nexport type EntitySchema<T> = z.ZodType<T, unknown>;\n/** @deprecated Use EntitySchema<T>. */\nexport type EntitySchemaParser<T> = EntitySchema<T>;\n\nexport type UnknownEntitySchema = EntitySchema<unknown>;\nexport type FrontmatterSchema = z.ZodObject<z.ZodRawShape>;\n\n/**\n * Base entity type - generic to support typed metadata\n * TMetadata defaults to Record<string, unknown> for backward compatibility\n */\nexport interface BaseEntity<TMetadata = Record<string, unknown>> {\n id: string;\n entityType: string;\n content: string;\n created: string;\n updated: string;\n visibility: ContentVisibility;\n metadata: TMetadata;\n /** SHA256 hash of content for change detection */\n contentHash: string;\n}\n\n/**\n * Entity input type for creation - allows partial entities with optional system fields\n * contentHash is excluded because it's computed automatically by the entity service\n */\nexport type EntityInput<T extends BaseEntity> = Omit<\n T,\n \"id\" | \"created\" | \"updated\" | \"contentHash\" | \"visibility\"\n> & {\n id?: string;\n created?: string;\n updated?: string;\n visibility?: RawContentVisibility;\n};\n\n/**\n * Search result type\n */\nexport interface SearchResult<T extends BaseEntity = BaseEntity> {\n entity: T;\n score: number;\n excerpt: string;\n}\n\n/**\n * Normalized system_create input shape used by plugin create interceptors.\n */\nexport interface CreateCoverImageInput {\n generate?: boolean | undefined;\n prompt?: string | undefined;\n}\n\nexport interface CreateFromAttachmentInput {\n kind: \"entity-attachment\";\n sourceEntityType: string;\n sourceEntityId: string;\n attachmentType: string;\n}\n\nexport interface CreateFromUploadInput {\n kind: \"upload\";\n id: string;\n}\n\nexport interface CreateFromConversationMessageInput {\n kind: \"conversation-message\";\n messageId?: string | undefined;\n}\n\nexport type CreateFromInput =\n | CreateFromAttachmentInput\n | CreateFromUploadInput\n | CreateFromConversationMessageInput;\n\nexport type CreateTransform = \"extract-markdown\" | \"preserve\";\n\nexport interface CreateInput {\n entityType: string;\n prompt?: string;\n title?: string;\n content?: string;\n url?: string;\n from?: CreateFromInput;\n transform?: CreateTransform;\n replace?: boolean;\n sourceEntityType?: string;\n sourceEntityId?: string;\n sourceEntityIds?: string[];\n targetEntityType?: string;\n targetEntityId?: string;\n coverImage?: boolean | CreateCoverImageInput;\n}\n\n/**\n * Minimal caller context forwarded to plugin create interceptors.\n */\nexport interface CreateExecutionContext {\n interfaceType: string;\n userId: string;\n channelId?: string;\n channelName?: string;\n}\n\n/**\n * Result returned to system_create when a plugin fully handles creation.\n */\nexport const createResultAttachmentSchema: z.ZodObject<{\n mediaType: z.ZodString;\n url: z.ZodString;\n downloadUrl: z.ZodOptional<z.ZodString>;\n previewUrl: z.ZodOptional<z.ZodString>;\n filename: z.ZodOptional<z.ZodString>;\n sizeBytes: z.ZodOptional<z.ZodNumber>;\n source: z.ZodOptional<\n z.ZodObject<{\n entityType: z.ZodOptional<z.ZodString>;\n entityId: z.ZodOptional<z.ZodString>;\n attachmentType: z.ZodOptional<z.ZodString>;\n }>\n >;\n}> = z.object({\n mediaType: z.string(),\n url: z.string(),\n downloadUrl: z.string().optional(),\n previewUrl: z.string().optional(),\n filename: z.string().optional(),\n sizeBytes: z.number().optional(),\n source: z\n .object({\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n attachmentType: z.string().optional(),\n })\n .optional(),\n});\n\nexport type CreateResultAttachment = z.infer<\n typeof createResultAttachmentSchema\n>;\n\nexport type CreateResult =\n | {\n success: true;\n data: {\n entityId?: string;\n jobId?: string;\n status: string;\n attachment?: CreateResultAttachment;\n };\n }\n | { success: false; error: string };\n\n/**\n * Plugin create interceptors can either fully handle creation,\n * or continue with a rewritten normalized input.\n */\nexport type CreateInterceptionResult =\n | { kind: \"handled\"; result: CreateResult }\n | { kind: \"continue\"; input: CreateInput };\n\nexport type CreateInterceptor = (\n input: CreateInput,\n executionContext: CreateExecutionContext,\n) => Promise<CreateInterceptionResult>;\n\nexport interface UploadSaveInput {\n upload: CreateFromUploadInput;\n title?: string;\n}\n\nexport type UploadSaveHandler = (\n input: UploadSaveInput,\n executionContext: CreateExecutionContext,\n) => Promise<CreateResult>;\n\nexport interface UploadSaveHandlerRegistration {\n entityType: string;\n mediaTypes: string[];\n handler: UploadSaveHandler;\n}\n\n/**\n * Called before an entity is persisted (on create or update). Throws to reject\n * the write with an operator-facing error. Use this for cross-entity invariants\n * the per-entity Zod schema cannot express.\n */\nexport type PersistValidator<T extends BaseEntity = BaseEntity> = (\n entity: T,\n context: { operation: \"create\" | \"update\" },\n) => Promise<void>;\n\n/**\n * Minimal event bus contract used by entity-service for lifecycle events.\n * Kept structural to avoid coupling this package to a concrete messaging service.\n */\nexport interface EntityEventBus {\n send(request: {\n type: string;\n payload: Record<string, unknown>;\n sender: string;\n target?: string;\n metadata?: Record<string, unknown>;\n broadcast?: boolean;\n }): Promise<unknown>;\n}\n\n/**\n * Interface for entity adapter - handles conversion between entities and markdown\n * following the hybrid storage model\n *\n * @template TEntity - The full entity type\n * @template TMetadata - The metadata type (defaults to Record<string, unknown>)\n */\nexport interface EntityAdapter<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n> {\n entityType: string;\n\n /**\n * One declarative sentence describing what this entity type is. This is the\n * data the model reads to select `entityType`, replacing hardcoded example\n * phrasings in system instructions. Required: every type must define itself.\n */\n purpose: string;\n\n schema: EntitySchema<TEntity>;\n\n // Convert entity to markdown content (may include frontmatter for entity-specific fields)\n toMarkdown(entity: TEntity): string;\n\n // Extract entity-specific fields from markdown\n // Returns Partial<TEntity> as core fields come from database\n fromMarkdown(markdown: string): Partial<TEntity>;\n\n // Extract metadata from entity for search/filtering - now strongly typed\n extractMetadata(entity: TEntity): TMetadata;\n\n // Parse frontmatter metadata from markdown\n parseFrontMatter<TFrontmatter>(\n markdown: string,\n schema: { parse(data: unknown): TFrontmatter },\n ): TFrontmatter;\n\n // Generate frontmatter for markdown\n generateFrontMatter(entity: TEntity): string;\n\n /** Optional: Zod schema for frontmatter fields. Used by CMS config generation. */\n frontmatterSchema?: z.ZodObject<z.ZodRawShape>;\n\n /** Optional: Declares this entity type is a singleton (one file, e.g., identity/identity.md). Used by CMS to generate files collection. */\n isSingleton?: boolean;\n\n /** Optional: Whether this entity has a free-form markdown body below frontmatter. Defaults to true. When false, CMS omits the body widget. */\n hasBody?: boolean;\n\n /** Returns a markdown body template with section headings for this entity type. Empty string for free-form entities. */\n getBodyTemplate(): string;\n\n /** Optional: Declares that this entity type supports cover images via coverImageId in frontmatter */\n supportsCoverImage?: boolean;\n\n /** Optional: Extract coverImageId from entity content/frontmatter */\n getCoverImageId?(entity: TEntity): string | undefined;\n\n /**\n * Optional: build the markdown content and metadata for a queued-generation stub.\n * When undefined, this entity type does not support prompt-based queued creation\n * via system_create; the tool will reject the call rather than silently degrade.\n * The returned metadata must satisfy this entity's metadata schema (with\n * status set to \"generating\"); central code only stamps id/timestamps/visibility.\n */\n buildStub?(input: { id: string; title: string }): {\n content: string;\n metadata: TMetadata;\n };\n}\n\n/**\n * Sort field specification for multi-field sorting\n */\nexport interface SortField {\n /** Field to sort by - \"created\", \"updated\", or a metadata field name */\n field: string;\n /** Sort direction */\n direction: \"asc\" | \"desc\";\n /** Sort NULL values before non-NULL values (default: false / SQLite default) */\n nullsFirst?: boolean;\n}\n\n/**\n * List entities options\n * Generic over metadata type for type-safe filtering\n */\nexport interface ListOptions<TMetadata = Record<string, unknown>> {\n limit?: number;\n offset?: number;\n /** Multi-field sorting - supports system fields (created, updated) and metadata fields */\n sortFields?: SortField[];\n filter?: {\n // Typed metadata filter - partial match on metadata fields\n metadata?: Partial<TMetadata>;\n visibilityScope?: ContentVisibility;\n };\n /** Filter to only entities with metadata.status = \"published\" */\n publishedOnly?: boolean;\n}\n\n/**\n * Search options\n */\nexport interface SearchOptions {\n limit?: number;\n offset?: number;\n types?: string[];\n excludeTypes?: string[];\n sortBy?: \"relevance\" | \"created\" | \"updated\";\n sortDirection?: \"asc\" | \"desc\";\n /** Score multipliers per entity type - applied after initial search */\n weight?: Record<string, number>;\n visibilityScope?: ContentVisibility;\n /** Include queued/failed generation stubs in search results (default: false) */\n includeUngenerated?: boolean;\n /** Minimum relevance score to return. Omit for no score cutoff. */\n minScore?: number;\n}\n\n/**\n * Configuration for entity type registration\n */\nexport interface EntityTypeConfig {\n /** Score multiplier for search results (default: 1.0) */\n weight?: number;\n /** Whether to generate embeddings for this entity type (default: true).\n * Set to false for entity types with non-textual content (e.g., images). */\n embeddable?: boolean;\n /** Whether this entity type may be used as source material for derived projections (default: true).\n * Set to false for projection outputs that would create feedback loops. */\n projectionSource?: boolean;\n /** Publish semantics for status-bearing entity types. Statuses listed here\n * represent publication commitment/execution states and require the\n * `publish` entity action when entered or modified. */\n publish?: {\n publishStatuses: string[];\n };\n}\n\n/**\n * Core entity service interface for read-only operations\n * Used by core plugins that need entity access but shouldn't modify entities\n */\nexport interface GetEntityRequest {\n entityType: string;\n id: string;\n /**\n * Optional visibility scope. Undefined fails closed to \"public\" — callers\n * with elevated access must opt up explicitly.\n */\n visibilityScope?: ContentVisibility;\n}\n\nexport type GetEntityRawRequest = GetEntityRequest;\n\nexport interface ListEntitiesRequest {\n entityType: string;\n options?: ListOptions | undefined;\n}\n\nexport interface CountEntitiesRequest {\n entityType: string;\n options?: Pick<ListOptions, \"publishedOnly\" | \"filter\"> | undefined;\n}\n\nexport interface CreateEntityRequest<T extends BaseEntity> {\n entity: EntityInput<T>;\n options?: CreateEntityOptions | undefined;\n}\n\nexport interface CreateEntityFromMarkdownRequest {\n input: CreateEntityFromMarkdownInput;\n options?: CreateEntityOptions | undefined;\n}\n\nexport interface UpdateEntityRequest<T extends BaseEntity> {\n entity: T;\n options?: EntityJobOptions | undefined;\n}\n\nexport interface DeleteEntityRequest {\n entityType: string;\n id: string;\n}\n\nexport interface UpsertEntityRequest<T extends BaseEntity> {\n entity: T;\n options?: EntityJobOptions | undefined;\n}\n\nexport interface EntitySearchRequest {\n query: string;\n options?: SearchOptions | undefined;\n}\n\nexport interface SearchWithDistancesRequest {\n query: string;\n}\n\n/**\n * Context passed to all DataSource operations\n * Contains internal state that should not be mixed with user query parameters\n */\nexport interface BaseDataSourceContext {\n /**\n * Whether to filter to only published/complete content\n * Set by site-builder: true for production, false for preview\n */\n publishedOnly?: boolean;\n\n /**\n * Scoped entity service that auto-applies publishedOnly filter\n * Datasources should use this instead of their injected entityService\n * to ensure consistent filtering behavior across environments\n */\n entityService: EntityService;\n}\n\nexport type DataSourceSchema<T> = z.ZodType<T, unknown>;\n\n/**\n * DataSource Interface\n *\n * Provides data for templates through fetch, generate, or transform operations.\n * DataSources are registered in the DataSourceRegistry and referenced by templates\n * via their dataSourceId property.\n */\nexport interface DataSource {\n /**\n * Unique identifier for this data source\n */\n id: string;\n\n /**\n * Human-readable name for this data source\n */\n name: string;\n\n /**\n * Optional description of what this data source provides\n */\n description?: string;\n\n /**\n * Optional: Fetch existing data\n * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)\n * DataSources validate output using the provided schema\n * @param query - Query parameters for fetching data\n * @param outputSchema - Schema for validating output data\n * @param context - Context with environment\n */\n fetch?: <T>(\n query: unknown,\n outputSchema: z.ZodSchema<T>,\n context: BaseDataSourceContext,\n ) => Promise<T>;\n\n /**\n * Optional: Generate new content\n * Used by data sources that create content (e.g., AI-generated content, reports)\n */\n generate?: <T>(request: unknown, schema: z.ZodSchema<T>) => Promise<T>;\n\n /**\n * Optional: Transform content between formats\n * Used by data sources that convert content (e.g., markdown to HTML, data formatting)\n */\n transform?: <T>(\n content: unknown,\n format: string,\n schema: z.ZodSchema<T>,\n ) => Promise<T>;\n}\n\n/**\n * DataSource capabilities for discovery and validation\n */\nexport interface DataSourceCapabilities {\n canFetch: boolean;\n canGenerate: boolean;\n canTransform: boolean;\n}\n\nexport interface ICoreEntityService {\n // Read-only operations\n getEntity<T extends BaseEntity>(request: GetEntityRequest): Promise<T | null>;\n\n /**\n * Get entity without content resolution (raw)\n * Used internally to avoid recursion when resolving image references\n */\n getEntityRaw<T extends BaseEntity>(\n request: GetEntityRawRequest,\n ): Promise<T | null>;\n\n listEntities<T extends BaseEntity>(\n request: ListEntitiesRequest,\n ): Promise<T[]>;\n\n search<T extends BaseEntity = BaseEntity>(\n request: EntitySearchRequest,\n ): Promise<SearchResult<T>[]>;\n\n // Entity type information\n getEntityTypes(): string[];\n hasEntityType(type: string): boolean;\n\n // Entity counts\n countEntities(request: CountEntitiesRequest): Promise<number>;\n /**\n * Group counts by entity type. Fails closed: undefined visibilityScope\n * filters to public-only counts so aggregate insights cannot reveal\n * non-public entity existence.\n */\n getEntityCounts(\n visibilityScope?: ContentVisibility,\n ): Promise<Array<{ entityType: string; count: number }>>;\n\n /** Get configuration for a specific entity type */\n getEntityTypeConfig(type: string): EntityTypeConfig;\n\n /** Get weight map for all registered entity types with non-default weights */\n getWeightMap(): Record<string, number>;\n}\n\n/**\n * Entity service interface for managing brain entities\n */\nexport interface IEntitiesNamespace {\n /** Register a new entity type with schema and adapter */\n register<TEntity extends BaseEntity>(\n entityType: string,\n schema: EntitySchema<TEntity>,\n adapter: EntityAdapter<TEntity>,\n config?: EntityTypeConfig,\n ): void;\n\n /**\n * Get the adapter for an entity type.\n *\n * Returns the structural `EntityAdapter<BaseEntity>` view — namespace\n * consumers don't narrow by entity type. For typed access tied to a\n * specific `TEntity`, use the underlying `EntityRegistry.getAdapter<T>`\n * directly (see `entity-serializer.ts`).\n */\n getAdapter(entityType: string): EntityAdapter<BaseEntity> | undefined;\n\n /** Extend an adapter's frontmatterSchema with additional fields */\n extendFrontmatterSchema(\n type: string,\n extension: z.ZodObject<z.ZodRawShape>,\n ): void;\n\n /** Get effective frontmatter schema (base + extensions) for an entity type */\n getEffectiveFrontmatterSchema(\n type: string,\n ): z.ZodObject<z.ZodRawShape> | undefined;\n\n /** Update an existing entity */\n update<TEntity extends BaseEntity>(\n entity: TEntity,\n ): Promise<{ entityId: string; jobId: string }>;\n\n /** Register a data source for dynamic content */\n registerDataSource(dataSource: DataSource): void;\n\n /** Register a create interceptor for this plugin's entity type */\n registerCreateInterceptor(\n entityType: string,\n interceptor: CreateInterceptor,\n ): void;\n\n /** Register a raw-upload durable save handler for this plugin's entity type */\n registerUploadSaveHandler(registration: UploadSaveHandlerRegistration): void;\n\n /** Look up the registered upload-save handler claiming a media type */\n getUploadSaveHandler(\n mediaType: string,\n ): UploadSaveHandlerRegistration | undefined;\n}\n\nexport interface EmbeddingBackfillResult {\n queued: number;\n skipped: number;\n}\n\nexport interface EmbeddingFailureReference {\n entityId: string;\n entityType: string;\n contentHash: string;\n}\n\nexport interface EmbeddingIndexStats {\n missingEmbeddings: number;\n staleEmbeddings: number;\n failedEmbeddings: number;\n /** Entities whose type generates embeddings (non-embeddable types excluded). */\n embeddableEntities: number;\n /** Embeddable entities whose embedding is present and current. */\n embeddedEntities: number;\n}\n\nexport interface IndexReadinessOptions {\n timeoutMs: number;\n intervalMs?: number;\n}\n\nexport interface IndexReadinessStatus extends EmbeddingIndexStats {\n ready: boolean;\n degraded: boolean;\n activeEmbeddingJobs: number;\n}\n\nexport interface EntityService extends ICoreEntityService {\n // Mutations\n createEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n ): Promise<EntityMutationResult>;\n createEntityFromMarkdown(\n request: CreateEntityFromMarkdownRequest,\n ): Promise<EntityMutationResult>;\n updateEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n ): Promise<EntityMutationResult>;\n deleteEntity(request: DeleteEntityRequest): Promise<boolean>;\n upsertEntity<T extends BaseEntity>(\n request: UpsertEntityRequest<T>,\n ): Promise<EntityMutationResult & { created: boolean }>;\n storeEmbedding(data: StoreEmbeddingData): Promise<void>;\n backfillMissingEmbeddings(): Promise<EmbeddingBackfillResult>;\n isIndexReady(): boolean;\n awaitIndexReady(\n options: IndexReadinessOptions,\n ): Promise<IndexReadinessStatus>;\n\n // Serialization\n serializeEntity(entity: BaseEntity): string;\n deserializeEntity(markdown: string, entityType: string): Partial<BaseEntity>;\n\n // Counts\n countEmbeddings(): Promise<number>;\n\n // Diagnostics\n searchWithDistances(\n request: SearchWithDistancesRequest,\n ): Promise<Array<{ entityId: string; entityType: string; distance: number }>>;\n\n // Lifecycle\n initialize(): Promise<void>;\n\n // Job status\n getAsyncJobStatus(jobId: string): Promise<{\n status: \"pending\" | \"processing\" | \"completed\" | \"failed\";\n error?: string;\n } | null>;\n}\n\n/**\n * Entity Registry interface for managing entity types and their schemas/adapters\n */\nexport interface EntityRegistry {\n registerEntityType<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n >(\n type: string,\n schema: UnknownEntitySchema,\n adapter: EntityAdapter<TEntity, TMetadata>,\n config?: EntityTypeConfig,\n ): void;\n\n getSchema(type: string): UnknownEntitySchema;\n\n getAdapter<\n TEntity extends BaseEntity<TMetadata>,\n TMetadata = Record<string, unknown>,\n >(\n type: string,\n ): EntityAdapter<TEntity, TMetadata>;\n\n hasEntityType(type: string): boolean;\n\n validateEntity(type: string, entity: unknown): BaseEntity;\n\n getAllEntityTypes(): string[];\n\n /** Get configuration for a specific entity type */\n getEntityTypeConfig(type: string): EntityTypeConfig;\n\n /** Get weight map for all registered entity types with non-default weights */\n getWeightMap(): Record<string, number>;\n\n registerCreateInterceptor(type: string, interceptor: CreateInterceptor): void;\n\n getCreateInterceptor(type: string): CreateInterceptor | undefined;\n\n registerUploadSaveHandler(registration: UploadSaveHandlerRegistration): void;\n\n getUploadSaveHandler(\n mediaType: string,\n ): UploadSaveHandlerRegistration | undefined;\n\n registerPersistValidator(type: string, validator: PersistValidator): void;\n\n getPersistValidator(type: string): PersistValidator | undefined;\n\n /**\n * Extend an adapter's frontmatterSchema with additional fields.\n * Used by plugins to add domain-specific fields (e.g., professional-site adds tagline to profile).\n * Extensions are merged into the effective schema returned by getEffectiveFrontmatterSchema().\n */\n extendFrontmatterSchema(\n type: string,\n extension: z.ZodObject<z.ZodRawShape>,\n ): void;\n\n /**\n * Get the effective frontmatter schema for an entity type,\n * with all registered extensions merged in.\n * Returns undefined if the adapter has no frontmatterSchema.\n */\n getEffectiveFrontmatterSchema(\n type: string,\n ): z.ZodObject<z.ZodRawShape> | undefined;\n}\n\n/**\n * Database configuration for entity service\n */\nexport type { DbConfig as EntityDbConfig } from \"@brains/contracts\";\n",
166
166
  "import { openSync, writeSync } from \"node:fs\";\n\n/**\n * Logger interface for consistent logging across the application\n * Simplified version without Winston dependency\n */\n\n/**\n * Log levels\n */\nexport const LogLevel = {\n SILLY: 0,\n VERBOSE: 1,\n DEBUG: 2,\n INFO: 3,\n WARN: 4,\n ERROR: 5,\n NONE: 6,\n} as const;\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\n/**\n * Logger implementation with Component Interface Standardization pattern\n */\nexport type LogFormat = \"text\" | \"json\";\n\nexport interface LoggerOptions {\n level?: LogLevel;\n context?: string;\n useStderr?: boolean;\n format?: LogFormat;\n /** Path to a log file. Always writes JSON, one line per entry. */\n logFile?: string;\n}\n\nexport class Logger {\n /** The singleton instance */\n private static instance: Logger | null = null;\n\n private level: LogLevel;\n private context: string | undefined;\n private useStderr: boolean;\n private format: LogFormat;\n private logFile: string | undefined;\n private fileHandle: number | undefined;\n\n /**\n * Private constructor to enforce singleton pattern\n */\n private constructor(options: LoggerOptions = {}, fileHandle?: number) {\n this.level = options.level ?? LogLevel.INFO;\n this.context = options.context ?? undefined;\n this.useStderr = options.useStderr ?? false;\n this.format = options.format ?? \"text\";\n this.logFile = options.logFile;\n\n if (fileHandle !== undefined) {\n // Reuse parent's file handle (child logger)\n this.fileHandle = fileHandle;\n } else if (this.logFile) {\n try {\n this.fileHandle = openSync(this.logFile, \"a\");\n } catch {\n // Silently fail — logging should never crash the app\n }\n }\n }\n\n /**\n * Get the singleton instance of Logger\n */\n public static getInstance(options?: LoggerOptions): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger(options);\n } else if (options?.useStderr !== undefined) {\n // Update useStderr if explicitly provided\n Logger.instance.useStderr = options.useStderr;\n }\n return Logger.instance;\n }\n\n /**\n * Reset the singleton instance (primarily for testing)\n */\n public static resetInstance(): void {\n Logger.instance = null;\n }\n\n /**\n * Create a fresh instance without affecting the singleton\n */\n public static createFresh(options?: LoggerOptions): Logger {\n return new Logger(options);\n }\n\n /**\n * Format a log entry for output.\n * Text: [timestamp] [context] message\n * JSON: {\"ts\":\"...\",\"level\":\"...\",\"ctx\":\"...\",\"msg\":\"...\",\"data\":[...]}\n */\n private formatEntry(level: string, message: string, args: unknown[]): string {\n const timestamp = new Date().toISOString();\n if (this.format === \"json\") {\n const entry: Record<string, unknown> = {\n ts: timestamp,\n level,\n msg: message,\n };\n if (this.context) entry[\"ctx\"] = this.context;\n if (args.length > 0) entry[\"data\"] = args;\n return JSON.stringify(entry);\n }\n return this.context\n ? `[${timestamp}] [${this.context}] ${message}`\n : `[${timestamp}] ${message}`;\n }\n\n /**\n * Log a message at the 'silly' level\n */\n /**\n * Write a formatted log entry to the appropriate output stream.\n * JSON format: single string argument (no spread).\n * Text format: message + spread args for console formatting.\n */\n private write(\n consoleFn: (...data: unknown[]) => void,\n level: string,\n message: string,\n args: unknown[],\n ): void {\n // Console output\n if (this.format === \"json\") {\n consoleFn(this.formatEntry(level, message, args));\n } else {\n if (args.length > 0) {\n consoleFn(this.formatEntry(level, message, []), ...args);\n } else {\n consoleFn(this.formatEntry(level, message, []));\n }\n }\n\n // File output — always JSON\n if (this.fileHandle !== undefined) {\n const jsonLine = this.formatJsonEntry(level, message, args);\n try {\n writeSync(this.fileHandle, jsonLine + \"\\n\");\n } catch {\n // Silently fail\n }\n }\n }\n\n /**\n * Format a JSON log entry (used for file output regardless of console format).\n */\n private formatJsonEntry(\n level: string,\n message: string,\n args: unknown[],\n ): string {\n const entry: Record<string, unknown> = {\n ts: new Date().toISOString(),\n level,\n msg: message,\n };\n if (this.context) entry[\"ctx\"] = this.context;\n if (args.length > 0) entry[\"data\"] = args;\n return JSON.stringify(entry);\n }\n\n public silly(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.SILLY) {\n this.write(console.debug.bind(console), \"silly\", message, args);\n }\n }\n\n public verbose(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.VERBOSE) {\n this.write(console.debug.bind(console), \"verbose\", message, args);\n }\n }\n\n public debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n this.write(console.debug.bind(console), \"debug\", message, args);\n }\n }\n\n public info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n const fn = this.useStderr\n ? console.error.bind(console)\n : console.info.bind(console);\n this.write(fn, \"info\", message, args);\n }\n }\n\n public warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n this.write(console.warn.bind(console), \"warn\", message, args);\n }\n }\n\n public error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n this.write(console.error.bind(console), \"error\", message, args);\n }\n }\n\n /**\n * Create a child logger with a specific context\n */\n public child(context: string): Logger {\n // Pass file handle directly so children don't open new handles\n const child = new Logger(\n {\n level: this.level,\n context,\n useStderr: this.useStderr,\n format: this.format,\n },\n this.fileHandle,\n );\n return child;\n }\n\n /**\n * Configure the logger to use stderr for all output\n * Useful for MCP servers that need stdout for JSON-RPC\n */\n public setUseStderr(useStderr: boolean): void {\n this.useStderr = useStderr;\n }\n}\n\n// Export default logger instance\nconst defaultLogger: Logger = Logger.getInstance();\n\nexport default defaultLogger;\n",
167
167
  "import { Logger } from \"@brains/utils/logger\";\nimport { type ProgressReporter } from \"@brains/utils/progress\";\nimport { z } from \"@brains/utils/zod\";\nimport type {\n EntityService as IEntityService,\n EmbeddingJobData,\n EntityEventBus,\n} from \"../types\";\nimport type { IEmbeddingService } from \"../embedding-types\";\nimport type { JobHandler } from \"@brains/job-queue\";\nimport { internalFullScope } from \"../internal-scope\";\n/**\n * Zod schema for embedding job data validation\n * Content is NOT in job data - fetched fresh from entity when processing\n */\nconst embeddingJobDataSchema = z.object({\n id: z.string().min(1, \"Entity ID is required\"),\n entityType: z.string().min(1, \"Entity type is required\"),\n contentHash: z.string().min(1, \"Content hash is required\"),\n operation: z.enum([\"create\", \"update\"]),\n});\n\n/**\n * Job handler for embedding generation\n * Processes entities to generate embeddings using the EmbeddingService\n * Implements Component Interface Standardization pattern\n */\nexport class EmbeddingJobHandler implements JobHandler<\"embedding\"> {\n private static instance: EmbeddingJobHandler | null = null;\n private logger: Logger;\n private embeddingService: IEmbeddingService;\n private entityService: IEntityService;\n private messageBus?: EntityEventBus;\n\n /**\n * Get the singleton instance\n */\n public static getInstance(\n entityService: IEntityService,\n embeddingService: IEmbeddingService,\n messageBus?: EntityEventBus,\n ): EmbeddingJobHandler {\n EmbeddingJobHandler.instance ??= new EmbeddingJobHandler(\n entityService,\n embeddingService,\n messageBus,\n );\n return EmbeddingJobHandler.instance;\n }\n\n /**\n * Reset the singleton instance (primarily for testing)\n */\n public static resetInstance(): void {\n EmbeddingJobHandler.instance = null;\n }\n\n /**\n * Create a fresh instance without affecting the singleton\n */\n public static createFresh(\n entityService: IEntityService,\n embeddingService: IEmbeddingService,\n messageBus?: EntityEventBus,\n ): EmbeddingJobHandler {\n return new EmbeddingJobHandler(entityService, embeddingService, messageBus);\n }\n\n /**\n * Private constructor to enforce singleton pattern\n */\n private constructor(\n entityService: IEntityService,\n embeddingService: IEmbeddingService,\n messageBus?: EntityEventBus,\n ) {\n this.logger = Logger.getInstance().child(\"EmbeddingJobHandler\");\n this.embeddingService = embeddingService;\n this.entityService = entityService;\n if (messageBus) {\n this.messageBus = messageBus;\n }\n }\n\n /**\n * Process an embedding job\n * Generates embedding for entity content and stores it in the embeddings table\n * Entity must already exist in entities table (stored immediately by createEntity/updateEntity)\n */\n public async process(\n data: EmbeddingJobData,\n jobId: string,\n // Embedding jobs are enqueued silent, so progress is never emitted\n _progressReporter: ProgressReporter,\n ): Promise<void> {\n try {\n this.logger.debug(\"Processing embedding job\", {\n jobId,\n entityId: data.id,\n entityType: data.entityType,\n contentHash: data.contentHash,\n });\n\n // Fetch fresh entity - content is NOT stored in job data to avoid\n // large base64 data bloating job queue and dashboard hydration props.\n const currentEntity = await this.entityService.getEntity({\n entityType: data.entityType,\n id: data.id,\n visibilityScope: internalFullScope(\n \"embedding regeneration must index every entity, no user surface\",\n ),\n });\n\n if (!currentEntity) {\n this.logger.warn(\"Entity no longer exists, skipping embedding job\", {\n jobId,\n entityId: data.id,\n entityType: data.entityType,\n operation: data.operation,\n });\n return;\n }\n\n // Check if content has changed since job was queued (staleness detection)\n if (currentEntity.contentHash !== data.contentHash) {\n this.logger.info(\n \"Entity content changed since job created, skipping stale embedding\",\n {\n jobId,\n entityId: data.id,\n entityType: data.entityType,\n jobContentHash: data.contentHash,\n currentContentHash: currentEntity.contentHash,\n },\n );\n return;\n }\n\n // Generate embedding using fresh content from entity\n const { embedding, usage } =\n await this.embeddingService.generateEmbedding(currentEntity.content);\n\n // Log usage event for monitoring\n this.logger.info(\"ai:usage\", {\n operation: \"embedding\",\n provider: \"openai\",\n model: \"text-embedding-3-small\",\n inputTokens: usage.tokens,\n outputTokens: 0,\n });\n\n // Store the embedding in the embeddings table\n await this.entityService.storeEmbedding({\n entityId: data.id,\n entityType: data.entityType,\n embedding,\n contentHash: data.contentHash,\n });\n\n // Emit entity:embedding:ready event after successful save\n // Note: entity:created is now emitted by createEntity() when entity is first persisted\n if (this.messageBus) {\n this.logger.debug(\n `Emitting entity:embedding:ready event for ${data.entityType}:${data.id}`,\n );\n\n await this.messageBus.send({\n type: \"entity:embedding:ready\",\n payload: {\n entityType: data.entityType,\n entityId: data.id,\n entity: currentEntity,\n },\n sender: \"entity-service\",\n broadcast: true,\n });\n }\n\n this.logger.debug(\"Embedding job completed successfully\", {\n jobId,\n entityId: data.id,\n embeddingDimensions: embedding.length,\n });\n } catch (error) {\n this.logger.error(\"Embedding job failed\", {\n jobId,\n entityId: data.id,\n entityType: data.entityType,\n error,\n });\n throw error;\n }\n }\n\n /**\n * Handle embedding job errors\n */\n public async onError(\n error: Error,\n data: EmbeddingJobData,\n jobId: string,\n ): Promise<void> {\n this.logger.error(\"Embedding job error handler called\", {\n jobId,\n entityId: data.id,\n entityType: data.entityType,\n contentHash: data.contentHash,\n errorMessage: error.message,\n errorStack: error.stack,\n });\n }\n\n /**\n * Validate and parse embedding job data using Zod schema\n * Ensures type safety and data integrity\n */\n public validateAndParse(data: unknown): EmbeddingJobData | null {\n const parsed = embeddingJobDataSchema.safeParse(data);\n if (!parsed.success) {\n this.logger.warn(\"Invalid embedding job data\", {\n data,\n validationError: parsed.error.issues,\n });\n return null;\n }\n\n this.logger.debug(\"Embedding job data validation successful\", {\n entityId: parsed.data.id,\n entityType: parsed.data.entityType,\n contentHash: parsed.data.contentHash,\n });\n\n return parsed.data;\n }\n}\n",
168
168
  "import type { EntityDB } from \"./db\";\nimport {\n getVisibleContentVisibilities,\n type BaseEntity,\n type ContentVisibility,\n type SearchResult,\n type SearchOptions,\n} from \"./types\";\nimport type { IEmbeddingService } from \"./embedding-types\";\nimport type { EntitySerializer } from \"./entity-serializer\";\nimport { type Logger } from \"@brains/utils/logger\";\nimport { z } from \"@brains/utils/zod\";\nimport { sql, and, desc, inArray, type SQL } from \"drizzle-orm\";\nimport { entities } from \"./schema/entities\";\n\nexport const MAX_SEARCH_QUERY_CHARS = 12_000;\nconst MAX_VECTOR_DISTANCE = 0.82;\n\nexport function prepareSearchQuery(\n query: string,\n logger?: Logger,\n maxChars: number = MAX_SEARCH_QUERY_CHARS,\n): string {\n const normalizedQuery = query.trim().replace(/\\s+/g, \" \");\n\n if (normalizedQuery.length <= maxChars) {\n return normalizedQuery;\n }\n\n logger?.warn(\"Truncating search query that exceeds max length\", {\n originalLength: normalizedQuery.length,\n truncatedLength: maxChars,\n });\n\n return normalizedQuery.slice(0, maxChars);\n}\n\n/**\n * Schema for search options (excluding tags)\n */\nconst searchOptionsSchema = z.object({\n limit: z.number().int().positive().optional().default(20),\n offset: z.number().int().min(0).optional().default(0),\n types: z.array(z.string()).optional().default([]),\n excludeTypes: z.array(z.string()).optional().default([]),\n weight: z.record(z.string(), z.number()).optional(),\n visibilityScope: z.enum([\"public\", \"shared\", \"restricted\"]).optional(),\n includeUngenerated: z.boolean().optional().default(false),\n minScore: z.number().min(0).optional(),\n});\n\nconst entityMetadataSchema = z.preprocess(\n (value) => {\n if (typeof value !== \"string\") return value;\n return JSON.parse(value);\n },\n z.record(z.string(), z.unknown()),\n);\n\n/**\n * EntitySearch handles all search operations for entities\n * Extracted from EntityService for single responsibility\n */\nexport class EntitySearch {\n private db: EntityDB;\n private embeddingService: IEmbeddingService;\n private serializer: EntitySerializer;\n private logger: Logger;\n\n constructor(\n db: EntityDB,\n embeddingService: IEmbeddingService,\n serializer: EntitySerializer,\n logger: Logger,\n ) {\n this.db = db;\n this.embeddingService = embeddingService;\n this.serializer = serializer;\n this.logger = logger.child(\"EntitySearch\");\n }\n\n /**\n * Search entities by query using vector similarity\n */\n public async search<T extends BaseEntity = BaseEntity>(\n query: string,\n options?: SearchOptions,\n ): Promise<SearchResult<T>[]> {\n const validatedOptions = searchOptionsSchema.parse(options ?? {});\n const {\n limit,\n offset,\n types,\n excludeTypes,\n weight,\n visibilityScope,\n includeUngenerated,\n minScore,\n } = validatedOptions;\n\n // Check if we have weights to apply\n const hasWeights = weight && Object.keys(weight).length > 0;\n const preparedQuery = prepareSearchQuery(query, this.logger);\n\n this.logger.debug(\n `Searching entities with query (${preparedQuery.length} chars)`,\n );\n\n // Generate embedding for the query\n const { embedding: queryEmbedding } =\n await this.embeddingService.generateEmbedding(preparedQuery);\n\n // Convert Float32Array to JSON array for SQL\n const embeddingArray = JSON.stringify(Array.from(queryEmbedding));\n\n const weightMultiplier = this.buildWeightMultiplier(\n hasWeights ? weight : undefined,\n );\n\n // Build type filter conditions for drizzle\n const typeConditions: SQL[] = [];\n if (types.length > 0) {\n typeConditions.push(\n sql`${entities.entityType} IN (${sql.join(\n types.map((t) => sql`${t}`),\n sql`, `,\n )})`,\n );\n }\n if (excludeTypes.length > 0) {\n typeConditions.push(\n sql`${entities.entityType} NOT IN (${sql.join(\n excludeTypes.map((t) => sql`${t}`),\n sql`, `,\n )})`,\n );\n }\n\n return this.searchWithAttachedDb<T>(\n embeddingArray,\n weightMultiplier,\n [\n ...typeConditions,\n ...this.buildVisibilityConditions(visibilityScope),\n ...this.buildGenerationStatusConditions(includeUngenerated),\n ],\n limit,\n offset,\n preparedQuery,\n minScore,\n );\n }\n\n private buildVisibilityConditions(\n visibilityScope?: ContentVisibility,\n ): SQL[] {\n // Fail closed: undefined scope filters to public-only.\n const scope: ContentVisibility = visibilityScope ?? \"public\";\n if (scope === \"restricted\") {\n return [];\n }\n return [inArray(entities.visibility, getVisibleContentVisibilities(scope))];\n }\n\n private buildGenerationStatusConditions(includeUngenerated: boolean): SQL[] {\n if (includeUngenerated) return [];\n return [\n sql`(json_extract(${entities.metadata}, '$.status') IS NULL OR json_extract(${entities.metadata}, '$.status') NOT IN ('generating', 'failed'))`,\n ];\n }\n\n /**\n * FTS5 boost weight. When a keyword match is found, this fraction of the\n * final score comes from FTS5 rank, the rest from vector similarity.\n * 0.3 = 30% keyword, 70% semantic.\n */\n private static readonly FTS_ALPHA = 0.3;\n\n /**\n * Build a parameterized CASE expression for entity-type score multipliers.\n * Weight keys may be caller-provided, so avoid raw SQL string interpolation.\n */\n private buildWeightMultiplier(weight?: Record<string, number>): SQL {\n const entries = Object.entries(weight ?? {}).filter(([, multiplier]) =>\n Number.isFinite(multiplier),\n );\n\n if (entries.length === 0) {\n return sql`1.0`;\n }\n\n const cases = entries.map(\n ([entityType, multiplier]) =>\n sql`WHEN ${entities.entityType} = ${entityType} THEN ${multiplier}`,\n );\n\n return sql`CASE ${sql.join(cases, sql` `)} ELSE 1.0 END`;\n }\n\n /**\n * Execute search against an attached embedding database (aliased as \"emb\").\n */\n private async searchWithAttachedDb<T extends BaseEntity = BaseEntity>(\n embeddingArray: string,\n weightMultiplier: SQL,\n typeConditions: SQL[],\n limit: number,\n offset: number,\n query: string,\n minScore: number | undefined,\n ): Promise<SearchResult<T>[]> {\n const alpha = EntitySearch.FTS_ALPHA;\n\n // Vector similarity score (0..1, higher is better)\n const vectorScore = sql<number>`(1.0 - vector_distance_cos(emb_e.embedding, vector32(${embeddingArray})) / 2.0) * (${weightMultiplier})`;\n const distanceExpr = sql<number>`vector_distance_cos(emb_e.embedding, vector32(${embeddingArray}))`;\n\n // FTS5 keyword boost via subquery: 1.0 when matched, 0.0 when not.\n // Wrap in double quotes for phrase matching — prevents special characters\n // (?, *, OR, AND, etc.) from being parsed as FTS5 operators.\n const ftsQuery = '\"' + query.replace(/\"/g, '\"\"') + '\"';\n const ftsBoost = sql<number>`CASE WHEN EXISTS (\n SELECT 1 FROM entity_fts WHERE entity_fts MATCH ${ftsQuery}\n AND entity_id = ${entities.id} AND entity_type = ${entities.entityType}\n ) THEN 1.0 ELSE 0.0 END`;\n\n // Combined score: (1-α)*vector + α*keyword_match\n const combinedScore = sql<number>`(${1 - alpha} * ${vectorScore}) + (${alpha} * ${ftsBoost})`;\n\n const results = await this.db\n .select({\n id: entities.id,\n entityType: entities.entityType,\n content: entities.content,\n contentHash: entities.contentHash,\n visibility: entities.visibility,\n created: entities.created,\n updated: entities.updated,\n metadata: entities.metadata,\n distance: distanceExpr,\n weighted_score: combinedScore,\n })\n .from(entities)\n .innerJoin(\n sql`emb.embeddings AS emb_e`,\n sql`${entities.id} = emb_e.entity_id AND ${entities.entityType} = emb_e.entity_type`,\n )\n .where(\n and(\n sql`${distanceExpr} < ${MAX_VECTOR_DISTANCE}`,\n ...(minScore !== undefined\n ? [sql`${combinedScore} >= ${minScore}`]\n : []),\n ...typeConditions,\n ),\n )\n .orderBy(desc(combinedScore))\n .limit(limit)\n .offset(offset);\n\n return this.mapSearchResults<T>(results, query);\n }\n\n /**\n * Search entities by type and query\n */\n public async searchEntities(\n entityType: string,\n query: string,\n options?: { limit?: number },\n ): Promise<SearchResult[]> {\n // Build search options with the entity type filter\n const searchOptions: SearchOptions = {\n types: [entityType],\n limit: options?.limit ?? 20,\n offset: 0,\n sortBy: \"relevance\",\n sortDirection: \"desc\",\n };\n\n return this.search(query, searchOptions);\n }\n\n /**\n * Return all embedded entities with their raw cosine distance to the query.\n * No threshold filter — used for diagnostics and threshold tuning.\n * Results sorted by distance ascending (closest first).\n */\n public async searchWithDistances(\n query: string,\n ): Promise<\n Array<{ entityId: string; entityType: string; distance: number }>\n > {\n const preparedQuery = prepareSearchQuery(query, this.logger);\n const { embedding: queryEmbedding } =\n await this.embeddingService.generateEmbedding(preparedQuery);\n const embeddingArray = JSON.stringify(Array.from(queryEmbedding));\n\n const distanceExpr = sql<number>`vector_distance_cos(emb_e.embedding, vector32(${embeddingArray}))`;\n\n const results = await this.db\n .select({\n entityId: entities.id,\n entityType: entities.entityType,\n distance: distanceExpr,\n })\n .from(entities)\n .innerJoin(\n sql`emb.embeddings AS emb_e`,\n sql`${entities.id} = emb_e.entity_id AND ${entities.entityType} = emb_e.entity_type`,\n )\n .orderBy(sql`${distanceExpr} ASC`);\n\n return results;\n }\n\n /**\n * Transform raw query rows into SearchResult objects\n */\n private mapSearchResults<T extends BaseEntity = BaseEntity>(\n results: Array<{\n id: string;\n entityType: string;\n content: string;\n contentHash: string;\n visibility: ContentVisibility;\n created: number;\n updated: number;\n metadata: unknown;\n weighted_score: number;\n }>,\n query: string,\n ): SearchResult<T>[] {\n const searchResults: SearchResult<T>[] = [];\n\n for (const row of results) {\n try {\n const metadata = entityMetadataSchema.parse(row.metadata);\n\n const entity = this.serializer.reconstructEntity<T>({\n id: row.id,\n entityType: row.entityType,\n content: row.content,\n contentHash: row.contentHash,\n visibility: row.visibility,\n created: row.created,\n updated: row.updated,\n metadata,\n });\n\n searchResults.push({\n entity,\n score: row.weighted_score,\n excerpt: this.createExcerpt(row.content, query),\n });\n } catch (error) {\n this.logger.error(`Failed to parse entity during search: ${error}`);\n }\n }\n\n const queryPreview =\n query.length > 50 ? query.substring(0, 50) + \"...\" : query;\n this.logger.debug(\n `Found ${searchResults.length} results for query \"${queryPreview}\"`,\n );\n\n return searchResults;\n }\n\n /**\n * Create an excerpt from content based on query\n */\n private createExcerpt(content: string, query: string): string {\n const maxLength = 200;\n const queryLower = query.toLowerCase();\n const contentLower = content.toLowerCase();\n\n // Find the position of the query in the content\n const position = contentLower.indexOf(queryLower);\n\n if (position !== -1) {\n // Extract text around the query\n const start = Math.max(0, position - 50);\n const end = Math.min(content.length, position + queryLower.length + 50);\n let excerpt = content.slice(start, end);\n\n // Add ellipsis if needed\n if (start > 0) excerpt = \"...\" + excerpt;\n if (end < content.length) excerpt = excerpt + \"...\";\n\n return excerpt;\n }\n\n // If query not found, return beginning of content\n return (\n content.slice(0, maxLength) + (content.length > maxLength ? \"...\" : \"\")\n );\n }\n}\n",
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var Pc=Object.defineProperty;var Jc=(n)=>n;function dc(n,i){this[n]=Jc.bind(null,i)}var s=(n,i)=>{for(var o in i)Pc(n,o,{get:i[o],enumerable:!0,configurable:!0,set:dc.bind(i,o)})};function Ec(n){return n}var wg={name:"@rizom/brain",version:"0.2.0-alpha.145",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/sdk":"^1.29.0","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20",postcss:"^8.5.15",preact:"^10.27.2","preact-render-to-string":"^6.7.0",tailwindcss:"^4.3.1",zod:"^4.1.8"},devDependencies:{"@brains/app":"workspace:*","@brains/build-tools":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.3.14",rollup:"^4.62.0","rollup-plugin-dts":"^6.4.1",typescript:"^6.0.3"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","playwright-core":"^1.61.0","react-devtools-core":"^7.0.1",sharp:"^0.35.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Gc=wg.version;var _t={};s(_t,{xor:()=>al,xid:()=>ml,void:()=>xl,uuidv7:()=>cl,uuidv6:()=>ll,uuidv4:()=>gl,uuid:()=>$l,util:()=>k,url:()=>bl,uppercase:()=>Vr,unknown:()=>Sr,union:()=>gt,undefined:()=>Hl,ulid:()=>wl,uint64:()=>Fl,uint32:()=>Yl,tuple:()=>T$,trim:()=>Tr,treeifyError:()=>Et,transform:()=>ct,toUpperCase:()=>Br,toLowerCase:()=>Fr,toJSONSchema:()=>Ki,templateLiteral:()=>lc,symbol:()=>Bl,superRefine:()=>Ig,success:()=>vc,stringbool:()=>wc,stringFormat:()=>Gl,string:()=>On,strictObject:()=>Cl,startsWith:()=>qr,slugify:()=>Hr,size:()=>Dr,setErrorMap:()=>g4,set:()=>nc,safeParseAsync:()=>I$,safeParse:()=>b$,safeEncodeAsync:()=>S$,safeEncode:()=>w$,safeDecodeAsync:()=>N$,safeDecode:()=>m$,registry:()=>ui,regexes:()=>M,regex:()=>Wr,refine:()=>bg,record:()=>F$,readonly:()=>vg,property:()=>Ai,promise:()=>cc,prettifyError:()=>Lt,preprocess:()=>Sc,prefault:()=>p$,positive:()=>Ei,pipe:()=>Mi,partialRecord:()=>pl,parseAsync:()=>c$,parse:()=>l$,overwrite:()=>f,optional:()=>Pn,object:()=>Zl,number:()=>O$,nullish:()=>ec,nullable:()=>Jn,null:()=>E$,normalize:()=>Qr,nonpositive:()=>Gi,nonoptional:()=>s$,nonnegative:()=>Wi,never:()=>$t,negative:()=>Li,nativeEnum:()=>ic,nanoid:()=>Ul,nan:()=>uc,multipleOf:()=>ur,minSize:()=>y,minLength:()=>nr,mime:()=>Yr,meta:()=>kc,maxSize:()=>$r,maxLength:()=>wr,map:()=>rc,mac:()=>zl,lte:()=>x,lt:()=>h,lowercase:()=>Ar,looseRecord:()=>sl,looseObject:()=>hl,locales:()=>mn,literal:()=>tc,length:()=>mr,lazy:()=>gg,ksuid:()=>Sl,keyof:()=>fl,jwt:()=>Ll,json:()=>mc,iso:()=>Rr,ipv6:()=>Ol,ipv4:()=>Nl,invertCodec:()=>gc,intersection:()=>Y$,int64:()=>Tl,int32:()=>Kl,int:()=>Hi,instanceof:()=>Dc,includes:()=>Xr,httpUrl:()=>Il,hostname:()=>Wl,hex:()=>Al,hash:()=>Vl,guid:()=>ul,gte:()=>Y,gt:()=>a,globalRegistry:()=>V,getErrorMap:()=>l4,function:()=>bc,fromJSONSchema:()=>zc,formatError:()=>$n,float64:()=>ql,float32:()=>Xl,flattenError:()=>un,file:()=>oc,exactOptional:()=>Z$,enum:()=>lt,endsWith:()=>Kr,encodeAsync:()=>k$,encode:()=>_$,emoji:()=>_l,email:()=>vl,e164:()=>El,discriminatedUnion:()=>yl,describe:()=>Uc,decodeAsync:()=>D$,decode:()=>U$,date:()=>Rl,custom:()=>_c,cuid2:()=>Dl,cuid:()=>kl,core:()=>ir,config:()=>G,coerce:()=>Ug,codec:()=>$c,clone:()=>q,cidrv6:()=>Pl,cidrv4:()=>jl,check:()=>Ic,catch:()=>ig,boolean:()=>j$,bigint:()=>Ql,base64url:()=>dl,base64:()=>Jl,array:()=>Gn,any:()=>Ml,_function:()=>bc,_default:()=>a$,_ZodString:()=>xi,ZodXor:()=>X$,ZodXID:()=>yi,ZodVoid:()=>A$,ZodUnknown:()=>G$,ZodUnion:()=>An,ZodUndefined:()=>J$,ZodUUID:()=>p,ZodURL:()=>En,ZodULID:()=>ai,ZodType:()=>O,ZodTuple:()=>Q$,ZodTransform:()=>R$,ZodTemplateLiteral:()=>ug,ZodSymbol:()=>P$,ZodSuccess:()=>rg,ZodStringFormat:()=>d,ZodString:()=>Cr,ZodSet:()=>H$,ZodRecord:()=>fr,ZodRealError:()=>H,ZodReadonly:()=>eg,ZodPromise:()=>lg,ZodPreprocess:()=>og,ZodPrefault:()=>y$,ZodPipe:()=>Vn,ZodOptional:()=>bt,ZodObject:()=>Wn,ZodNumberFormat:()=>Nr,ZodNumber:()=>ar,ZodNullable:()=>C$,ZodNull:()=>d$,ZodNonOptional:()=>It,ZodNever:()=>W$,ZodNanoID:()=>Zi,ZodNaN:()=>tg,ZodMap:()=>B$,ZodMAC:()=>z$,ZodLiteral:()=>M$,ZodLazy:()=>$g,ZodKSUID:()=>pi,ZodJWT:()=>vt,ZodIssueCode:()=>$4,ZodIntersection:()=>K$,ZodISOTime:()=>Fi,ZodISODuration:()=>Bi,ZodISODateTime:()=>Qi,ZodISODate:()=>Ti,ZodIPv6:()=>rt,ZodIPv4:()=>si,ZodGUID:()=>jn,ZodFunction:()=>cg,ZodFirstPartyTypeKind:()=>_g,ZodFile:()=>x$,ZodExactOptional:()=>f$,ZodError:()=>g$,ZodEnum:()=>Zr,ZodEmoji:()=>fi,ZodEmail:()=>Ri,ZodE164:()=>et,ZodDiscriminatedUnion:()=>q$,ZodDefault:()=>h$,ZodDate:()=>Ln,ZodCustomStringFormat:()=>hr,ZodCustom:()=>qn,ZodCodec:()=>Xn,ZodCatch:()=>ng,ZodCUID2:()=>hi,ZodCUID:()=>Ci,ZodCIDRv6:()=>it,ZodCIDRv4:()=>nt,ZodBoolean:()=>yr,ZodBigIntFormat:()=>ut,ZodBigInt:()=>pr,ZodBase64URL:()=>ot,ZodBase64:()=>tt,ZodArray:()=>V$,ZodAny:()=>L$,TimePrecision:()=>Qv,NEVER:()=>kt,$output:()=>Av,$input:()=>Vv,$brand:()=>Dt});var ir={};s(ir,{version:()=>Po,util:()=>k,treeifyError:()=>Et,toJSONSchema:()=>Ki,toDotPath:()=>Pg,safeParseAsync:()=>Wt,safeParse:()=>Gt,safeEncodeAsync:()=>gb,safeEncode:()=>ub,safeDecodeAsync:()=>lb,safeDecode:()=>$b,registry:()=>ui,regexes:()=>M,process:()=>P,prettifyError:()=>Lt,parseAsync:()=>Tn,parse:()=>Qn,meta:()=>wu,locales:()=>mn,isValidJWT:()=>Zg,isValidBase64URL:()=>fg,isValidBase64:()=>Co,initializeContext:()=>gr,globalRegistry:()=>V,globalConfig:()=>br,formatError:()=>$n,flattenError:()=>un,finalize:()=>cr,extractDefs:()=>lr,encodeAsync:()=>eb,encode:()=>tb,describe:()=>Du,decodeAsync:()=>vb,decode:()=>ob,createToJSONSchemaMethod:()=>Su,createStandardJSONSchemaMethod:()=>xr,config:()=>G,clone:()=>q,_xor:()=>YI,_xid:()=>wi,_void:()=>$u,_uuidv7:()=>bi,_uuidv6:()=>ci,_uuidv4:()=>li,_uuid:()=>gi,_url:()=>Nn,_uppercase:()=>Vr,_unknown:()=>vu,_union:()=>KI,_undefined:()=>tu,_ulid:()=>Di,_uint64:()=>nu,_uint32:()=>hv,_tuple:()=>FI,_trim:()=>Tr,_transform:()=>ZI,_toUpperCase:()=>Br,_toLowerCase:()=>Fr,_templateLiteral:()=>i4,_symbol:()=>iu,_superRefine:()=>ku,_success:()=>pI,_stringbool:()=>mu,_stringFormat:()=>Mr,_string:()=>qv,_startsWith:()=>qr,_slugify:()=>Hr,_size:()=>Dr,_set:()=>MI,_safeParseAsync:()=>Er,_safeParse:()=>dr,_safeEncodeAsync:()=>fn,_safeEncode:()=>xn,_safeDecodeAsync:()=>Zn,_safeDecode:()=>Rn,_regex:()=>Wr,_refine:()=>Uu,_record:()=>BI,_readonly:()=>n4,_property:()=>Ai,_promise:()=>o4,_positive:()=>Ei,_pipe:()=>r4,_parseAsync:()=>Jr,_parse:()=>Pr,_overwrite:()=>f,_optional:()=>CI,_number:()=>Mv,_nullable:()=>hI,_null:()=>ou,_normalize:()=>Qr,_nonpositive:()=>Gi,_nonoptional:()=>yI,_nonnegative:()=>Wi,_never:()=>uu,_negative:()=>Li,_nativeEnum:()=>RI,_nanoid:()=>_i,_nan:()=>cu,_multipleOf:()=>ur,_minSize:()=>y,_minLength:()=>nr,_min:()=>Y,_mime:()=>Yr,_maxSize:()=>$r,_maxLength:()=>wr,_max:()=>x,_map:()=>HI,_mac:()=>Yv,_lte:()=>x,_lt:()=>h,_lowercase:()=>Ar,_literal:()=>fI,_length:()=>mr,_lazy:()=>t4,_ksuid:()=>mi,_jwt:()=>di,_isoTime:()=>Bv,_isoDuration:()=>Hv,_isoDateTime:()=>Tv,_isoDate:()=>Fv,_ipv6:()=>Ni,_ipv4:()=>Si,_intersection:()=>TI,_int64:()=>ru,_int32:()=>Cv,_int:()=>Rv,_includes:()=>Xr,_guid:()=>Sn,_gte:()=>Y,_gt:()=>a,_float64:()=>Zv,_float32:()=>fv,_file:()=>Iu,_enum:()=>xI,_endsWith:()=>Kr,_encodeAsync:()=>Hn,_encode:()=>Fn,_emoji:()=>Ii,_email:()=>$i,_e164:()=>Ji,_discriminatedUnion:()=>QI,_default:()=>aI,_decodeAsync:()=>Mn,_decode:()=>Bn,_date:()=>gu,_custom:()=>_u,_cuid2:()=>ki,_cuid:()=>Ui,_coercedString:()=>Kv,_coercedNumber:()=>xv,_coercedDate:()=>lu,_coercedBoolean:()=>yv,_coercedBigint:()=>sv,_cidrv6:()=>Oi,_cidrv4:()=>zi,_check:()=>il,_catch:()=>sI,_boolean:()=>av,_bigint:()=>pv,_base64url:()=>Pi,_base64:()=>ji,_array:()=>bu,_any:()=>eu,TimePrecision:()=>Qv,NEVER:()=>kt,JSONSchemaGenerator:()=>o$,JSONSchema:()=>tl,Doc:()=>yn,$output:()=>Av,$input:()=>Vv,$constructor:()=>l,$brand:()=>Dt,$ZodXor:()=>be,$ZodXID:()=>Yo,$ZodVoid:()=>$e,$ZodUnknown:()=>ve,$ZodUnion:()=>In,$ZodUndefined:()=>te,$ZodUUID:()=>Lo,$ZodURL:()=>Wo,$ZodULID:()=>Ko,$ZodType:()=>z,$ZodTuple:()=>oi,$ZodTransform:()=>Ne,$ZodTemplateLiteral:()=>Ae,$ZodSymbol:()=>ie,$ZodSuccess:()=>de,$ZodStringFormat:()=>J,$ZodString:()=>kr,$ZodSet:()=>De,$ZodRegistry:()=>Xv,$ZodRecord:()=>Ue,$ZodRealError:()=>B,$ZodReadonly:()=>We,$ZodPromise:()=>Xe,$ZodPreprocess:()=>Ge,$ZodPrefault:()=>Pe,$ZodPipe:()=>vi,$ZodOptional:()=>ei,$ZodObjectJIT:()=>ce,$ZodObject:()=>ag,$ZodNumberFormat:()=>re,$ZodNumber:()=>ii,$ZodNullable:()=>Oe,$ZodNull:()=>oe,$ZodNonOptional:()=>Je,$ZodNever:()=>ue,$ZodNanoID:()=>Vo,$ZodNaN:()=>Le,$ZodMap:()=>ke,$ZodMAC:()=>Ro,$ZodLiteral:()=>me,$ZodLazy:()=>qe,$ZodKSUID:()=>Qo,$ZodJWT:()=>po,$ZodIntersection:()=>_e,$ZodISOTime:()=>Bo,$ZodISODuration:()=>Ho,$ZodISODateTime:()=>To,$ZodISODate:()=>Fo,$ZodIPv6:()=>xo,$ZodIPv4:()=>Mo,$ZodGUID:()=>Eo,$ZodFunction:()=>Ve,$ZodFile:()=>Se,$ZodExactOptional:()=>ze,$ZodError:()=>vn,$ZodEnum:()=>we,$ZodEncodeError:()=>Ir,$ZodEmoji:()=>Ao,$ZodEmail:()=>Go,$ZodE164:()=>yo,$ZodDiscriminatedUnion:()=>Ie,$ZodDefault:()=>je,$ZodDate:()=>ge,$ZodCustomStringFormat:()=>so,$ZodCustom:()=>Ke,$ZodCodec:()=>_n,$ZodCheckUpperCase:()=>wo,$ZodCheckStringFormat:()=>Lr,$ZodCheckStartsWith:()=>So,$ZodCheckSizeEquals:()=>bo,$ZodCheckRegex:()=>ko,$ZodCheckProperty:()=>zo,$ZodCheckOverwrite:()=>jo,$ZodCheckNumberFormat:()=>$o,$ZodCheckMultipleOf:()=>uo,$ZodCheckMinSize:()=>co,$ZodCheckMinLength:()=>_o,$ZodCheckMimeType:()=>Oo,$ZodCheckMaxSize:()=>lo,$ZodCheckMaxLength:()=>Io,$ZodCheckLowerCase:()=>Do,$ZodCheckLessThan:()=>hn,$ZodCheckLengthEquals:()=>Uo,$ZodCheckIncludes:()=>mo,$ZodCheckGreaterThan:()=>an,$ZodCheckEndsWith:()=>No,$ZodCheckBigIntFormat:()=>go,$ZodCheck:()=>E,$ZodCatch:()=>Ee,$ZodCUID2:()=>qo,$ZodCUID:()=>Xo,$ZodCIDRv6:()=>Zo,$ZodCIDRv4:()=>fo,$ZodBoolean:()=>bn,$ZodBigIntFormat:()=>ne,$ZodBigInt:()=>ti,$ZodBase64URL:()=>ao,$ZodBase64:()=>ho,$ZodAsyncError:()=>C,$ZodArray:()=>le,$ZodAny:()=>ee});var mg,kt=Object.freeze({status:"aborted"});function l(n,i,o){function e(u,g){if(!u._zod)Object.defineProperty(u,"_zod",{value:{def:g,constr:v,traits:new Set},enumerable:!1});if(u._zod.traits.has(n))return;u._zod.traits.add(n),i(u,g);let $=v.prototype,c=Object.keys($);for(let I=0;I<c.length;I++){let m=c[I];if(!(m in u))u[m]=$[m].bind(u)}}let r=o?.Parent??Object;class t extends r{}Object.defineProperty(t,"name",{value:n});function v(u){var g;let $=o?.Parent?new t:this;e($,u),(g=$._zod).deferred??(g.deferred=[]);for(let c of $._zod.deferred)c();return $}return Object.defineProperty(v,"init",{value:e}),Object.defineProperty(v,Symbol.hasInstance,{value:(u)=>{if(o?.Parent&&u instanceof o.Parent)return!0;return u?._zod?.traits?.has(n)}}),Object.defineProperty(v,"name",{value:n}),v}var Dt=Symbol("zod_brand");class C extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ir extends Error{constructor(n){super(`Encountered unidirectional transform during encode: ${n}`);this.name="ZodEncodeError"}}(mg=globalThis).__zod_globalConfig??(mg.__zod_globalConfig={});var br=globalThis.__zod_globalConfig;function G(n){if(n)Object.assign(br,n);return br}var k={};s(k,{unwrapMessage:()=>sr,uint8ArrayToHex:()=>nb,uint8ArrayToBase64url:()=>sc,uint8ArrayToBase64:()=>zg,stringifyPrimitive:()=>_,slugify:()=>St,shallowClone:()=>zt,safeExtend:()=>Zc,required:()=>ac,randomString:()=>Fc,propertyKeyTypes:()=>tn,promiseAllObject:()=>Tc,primitiveTypes:()=>Ot,prefixIssues:()=>F,pick:()=>xc,partial:()=>hc,parsedType:()=>U,optionalKeys:()=>jt,omit:()=>Rc,objectClone:()=>Kc,numKeys:()=>Bc,nullish:()=>tr,normalizeParams:()=>w,mergeDefs:()=>rr,merge:()=>Cc,jsonStringifyReplacer:()=>zr,joinValues:()=>b,issue:()=>jr,isPlainObject:()=>er,isObject:()=>_r,hexToUint8Array:()=>rb,getSizableOrigin:()=>on,getParsedType:()=>Hc,getLengthableOrigin:()=>en,getEnumValues:()=>rn,getElementAtPath:()=>Qc,floatSafeRemainder:()=>mt,finalizeIssue:()=>K,extend:()=>fc,explicitlyAborted:()=>dt,escapeRegex:()=>R,esc:()=>Kn,defineLazy:()=>j,createTransparentProxy:()=>Mc,cloneDef:()=>Yc,clone:()=>q,cleanRegex:()=>nn,cleanEnum:()=>yc,captureStackTrace:()=>Yn,cached:()=>Or,base64urlToUint8Array:()=>pc,base64ToUint8Array:()=>Ng,assignProp:()=>or,assertNotEqual:()=>Ac,assertNever:()=>Xc,assertIs:()=>Vc,assertEqual:()=>Wc,assert:()=>qc,allowsEval:()=>Nt,aborted:()=>vr,NUMBER_FORMAT_RANGES:()=>Pt,Class:()=>Og,BIGINT_FORMAT_RANGES:()=>Jt});function Wc(n){return n}function Ac(n){return n}function Vc(n){}function Xc(n){throw Error("Unexpected value in exhaustive check")}function qc(n){}function rn(n){let i=Object.values(n).filter((e)=>typeof e==="number");return Object.entries(n).filter(([e,r])=>i.indexOf(+e)===-1).map(([e,r])=>r)}function b(n,i="|"){return n.map((o)=>_(o)).join(i)}function zr(n,i){if(typeof i==="bigint")return i.toString();return i}function Or(n){return{get value(){{let o=n();return Object.defineProperty(this,"value",{value:o}),o}throw Error("cached value already set")}}}function tr(n){return n===null||n===void 0}function nn(n){let i=n.startsWith("^")?1:0,o=n.endsWith("$")?n.length-1:n.length;return n.slice(i,o)}function mt(n,i){let o=n/i,e=Math.round(o),r=Number.EPSILON*Math.max(Math.abs(o),1);if(Math.abs(o-e)<r)return 0;return o-e}var Sg=Symbol("evaluating");function j(n,i,o){let e=void 0;Object.defineProperty(n,i,{get(){if(e===Sg)return;if(e===void 0)e=Sg,e=o();return e},set(r){Object.defineProperty(n,i,{value:r})},configurable:!0})}function Kc(n){return Object.create(Object.getPrototypeOf(n),Object.getOwnPropertyDescriptors(n))}function or(n,i,o){Object.defineProperty(n,i,{value:o,writable:!0,enumerable:!0,configurable:!0})}function rr(...n){let i={};for(let o of n){let e=Object.getOwnPropertyDescriptors(o);Object.assign(i,e)}return Object.defineProperties({},i)}function Yc(n){return rr(n._zod.def)}function Qc(n,i){if(!i)return n;return i.reduce((o,e)=>o?.[e],n)}function Tc(n){let i=Object.keys(n),o=i.map((e)=>n[e]);return Promise.all(o).then((e)=>{let r={};for(let t=0;t<i.length;t++)r[i[t]]=e[t];return r})}function Fc(n=10){let o="";for(let e=0;e<n;e++)o+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return o}function Kn(n){return JSON.stringify(n)}function St(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Yn="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function _r(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}var Nt=Or(()=>{if(br.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(n){return!1}});function er(n){if(_r(n)===!1)return!1;let i=n.constructor;if(i===void 0)return!0;if(typeof i!=="function")return!0;let o=i.prototype;if(_r(o)===!1)return!1;if(Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)return!1;return!0}function zt(n){if(er(n))return{...n};if(Array.isArray(n))return[...n];if(n instanceof Map)return new Map(n);if(n instanceof Set)return new Set(n);return n}function Bc(n){let i=0;for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))i++;return i}var Hc=(n)=>{let i=typeof n;switch(i){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(n))return"array";if(n===null)return"null";if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return"promise";if(typeof Map<"u"&&n instanceof Map)return"map";if(typeof Set<"u"&&n instanceof Set)return"set";if(typeof Date<"u"&&n instanceof Date)return"date";if(typeof File<"u"&&n instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${i}`)}},tn=new Set(["string","number","symbol"]),Ot=new Set(["string","number","bigint","boolean","symbol","undefined"]);function R(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q(n,i,o){let e=new n._zod.constr(i??n._zod.def);if(!i||o?.parent)e._zod.parent=n;return e}function w(n){let i=n;if(!i)return{};if(typeof i==="string")return{error:()=>i};if(i?.message!==void 0){if(i?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");i.error=i.message}if(delete i.message,typeof i.error==="string")return{...i,error:()=>i.error};return i}function Mc(n){let i;return new Proxy({},{get(o,e,r){return i??(i=n()),Reflect.get(i,e,r)},set(o,e,r,t){return i??(i=n()),Reflect.set(i,e,r,t)},has(o,e){return i??(i=n()),Reflect.has(i,e)},deleteProperty(o,e){return i??(i=n()),Reflect.deleteProperty(i,e)},ownKeys(o){return i??(i=n()),Reflect.ownKeys(i)},getOwnPropertyDescriptor(o,e){return i??(i=n()),Reflect.getOwnPropertyDescriptor(i,e)},defineProperty(o,e,r){return i??(i=n()),Reflect.defineProperty(i,e,r)}})}function _(n){if(typeof n==="bigint")return n.toString()+"n";if(typeof n==="string")return`"${n}"`;return`${n}`}function jt(n){return Object.keys(n).filter((i)=>{return n[i]._zod.optin==="optional"&&n[i]._zod.optout==="optional"})}var Pt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Jt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xc(n,i){let o=n._zod.def,e=o.checks;if(e&&e.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let t=rr(n._zod.def,{get shape(){let v={};for(let u in i){if(!(u in o.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;v[u]=o.shape[u]}return or(this,"shape",v),v},checks:[]});return q(n,t)}function Rc(n,i){let o=n._zod.def,e=o.checks;if(e&&e.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let t=rr(n._zod.def,{get shape(){let v={...n._zod.def.shape};for(let u in i){if(!(u in o.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;delete v[u]}return or(this,"shape",v),v},checks:[]});return q(n,t)}function fc(n,i){if(!er(i))throw Error("Invalid input to extend: expected a plain object");let o=n._zod.def.checks;if(o&&o.length>0){let t=n._zod.def.shape;for(let v in i)if(Object.getOwnPropertyDescriptor(t,v)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=rr(n._zod.def,{get shape(){let t={...n._zod.def.shape,...i};return or(this,"shape",t),t}});return q(n,r)}function Zc(n,i){if(!er(i))throw Error("Invalid input to safeExtend: expected a plain object");let o=rr(n._zod.def,{get shape(){let e={...n._zod.def.shape,...i};return or(this,"shape",e),e}});return q(n,o)}function Cc(n,i){if(n._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let o=rr(n._zod.def,{get shape(){let e={...n._zod.def.shape,...i._zod.def.shape};return or(this,"shape",e),e},get catchall(){return i._zod.def.catchall},checks:i._zod.def.checks??[]});return q(n,o)}function hc(n,i,o){let r=i._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let v=rr(i._zod.def,{get shape(){let u=i._zod.def.shape,g={...u};if(o)for(let $ in o){if(!($ in u))throw Error(`Unrecognized key: "${$}"`);if(!o[$])continue;g[$]=n?new n({type:"optional",innerType:u[$]}):u[$]}else for(let $ in u)g[$]=n?new n({type:"optional",innerType:u[$]}):u[$];return or(this,"shape",g),g},checks:[]});return q(i,v)}function ac(n,i,o){let e=rr(i._zod.def,{get shape(){let r=i._zod.def.shape,t={...r};if(o)for(let v in o){if(!(v in t))throw Error(`Unrecognized key: "${v}"`);if(!o[v])continue;t[v]=new n({type:"nonoptional",innerType:r[v]})}else for(let v in r)t[v]=new n({type:"nonoptional",innerType:r[v]});return or(this,"shape",t),t}});return q(i,e)}function vr(n,i=0){if(n.aborted===!0)return!0;for(let o=i;o<n.issues.length;o++)if(n.issues[o]?.continue!==!0)return!0;return!1}function dt(n,i=0){if(n.aborted===!0)return!0;for(let o=i;o<n.issues.length;o++)if(n.issues[o]?.continue===!1)return!0;return!1}function F(n,i){return i.map((o)=>{var e;return(e=o).path??(e.path=[]),o.path.unshift(n),o})}function sr(n){return typeof n==="string"?n:n?.message}function K(n,i,o){let e=n.message?n.message:sr(n.inst?._zod.def?.error?.(n))??sr(i?.error?.(n))??sr(o.customError?.(n))??sr(o.localeError?.(n))??"Invalid input",{inst:r,continue:t,input:v,...u}=n;if(u.path??(u.path=[]),u.message=e,i?.reportInput)u.input=v;return u}function on(n){if(n instanceof Set)return"set";if(n instanceof Map)return"map";if(n instanceof File)return"file";return"unknown"}function en(n){if(Array.isArray(n))return"array";if(typeof n==="string")return"string";return"unknown"}function U(n){let i=typeof n;switch(i){case"number":return Number.isNaN(n)?"nan":"number";case"object":{if(n===null)return"null";if(Array.isArray(n))return"array";let o=n;if(o&&Object.getPrototypeOf(o)!==Object.prototype&&"constructor"in o&&o.constructor)return o.constructor.name}}return i}function jr(...n){let[i,o,e]=n;if(typeof i==="string")return{message:i,code:"custom",input:o,inst:e};return{...i}}function yc(n){return Object.entries(n).filter(([i,o])=>{return Number.isNaN(Number.parseInt(i,10))}).map((i)=>i[1])}function Ng(n){let i=atob(n),o=new Uint8Array(i.length);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return o}function zg(n){let i="";for(let o=0;o<n.length;o++)i+=String.fromCharCode(n[o]);return btoa(i)}function pc(n){let i=n.replace(/-/g,"+").replace(/_/g,"/"),o="=".repeat((4-i.length%4)%4);return Ng(i+o)}function sc(n){return zg(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rb(n){let i=n.replace(/^0x/,"");if(i.length%2!==0)throw Error("Invalid hex string length");let o=new Uint8Array(i.length/2);for(let e=0;e<i.length;e+=2)o[e/2]=Number.parseInt(i.slice(e,e+2),16);return o}function nb(n){return Array.from(n).map((i)=>i.toString(16).padStart(2,"0")).join("")}class Og{constructor(...n){}}var jg=(n,i)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:i,enumerable:!1}),n.message=JSON.stringify(i,zr,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},vn=l("$ZodError",jg),B=l("$ZodError",jg,{Parent:Error});function un(n,i=(o)=>o.message){let o={},e=[];for(let r of n.issues)if(r.path.length>0)o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(i(r));else e.push(i(r));return{formErrors:e,fieldErrors:o}}function $n(n,i=(o)=>o.message){let o={_errors:[]},e=(r,t=[])=>{for(let v of r.issues)if(v.code==="invalid_union"&&v.errors.length)v.errors.map((u)=>e({issues:u},[...t,...v.path]));else if(v.code==="invalid_key")e({issues:v.issues},[...t,...v.path]);else if(v.code==="invalid_element")e({issues:v.issues},[...t,...v.path]);else{let u=[...t,...v.path];if(u.length===0)o._errors.push(i(v));else{let g=o,$=0;while($<u.length){let c=u[$];if($!==u.length-1)g[c]=g[c]||{_errors:[]};else g[c]=g[c]||{_errors:[]},g[c]._errors.push(i(v));g=g[c],$++}}}};return e(n),o}function Et(n,i=(o)=>o.message){let o={errors:[]},e=(r,t=[])=>{var v,u;for(let g of r.issues)if(g.code==="invalid_union"&&g.errors.length)g.errors.map(($)=>e({issues:$},[...t,...g.path]));else if(g.code==="invalid_key")e({issues:g.issues},[...t,...g.path]);else if(g.code==="invalid_element")e({issues:g.issues},[...t,...g.path]);else{let $=[...t,...g.path];if($.length===0){o.errors.push(i(g));continue}let c=o,I=0;while(I<$.length){let m=$[I],D=I===$.length-1;if(typeof m==="string")c.properties??(c.properties={}),(v=c.properties)[m]??(v[m]={errors:[]}),c=c.properties[m];else c.items??(c.items=[]),(u=c.items)[m]??(u[m]={errors:[]}),c=c.items[m];if(D)c.errors.push(i(g));I++}}};return e(n),o}function Pg(n){let i=[],o=n.map((e)=>typeof e==="object"?e.key:e);for(let e of o)if(typeof e==="number")i.push(`[${e}]`);else if(typeof e==="symbol")i.push(`[${JSON.stringify(String(e))}]`);else if(/[^\w$]/.test(e))i.push(`[${JSON.stringify(e)}]`);else{if(i.length)i.push(".");i.push(e)}return i.join("")}function Lt(n){let i=[],o=[...n.issues].sort((e,r)=>(e.path??[]).length-(r.path??[]).length);for(let e of o)if(i.push(`\u2716 ${e.message}`),e.path?.length)i.push(` \u2192 at ${Pg(e.path)}`);return i.join(`
2
+ var Pc=Object.defineProperty;var Jc=(n)=>n;function dc(n,i){this[n]=Jc.bind(null,i)}var s=(n,i)=>{for(var o in i)Pc(n,o,{get:i[o],enumerable:!0,configurable:!0,set:dc.bind(i,o)})};function Ec(n){return n}var wg={name:"@rizom/brain",version:"0.2.0-alpha.146",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/sdk":"^1.29.0","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20",postcss:"^8.5.15",preact:"^10.27.2","preact-render-to-string":"^6.7.0",tailwindcss:"^4.3.1",zod:"^4.1.8"},devDependencies:{"@brains/app":"workspace:*","@brains/build-tools":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.3.14",rollup:"^4.62.0","rollup-plugin-dts":"^6.4.1",typescript:"^6.0.3"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","playwright-core":"^1.61.0","react-devtools-core":"^7.0.1",sharp:"^0.35.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Gc=wg.version;var _t={};s(_t,{xor:()=>al,xid:()=>ml,void:()=>xl,uuidv7:()=>cl,uuidv6:()=>ll,uuidv4:()=>gl,uuid:()=>$l,util:()=>k,url:()=>bl,uppercase:()=>Vr,unknown:()=>Sr,union:()=>gt,undefined:()=>Hl,ulid:()=>wl,uint64:()=>Fl,uint32:()=>Yl,tuple:()=>T$,trim:()=>Tr,treeifyError:()=>Et,transform:()=>ct,toUpperCase:()=>Br,toLowerCase:()=>Fr,toJSONSchema:()=>Ki,templateLiteral:()=>lc,symbol:()=>Bl,superRefine:()=>Ig,success:()=>vc,stringbool:()=>wc,stringFormat:()=>Gl,string:()=>On,strictObject:()=>Cl,startsWith:()=>qr,slugify:()=>Hr,size:()=>Dr,setErrorMap:()=>g4,set:()=>nc,safeParseAsync:()=>I$,safeParse:()=>b$,safeEncodeAsync:()=>S$,safeEncode:()=>w$,safeDecodeAsync:()=>N$,safeDecode:()=>m$,registry:()=>ui,regexes:()=>M,regex:()=>Wr,refine:()=>bg,record:()=>F$,readonly:()=>vg,property:()=>Ai,promise:()=>cc,prettifyError:()=>Lt,preprocess:()=>Sc,prefault:()=>p$,positive:()=>Ei,pipe:()=>Mi,partialRecord:()=>pl,parseAsync:()=>c$,parse:()=>l$,overwrite:()=>f,optional:()=>Pn,object:()=>Zl,number:()=>O$,nullish:()=>ec,nullable:()=>Jn,null:()=>E$,normalize:()=>Qr,nonpositive:()=>Gi,nonoptional:()=>s$,nonnegative:()=>Wi,never:()=>$t,negative:()=>Li,nativeEnum:()=>ic,nanoid:()=>Ul,nan:()=>uc,multipleOf:()=>ur,minSize:()=>y,minLength:()=>nr,mime:()=>Yr,meta:()=>kc,maxSize:()=>$r,maxLength:()=>wr,map:()=>rc,mac:()=>zl,lte:()=>x,lt:()=>h,lowercase:()=>Ar,looseRecord:()=>sl,looseObject:()=>hl,locales:()=>mn,literal:()=>tc,length:()=>mr,lazy:()=>gg,ksuid:()=>Sl,keyof:()=>fl,jwt:()=>Ll,json:()=>mc,iso:()=>Rr,ipv6:()=>Ol,ipv4:()=>Nl,invertCodec:()=>gc,intersection:()=>Y$,int64:()=>Tl,int32:()=>Kl,int:()=>Hi,instanceof:()=>Dc,includes:()=>Xr,httpUrl:()=>Il,hostname:()=>Wl,hex:()=>Al,hash:()=>Vl,guid:()=>ul,gte:()=>Y,gt:()=>a,globalRegistry:()=>V,getErrorMap:()=>l4,function:()=>bc,fromJSONSchema:()=>zc,formatError:()=>$n,float64:()=>ql,float32:()=>Xl,flattenError:()=>un,file:()=>oc,exactOptional:()=>Z$,enum:()=>lt,endsWith:()=>Kr,encodeAsync:()=>k$,encode:()=>_$,emoji:()=>_l,email:()=>vl,e164:()=>El,discriminatedUnion:()=>yl,describe:()=>Uc,decodeAsync:()=>D$,decode:()=>U$,date:()=>Rl,custom:()=>_c,cuid2:()=>Dl,cuid:()=>kl,core:()=>ir,config:()=>G,coerce:()=>Ug,codec:()=>$c,clone:()=>q,cidrv6:()=>Pl,cidrv4:()=>jl,check:()=>Ic,catch:()=>ig,boolean:()=>j$,bigint:()=>Ql,base64url:()=>dl,base64:()=>Jl,array:()=>Gn,any:()=>Ml,_function:()=>bc,_default:()=>a$,_ZodString:()=>xi,ZodXor:()=>X$,ZodXID:()=>yi,ZodVoid:()=>A$,ZodUnknown:()=>G$,ZodUnion:()=>An,ZodUndefined:()=>J$,ZodUUID:()=>p,ZodURL:()=>En,ZodULID:()=>ai,ZodType:()=>O,ZodTuple:()=>Q$,ZodTransform:()=>R$,ZodTemplateLiteral:()=>ug,ZodSymbol:()=>P$,ZodSuccess:()=>rg,ZodStringFormat:()=>d,ZodString:()=>Cr,ZodSet:()=>H$,ZodRecord:()=>fr,ZodRealError:()=>H,ZodReadonly:()=>eg,ZodPromise:()=>lg,ZodPreprocess:()=>og,ZodPrefault:()=>y$,ZodPipe:()=>Vn,ZodOptional:()=>bt,ZodObject:()=>Wn,ZodNumberFormat:()=>Nr,ZodNumber:()=>ar,ZodNullable:()=>C$,ZodNull:()=>d$,ZodNonOptional:()=>It,ZodNever:()=>W$,ZodNanoID:()=>Zi,ZodNaN:()=>tg,ZodMap:()=>B$,ZodMAC:()=>z$,ZodLiteral:()=>M$,ZodLazy:()=>$g,ZodKSUID:()=>pi,ZodJWT:()=>vt,ZodIssueCode:()=>$4,ZodIntersection:()=>K$,ZodISOTime:()=>Fi,ZodISODuration:()=>Bi,ZodISODateTime:()=>Qi,ZodISODate:()=>Ti,ZodIPv6:()=>rt,ZodIPv4:()=>si,ZodGUID:()=>jn,ZodFunction:()=>cg,ZodFirstPartyTypeKind:()=>_g,ZodFile:()=>x$,ZodExactOptional:()=>f$,ZodError:()=>g$,ZodEnum:()=>Zr,ZodEmoji:()=>fi,ZodEmail:()=>Ri,ZodE164:()=>et,ZodDiscriminatedUnion:()=>q$,ZodDefault:()=>h$,ZodDate:()=>Ln,ZodCustomStringFormat:()=>hr,ZodCustom:()=>qn,ZodCodec:()=>Xn,ZodCatch:()=>ng,ZodCUID2:()=>hi,ZodCUID:()=>Ci,ZodCIDRv6:()=>it,ZodCIDRv4:()=>nt,ZodBoolean:()=>yr,ZodBigIntFormat:()=>ut,ZodBigInt:()=>pr,ZodBase64URL:()=>ot,ZodBase64:()=>tt,ZodArray:()=>V$,ZodAny:()=>L$,TimePrecision:()=>Qv,NEVER:()=>kt,$output:()=>Av,$input:()=>Vv,$brand:()=>Dt});var ir={};s(ir,{version:()=>Po,util:()=>k,treeifyError:()=>Et,toJSONSchema:()=>Ki,toDotPath:()=>Pg,safeParseAsync:()=>Wt,safeParse:()=>Gt,safeEncodeAsync:()=>gb,safeEncode:()=>ub,safeDecodeAsync:()=>lb,safeDecode:()=>$b,registry:()=>ui,regexes:()=>M,process:()=>P,prettifyError:()=>Lt,parseAsync:()=>Tn,parse:()=>Qn,meta:()=>wu,locales:()=>mn,isValidJWT:()=>Zg,isValidBase64URL:()=>fg,isValidBase64:()=>Co,initializeContext:()=>gr,globalRegistry:()=>V,globalConfig:()=>br,formatError:()=>$n,flattenError:()=>un,finalize:()=>cr,extractDefs:()=>lr,encodeAsync:()=>eb,encode:()=>tb,describe:()=>Du,decodeAsync:()=>vb,decode:()=>ob,createToJSONSchemaMethod:()=>Su,createStandardJSONSchemaMethod:()=>xr,config:()=>G,clone:()=>q,_xor:()=>YI,_xid:()=>wi,_void:()=>$u,_uuidv7:()=>bi,_uuidv6:()=>ci,_uuidv4:()=>li,_uuid:()=>gi,_url:()=>Nn,_uppercase:()=>Vr,_unknown:()=>vu,_union:()=>KI,_undefined:()=>tu,_ulid:()=>Di,_uint64:()=>nu,_uint32:()=>hv,_tuple:()=>FI,_trim:()=>Tr,_transform:()=>ZI,_toUpperCase:()=>Br,_toLowerCase:()=>Fr,_templateLiteral:()=>i4,_symbol:()=>iu,_superRefine:()=>ku,_success:()=>pI,_stringbool:()=>mu,_stringFormat:()=>Mr,_string:()=>qv,_startsWith:()=>qr,_slugify:()=>Hr,_size:()=>Dr,_set:()=>MI,_safeParseAsync:()=>Er,_safeParse:()=>dr,_safeEncodeAsync:()=>fn,_safeEncode:()=>xn,_safeDecodeAsync:()=>Zn,_safeDecode:()=>Rn,_regex:()=>Wr,_refine:()=>Uu,_record:()=>BI,_readonly:()=>n4,_property:()=>Ai,_promise:()=>o4,_positive:()=>Ei,_pipe:()=>r4,_parseAsync:()=>Jr,_parse:()=>Pr,_overwrite:()=>f,_optional:()=>CI,_number:()=>Mv,_nullable:()=>hI,_null:()=>ou,_normalize:()=>Qr,_nonpositive:()=>Gi,_nonoptional:()=>yI,_nonnegative:()=>Wi,_never:()=>uu,_negative:()=>Li,_nativeEnum:()=>RI,_nanoid:()=>_i,_nan:()=>cu,_multipleOf:()=>ur,_minSize:()=>y,_minLength:()=>nr,_min:()=>Y,_mime:()=>Yr,_maxSize:()=>$r,_maxLength:()=>wr,_max:()=>x,_map:()=>HI,_mac:()=>Yv,_lte:()=>x,_lt:()=>h,_lowercase:()=>Ar,_literal:()=>fI,_length:()=>mr,_lazy:()=>t4,_ksuid:()=>mi,_jwt:()=>di,_isoTime:()=>Bv,_isoDuration:()=>Hv,_isoDateTime:()=>Tv,_isoDate:()=>Fv,_ipv6:()=>Ni,_ipv4:()=>Si,_intersection:()=>TI,_int64:()=>ru,_int32:()=>Cv,_int:()=>Rv,_includes:()=>Xr,_guid:()=>Sn,_gte:()=>Y,_gt:()=>a,_float64:()=>Zv,_float32:()=>fv,_file:()=>Iu,_enum:()=>xI,_endsWith:()=>Kr,_encodeAsync:()=>Hn,_encode:()=>Fn,_emoji:()=>Ii,_email:()=>$i,_e164:()=>Ji,_discriminatedUnion:()=>QI,_default:()=>aI,_decodeAsync:()=>Mn,_decode:()=>Bn,_date:()=>gu,_custom:()=>_u,_cuid2:()=>ki,_cuid:()=>Ui,_coercedString:()=>Kv,_coercedNumber:()=>xv,_coercedDate:()=>lu,_coercedBoolean:()=>yv,_coercedBigint:()=>sv,_cidrv6:()=>Oi,_cidrv4:()=>zi,_check:()=>il,_catch:()=>sI,_boolean:()=>av,_bigint:()=>pv,_base64url:()=>Pi,_base64:()=>ji,_array:()=>bu,_any:()=>eu,TimePrecision:()=>Qv,NEVER:()=>kt,JSONSchemaGenerator:()=>o$,JSONSchema:()=>tl,Doc:()=>yn,$output:()=>Av,$input:()=>Vv,$constructor:()=>l,$brand:()=>Dt,$ZodXor:()=>be,$ZodXID:()=>Yo,$ZodVoid:()=>$e,$ZodUnknown:()=>ve,$ZodUnion:()=>In,$ZodUndefined:()=>te,$ZodUUID:()=>Lo,$ZodURL:()=>Wo,$ZodULID:()=>Ko,$ZodType:()=>z,$ZodTuple:()=>oi,$ZodTransform:()=>Ne,$ZodTemplateLiteral:()=>Ae,$ZodSymbol:()=>ie,$ZodSuccess:()=>de,$ZodStringFormat:()=>J,$ZodString:()=>kr,$ZodSet:()=>De,$ZodRegistry:()=>Xv,$ZodRecord:()=>Ue,$ZodRealError:()=>B,$ZodReadonly:()=>We,$ZodPromise:()=>Xe,$ZodPreprocess:()=>Ge,$ZodPrefault:()=>Pe,$ZodPipe:()=>vi,$ZodOptional:()=>ei,$ZodObjectJIT:()=>ce,$ZodObject:()=>ag,$ZodNumberFormat:()=>re,$ZodNumber:()=>ii,$ZodNullable:()=>Oe,$ZodNull:()=>oe,$ZodNonOptional:()=>Je,$ZodNever:()=>ue,$ZodNanoID:()=>Vo,$ZodNaN:()=>Le,$ZodMap:()=>ke,$ZodMAC:()=>Ro,$ZodLiteral:()=>me,$ZodLazy:()=>qe,$ZodKSUID:()=>Qo,$ZodJWT:()=>po,$ZodIntersection:()=>_e,$ZodISOTime:()=>Bo,$ZodISODuration:()=>Ho,$ZodISODateTime:()=>To,$ZodISODate:()=>Fo,$ZodIPv6:()=>xo,$ZodIPv4:()=>Mo,$ZodGUID:()=>Eo,$ZodFunction:()=>Ve,$ZodFile:()=>Se,$ZodExactOptional:()=>ze,$ZodError:()=>vn,$ZodEnum:()=>we,$ZodEncodeError:()=>Ir,$ZodEmoji:()=>Ao,$ZodEmail:()=>Go,$ZodE164:()=>yo,$ZodDiscriminatedUnion:()=>Ie,$ZodDefault:()=>je,$ZodDate:()=>ge,$ZodCustomStringFormat:()=>so,$ZodCustom:()=>Ke,$ZodCodec:()=>_n,$ZodCheckUpperCase:()=>wo,$ZodCheckStringFormat:()=>Lr,$ZodCheckStartsWith:()=>So,$ZodCheckSizeEquals:()=>bo,$ZodCheckRegex:()=>ko,$ZodCheckProperty:()=>zo,$ZodCheckOverwrite:()=>jo,$ZodCheckNumberFormat:()=>$o,$ZodCheckMultipleOf:()=>uo,$ZodCheckMinSize:()=>co,$ZodCheckMinLength:()=>_o,$ZodCheckMimeType:()=>Oo,$ZodCheckMaxSize:()=>lo,$ZodCheckMaxLength:()=>Io,$ZodCheckLowerCase:()=>Do,$ZodCheckLessThan:()=>hn,$ZodCheckLengthEquals:()=>Uo,$ZodCheckIncludes:()=>mo,$ZodCheckGreaterThan:()=>an,$ZodCheckEndsWith:()=>No,$ZodCheckBigIntFormat:()=>go,$ZodCheck:()=>E,$ZodCatch:()=>Ee,$ZodCUID2:()=>qo,$ZodCUID:()=>Xo,$ZodCIDRv6:()=>Zo,$ZodCIDRv4:()=>fo,$ZodBoolean:()=>bn,$ZodBigIntFormat:()=>ne,$ZodBigInt:()=>ti,$ZodBase64URL:()=>ao,$ZodBase64:()=>ho,$ZodAsyncError:()=>C,$ZodArray:()=>le,$ZodAny:()=>ee});var mg,kt=Object.freeze({status:"aborted"});function l(n,i,o){function e(u,g){if(!u._zod)Object.defineProperty(u,"_zod",{value:{def:g,constr:v,traits:new Set},enumerable:!1});if(u._zod.traits.has(n))return;u._zod.traits.add(n),i(u,g);let $=v.prototype,c=Object.keys($);for(let I=0;I<c.length;I++){let m=c[I];if(!(m in u))u[m]=$[m].bind(u)}}let r=o?.Parent??Object;class t extends r{}Object.defineProperty(t,"name",{value:n});function v(u){var g;let $=o?.Parent?new t:this;e($,u),(g=$._zod).deferred??(g.deferred=[]);for(let c of $._zod.deferred)c();return $}return Object.defineProperty(v,"init",{value:e}),Object.defineProperty(v,Symbol.hasInstance,{value:(u)=>{if(o?.Parent&&u instanceof o.Parent)return!0;return u?._zod?.traits?.has(n)}}),Object.defineProperty(v,"name",{value:n}),v}var Dt=Symbol("zod_brand");class C extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ir extends Error{constructor(n){super(`Encountered unidirectional transform during encode: ${n}`);this.name="ZodEncodeError"}}(mg=globalThis).__zod_globalConfig??(mg.__zod_globalConfig={});var br=globalThis.__zod_globalConfig;function G(n){if(n)Object.assign(br,n);return br}var k={};s(k,{unwrapMessage:()=>sr,uint8ArrayToHex:()=>nb,uint8ArrayToBase64url:()=>sc,uint8ArrayToBase64:()=>zg,stringifyPrimitive:()=>_,slugify:()=>St,shallowClone:()=>zt,safeExtend:()=>Zc,required:()=>ac,randomString:()=>Fc,propertyKeyTypes:()=>tn,promiseAllObject:()=>Tc,primitiveTypes:()=>Ot,prefixIssues:()=>F,pick:()=>xc,partial:()=>hc,parsedType:()=>U,optionalKeys:()=>jt,omit:()=>Rc,objectClone:()=>Kc,numKeys:()=>Bc,nullish:()=>tr,normalizeParams:()=>w,mergeDefs:()=>rr,merge:()=>Cc,jsonStringifyReplacer:()=>zr,joinValues:()=>b,issue:()=>jr,isPlainObject:()=>er,isObject:()=>_r,hexToUint8Array:()=>rb,getSizableOrigin:()=>on,getParsedType:()=>Hc,getLengthableOrigin:()=>en,getEnumValues:()=>rn,getElementAtPath:()=>Qc,floatSafeRemainder:()=>mt,finalizeIssue:()=>K,extend:()=>fc,explicitlyAborted:()=>dt,escapeRegex:()=>R,esc:()=>Kn,defineLazy:()=>j,createTransparentProxy:()=>Mc,cloneDef:()=>Yc,clone:()=>q,cleanRegex:()=>nn,cleanEnum:()=>yc,captureStackTrace:()=>Yn,cached:()=>Or,base64urlToUint8Array:()=>pc,base64ToUint8Array:()=>Ng,assignProp:()=>or,assertNotEqual:()=>Ac,assertNever:()=>Xc,assertIs:()=>Vc,assertEqual:()=>Wc,assert:()=>qc,allowsEval:()=>Nt,aborted:()=>vr,NUMBER_FORMAT_RANGES:()=>Pt,Class:()=>Og,BIGINT_FORMAT_RANGES:()=>Jt});function Wc(n){return n}function Ac(n){return n}function Vc(n){}function Xc(n){throw Error("Unexpected value in exhaustive check")}function qc(n){}function rn(n){let i=Object.values(n).filter((e)=>typeof e==="number");return Object.entries(n).filter(([e,r])=>i.indexOf(+e)===-1).map(([e,r])=>r)}function b(n,i="|"){return n.map((o)=>_(o)).join(i)}function zr(n,i){if(typeof i==="bigint")return i.toString();return i}function Or(n){return{get value(){{let o=n();return Object.defineProperty(this,"value",{value:o}),o}throw Error("cached value already set")}}}function tr(n){return n===null||n===void 0}function nn(n){let i=n.startsWith("^")?1:0,o=n.endsWith("$")?n.length-1:n.length;return n.slice(i,o)}function mt(n,i){let o=n/i,e=Math.round(o),r=Number.EPSILON*Math.max(Math.abs(o),1);if(Math.abs(o-e)<r)return 0;return o-e}var Sg=Symbol("evaluating");function j(n,i,o){let e=void 0;Object.defineProperty(n,i,{get(){if(e===Sg)return;if(e===void 0)e=Sg,e=o();return e},set(r){Object.defineProperty(n,i,{value:r})},configurable:!0})}function Kc(n){return Object.create(Object.getPrototypeOf(n),Object.getOwnPropertyDescriptors(n))}function or(n,i,o){Object.defineProperty(n,i,{value:o,writable:!0,enumerable:!0,configurable:!0})}function rr(...n){let i={};for(let o of n){let e=Object.getOwnPropertyDescriptors(o);Object.assign(i,e)}return Object.defineProperties({},i)}function Yc(n){return rr(n._zod.def)}function Qc(n,i){if(!i)return n;return i.reduce((o,e)=>o?.[e],n)}function Tc(n){let i=Object.keys(n),o=i.map((e)=>n[e]);return Promise.all(o).then((e)=>{let r={};for(let t=0;t<i.length;t++)r[i[t]]=e[t];return r})}function Fc(n=10){let o="";for(let e=0;e<n;e++)o+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return o}function Kn(n){return JSON.stringify(n)}function St(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Yn="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function _r(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}var Nt=Or(()=>{if(br.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(n){return!1}});function er(n){if(_r(n)===!1)return!1;let i=n.constructor;if(i===void 0)return!0;if(typeof i!=="function")return!0;let o=i.prototype;if(_r(o)===!1)return!1;if(Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)return!1;return!0}function zt(n){if(er(n))return{...n};if(Array.isArray(n))return[...n];if(n instanceof Map)return new Map(n);if(n instanceof Set)return new Set(n);return n}function Bc(n){let i=0;for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))i++;return i}var Hc=(n)=>{let i=typeof n;switch(i){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(n))return"array";if(n===null)return"null";if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return"promise";if(typeof Map<"u"&&n instanceof Map)return"map";if(typeof Set<"u"&&n instanceof Set)return"set";if(typeof Date<"u"&&n instanceof Date)return"date";if(typeof File<"u"&&n instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${i}`)}},tn=new Set(["string","number","symbol"]),Ot=new Set(["string","number","bigint","boolean","symbol","undefined"]);function R(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q(n,i,o){let e=new n._zod.constr(i??n._zod.def);if(!i||o?.parent)e._zod.parent=n;return e}function w(n){let i=n;if(!i)return{};if(typeof i==="string")return{error:()=>i};if(i?.message!==void 0){if(i?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");i.error=i.message}if(delete i.message,typeof i.error==="string")return{...i,error:()=>i.error};return i}function Mc(n){let i;return new Proxy({},{get(o,e,r){return i??(i=n()),Reflect.get(i,e,r)},set(o,e,r,t){return i??(i=n()),Reflect.set(i,e,r,t)},has(o,e){return i??(i=n()),Reflect.has(i,e)},deleteProperty(o,e){return i??(i=n()),Reflect.deleteProperty(i,e)},ownKeys(o){return i??(i=n()),Reflect.ownKeys(i)},getOwnPropertyDescriptor(o,e){return i??(i=n()),Reflect.getOwnPropertyDescriptor(i,e)},defineProperty(o,e,r){return i??(i=n()),Reflect.defineProperty(i,e,r)}})}function _(n){if(typeof n==="bigint")return n.toString()+"n";if(typeof n==="string")return`"${n}"`;return`${n}`}function jt(n){return Object.keys(n).filter((i)=>{return n[i]._zod.optin==="optional"&&n[i]._zod.optout==="optional"})}var Pt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Jt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xc(n,i){let o=n._zod.def,e=o.checks;if(e&&e.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let t=rr(n._zod.def,{get shape(){let v={};for(let u in i){if(!(u in o.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;v[u]=o.shape[u]}return or(this,"shape",v),v},checks:[]});return q(n,t)}function Rc(n,i){let o=n._zod.def,e=o.checks;if(e&&e.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let t=rr(n._zod.def,{get shape(){let v={...n._zod.def.shape};for(let u in i){if(!(u in o.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;delete v[u]}return or(this,"shape",v),v},checks:[]});return q(n,t)}function fc(n,i){if(!er(i))throw Error("Invalid input to extend: expected a plain object");let o=n._zod.def.checks;if(o&&o.length>0){let t=n._zod.def.shape;for(let v in i)if(Object.getOwnPropertyDescriptor(t,v)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=rr(n._zod.def,{get shape(){let t={...n._zod.def.shape,...i};return or(this,"shape",t),t}});return q(n,r)}function Zc(n,i){if(!er(i))throw Error("Invalid input to safeExtend: expected a plain object");let o=rr(n._zod.def,{get shape(){let e={...n._zod.def.shape,...i};return or(this,"shape",e),e}});return q(n,o)}function Cc(n,i){if(n._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let o=rr(n._zod.def,{get shape(){let e={...n._zod.def.shape,...i._zod.def.shape};return or(this,"shape",e),e},get catchall(){return i._zod.def.catchall},checks:i._zod.def.checks??[]});return q(n,o)}function hc(n,i,o){let r=i._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let v=rr(i._zod.def,{get shape(){let u=i._zod.def.shape,g={...u};if(o)for(let $ in o){if(!($ in u))throw Error(`Unrecognized key: "${$}"`);if(!o[$])continue;g[$]=n?new n({type:"optional",innerType:u[$]}):u[$]}else for(let $ in u)g[$]=n?new n({type:"optional",innerType:u[$]}):u[$];return or(this,"shape",g),g},checks:[]});return q(i,v)}function ac(n,i,o){let e=rr(i._zod.def,{get shape(){let r=i._zod.def.shape,t={...r};if(o)for(let v in o){if(!(v in t))throw Error(`Unrecognized key: "${v}"`);if(!o[v])continue;t[v]=new n({type:"nonoptional",innerType:r[v]})}else for(let v in r)t[v]=new n({type:"nonoptional",innerType:r[v]});return or(this,"shape",t),t}});return q(i,e)}function vr(n,i=0){if(n.aborted===!0)return!0;for(let o=i;o<n.issues.length;o++)if(n.issues[o]?.continue!==!0)return!0;return!1}function dt(n,i=0){if(n.aborted===!0)return!0;for(let o=i;o<n.issues.length;o++)if(n.issues[o]?.continue===!1)return!0;return!1}function F(n,i){return i.map((o)=>{var e;return(e=o).path??(e.path=[]),o.path.unshift(n),o})}function sr(n){return typeof n==="string"?n:n?.message}function K(n,i,o){let e=n.message?n.message:sr(n.inst?._zod.def?.error?.(n))??sr(i?.error?.(n))??sr(o.customError?.(n))??sr(o.localeError?.(n))??"Invalid input",{inst:r,continue:t,input:v,...u}=n;if(u.path??(u.path=[]),u.message=e,i?.reportInput)u.input=v;return u}function on(n){if(n instanceof Set)return"set";if(n instanceof Map)return"map";if(n instanceof File)return"file";return"unknown"}function en(n){if(Array.isArray(n))return"array";if(typeof n==="string")return"string";return"unknown"}function U(n){let i=typeof n;switch(i){case"number":return Number.isNaN(n)?"nan":"number";case"object":{if(n===null)return"null";if(Array.isArray(n))return"array";let o=n;if(o&&Object.getPrototypeOf(o)!==Object.prototype&&"constructor"in o&&o.constructor)return o.constructor.name}}return i}function jr(...n){let[i,o,e]=n;if(typeof i==="string")return{message:i,code:"custom",input:o,inst:e};return{...i}}function yc(n){return Object.entries(n).filter(([i,o])=>{return Number.isNaN(Number.parseInt(i,10))}).map((i)=>i[1])}function Ng(n){let i=atob(n),o=new Uint8Array(i.length);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return o}function zg(n){let i="";for(let o=0;o<n.length;o++)i+=String.fromCharCode(n[o]);return btoa(i)}function pc(n){let i=n.replace(/-/g,"+").replace(/_/g,"/"),o="=".repeat((4-i.length%4)%4);return Ng(i+o)}function sc(n){return zg(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rb(n){let i=n.replace(/^0x/,"");if(i.length%2!==0)throw Error("Invalid hex string length");let o=new Uint8Array(i.length/2);for(let e=0;e<i.length;e+=2)o[e/2]=Number.parseInt(i.slice(e,e+2),16);return o}function nb(n){return Array.from(n).map((i)=>i.toString(16).padStart(2,"0")).join("")}class Og{constructor(...n){}}var jg=(n,i)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:i,enumerable:!1}),n.message=JSON.stringify(i,zr,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},vn=l("$ZodError",jg),B=l("$ZodError",jg,{Parent:Error});function un(n,i=(o)=>o.message){let o={},e=[];for(let r of n.issues)if(r.path.length>0)o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(i(r));else e.push(i(r));return{formErrors:e,fieldErrors:o}}function $n(n,i=(o)=>o.message){let o={_errors:[]},e=(r,t=[])=>{for(let v of r.issues)if(v.code==="invalid_union"&&v.errors.length)v.errors.map((u)=>e({issues:u},[...t,...v.path]));else if(v.code==="invalid_key")e({issues:v.issues},[...t,...v.path]);else if(v.code==="invalid_element")e({issues:v.issues},[...t,...v.path]);else{let u=[...t,...v.path];if(u.length===0)o._errors.push(i(v));else{let g=o,$=0;while($<u.length){let c=u[$];if($!==u.length-1)g[c]=g[c]||{_errors:[]};else g[c]=g[c]||{_errors:[]},g[c]._errors.push(i(v));g=g[c],$++}}}};return e(n),o}function Et(n,i=(o)=>o.message){let o={errors:[]},e=(r,t=[])=>{var v,u;for(let g of r.issues)if(g.code==="invalid_union"&&g.errors.length)g.errors.map(($)=>e({issues:$},[...t,...g.path]));else if(g.code==="invalid_key")e({issues:g.issues},[...t,...g.path]);else if(g.code==="invalid_element")e({issues:g.issues},[...t,...g.path]);else{let $=[...t,...g.path];if($.length===0){o.errors.push(i(g));continue}let c=o,I=0;while(I<$.length){let m=$[I],D=I===$.length-1;if(typeof m==="string")c.properties??(c.properties={}),(v=c.properties)[m]??(v[m]={errors:[]}),c=c.properties[m];else c.items??(c.items=[]),(u=c.items)[m]??(u[m]={errors:[]}),c=c.items[m];if(D)c.errors.push(i(g));I++}}};return e(n),o}function Pg(n){let i=[],o=n.map((e)=>typeof e==="object"?e.key:e);for(let e of o)if(typeof e==="number")i.push(`[${e}]`);else if(typeof e==="symbol")i.push(`[${JSON.stringify(String(e))}]`);else if(/[^\w$]/.test(e))i.push(`[${JSON.stringify(e)}]`);else{if(i.length)i.push(".");i.push(e)}return i.join("")}function Lt(n){let i=[],o=[...n.issues].sort((e,r)=>(e.path??[]).length-(r.path??[]).length);for(let e of o)if(i.push(`\u2716 ${e.message}`),e.path?.length)i.push(` \u2192 at ${Pg(e.path)}`);return i.join(`
3
3
  `)}var Pr=(n)=>(i,o,e,r)=>{let t=e?{...e,async:!1}:{async:!1},v=i._zod.run({value:o,issues:[]},t);if(v instanceof Promise)throw new C;if(v.issues.length){let u=new(r?.Err??n)(v.issues.map((g)=>K(g,t,G())));throw Yn(u,r?.callee),u}return v.value},Qn=Pr(B),Jr=(n)=>async(i,o,e,r)=>{let t=e?{...e,async:!0}:{async:!0},v=i._zod.run({value:o,issues:[]},t);if(v instanceof Promise)v=await v;if(v.issues.length){let u=new(r?.Err??n)(v.issues.map((g)=>K(g,t,G())));throw Yn(u,r?.callee),u}return v.value},Tn=Jr(B),dr=(n)=>(i,o,e)=>{let r=e?{...e,async:!1}:{async:!1},t=i._zod.run({value:o,issues:[]},r);if(t instanceof Promise)throw new C;return t.issues.length?{success:!1,error:new(n??vn)(t.issues.map((v)=>K(v,r,G())))}:{success:!0,data:t.value}},Gt=dr(B),Er=(n)=>async(i,o,e)=>{let r=e?{...e,async:!0}:{async:!0},t=i._zod.run({value:o,issues:[]},r);if(t instanceof Promise)t=await t;return t.issues.length?{success:!1,error:new n(t.issues.map((v)=>K(v,r,G())))}:{success:!0,data:t.value}},Wt=Er(B),Fn=(n)=>(i,o,e)=>{let r=e?{...e,direction:"backward"}:{direction:"backward"};return Pr(n)(i,o,r)},tb=Fn(B),Bn=(n)=>(i,o,e)=>{return Pr(n)(i,o,e)},ob=Bn(B),Hn=(n)=>async(i,o,e)=>{let r=e?{...e,direction:"backward"}:{direction:"backward"};return Jr(n)(i,o,r)},eb=Hn(B),Mn=(n)=>async(i,o,e)=>{return Jr(n)(i,o,e)},vb=Mn(B),xn=(n)=>(i,o,e)=>{let r=e?{...e,direction:"backward"}:{direction:"backward"};return dr(n)(i,o,r)},ub=xn(B),Rn=(n)=>(i,o,e)=>{return dr(n)(i,o,e)},$b=Rn(B),fn=(n)=>async(i,o,e)=>{let r=e?{...e,direction:"backward"}:{direction:"backward"};return Er(n)(i,o,r)},gb=fn(B),Zn=(n)=>async(i,o,e)=>{return Er(n)(i,o,e)},lb=Zn(B);var M={};s(M,{xid:()=>qt,uuid7:()=>_b,uuid6:()=>Ib,uuid4:()=>bb,uuid:()=>Ur,uppercase:()=>vo,unicodeEmail:()=>Jg,undefined:()=>oo,ulid:()=>Xt,time:()=>yt,string:()=>st,sha512_hex:()=>qb,sha512_base64url:()=>Yb,sha512_base64:()=>Kb,sha384_hex:()=>Ab,sha384_base64url:()=>Xb,sha384_base64:()=>Vb,sha256_hex:()=>Lb,sha256_base64url:()=>Wb,sha256_base64:()=>Gb,sha1_hex:()=>Jb,sha1_base64url:()=>Eb,sha1_base64:()=>db,rfc5322Email:()=>kb,number:()=>gn,null:()=>to,nanoid:()=>Yt,md5_hex:()=>Ob,md5_base64url:()=>Pb,md5_base64:()=>jb,mac:()=>xt,lowercase:()=>eo,ksuid:()=>Kt,ipv6:()=>Mt,ipv4:()=>Ht,integer:()=>no,idnEmail:()=>Db,httpProtocol:()=>Ct,html5Email:()=>Ub,hostname:()=>Sb,hex:()=>zb,guid:()=>Tt,extendedDuration:()=>cb,emoji:()=>Bt,email:()=>Ft,e164:()=>ht,duration:()=>Qt,domain:()=>Nb,datetime:()=>pt,date:()=>at,cuid2:()=>Vt,cuid:()=>At,cidrv6:()=>ft,cidrv4:()=>Rt,browserEmail:()=>wb,boolean:()=>io,bigint:()=>ro,base64url:()=>Cn,base64:()=>Zt});var At=/^[cC][0-9a-z]{6,}$/,Vt=/^[0-9a-z]+$/,Xt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qt=/^[0-9a-vA-V]{20}$/,Kt=/^[A-Za-z0-9]{27}$/,Yt=/^[a-zA-Z0-9_-]{21}$/,Qt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,cb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Tt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ur=(n)=>{if(!n)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},bb=Ur(4),Ib=Ur(6),_b=Ur(7),Ft=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ub=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,kb=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Jg=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Db=Jg,wb=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,mb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bt(){return new RegExp(mb,"u")}var Ht=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,xt=(n)=>{let i=R(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},Rt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ft=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Cn=/^[A-Za-z0-9_-]*$/,Sb=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Nb=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Ct=/^https?$/,ht=/^\+[1-9]\d{6,14}$/,dg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",at=new RegExp(`^${dg}$`);function Eg(n){return typeof n.precision==="number"?n.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":n.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${n.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function yt(n){return new RegExp(`^${Eg(n)}$`)}function pt(n){let i=Eg({precision:n.precision}),o=["Z"];if(n.local)o.push("");if(n.offset)o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let e=`${i}(?:${o.join("|")})`;return new RegExp(`^${dg}T(?:${e})$`)}var st=(n)=>{let i=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${i}$`)},ro=/^-?\d+n?$/,no=/^-?\d+$/,gn=/^-?\d+(?:\.\d+)?$/,io=/^(?:true|false)$/i,to=/^null$/i;var oo=/^undefined$/i;var eo=/^[^A-Z]*$/,vo=/^[^a-z]*$/,zb=/^[0-9a-fA-F]*$/;function ln(n,i){return new RegExp(`^[A-Za-z0-9+/]{${n}}${i}$`)}function cn(n){return new RegExp(`^[A-Za-z0-9_-]{${n}}$`)}var Ob=/^[0-9a-fA-F]{32}$/,jb=ln(22,"=="),Pb=cn(22),Jb=/^[0-9a-fA-F]{40}$/,db=ln(27,"="),Eb=cn(27),Lb=/^[0-9a-fA-F]{64}$/,Gb=ln(43,"="),Wb=cn(43),Ab=/^[0-9a-fA-F]{96}$/,Vb=ln(64,""),Xb=cn(64),qb=/^[0-9a-fA-F]{128}$/,Kb=ln(86,"=="),Yb=cn(86);var E=l("$ZodCheck",(n,i)=>{var o;n._zod??(n._zod={}),n._zod.def=i,(o=n._zod).onattach??(o.onattach=[])}),Gg={number:"number",bigint:"bigint",object:"date"},hn=l("$ZodCheckLessThan",(n,i)=>{E.init(n,i);let o=Gg[typeof i.value];n._zod.onattach.push((e)=>{let r=e._zod.bag,t=(i.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(i.value<t)if(i.inclusive)r.maximum=i.value;else r.exclusiveMaximum=i.value}),n._zod.check=(e)=>{if(i.inclusive?e.value<=i.value:e.value<i.value)return;e.issues.push({origin:o,code:"too_big",maximum:typeof i.value==="object"?i.value.getTime():i.value,input:e.value,inclusive:i.inclusive,inst:n,continue:!i.abort})}}),an=l("$ZodCheckGreaterThan",(n,i)=>{E.init(n,i);let o=Gg[typeof i.value];n._zod.onattach.push((e)=>{let r=e._zod.bag,t=(i.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(i.value>t)if(i.inclusive)r.minimum=i.value;else r.exclusiveMinimum=i.value}),n._zod.check=(e)=>{if(i.inclusive?e.value>=i.value:e.value>i.value)return;e.issues.push({origin:o,code:"too_small",minimum:typeof i.value==="object"?i.value.getTime():i.value,input:e.value,inclusive:i.inclusive,inst:n,continue:!i.abort})}}),uo=l("$ZodCheckMultipleOf",(n,i)=>{E.init(n,i),n._zod.onattach.push((o)=>{var e;(e=o._zod.bag).multipleOf??(e.multipleOf=i.value)}),n._zod.check=(o)=>{if(typeof o.value!==typeof i.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof o.value==="bigint"?o.value%i.value===BigInt(0):mt(o.value,i.value)===0)return;o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:i.value,input:o.value,inst:n,continue:!i.abort})}}),$o=l("$ZodCheckNumberFormat",(n,i)=>{E.init(n,i),i.format=i.format||"float64";let o=i.format?.includes("int"),e=o?"int":"number",[r,t]=Pt[i.format];n._zod.onattach.push((v)=>{let u=v._zod.bag;if(u.format=i.format,u.minimum=r,u.maximum=t,o)u.pattern=no}),n._zod.check=(v)=>{let u=v.value;if(o){if(!Number.isInteger(u)){v.issues.push({expected:e,format:i.format,code:"invalid_type",continue:!1,input:u,inst:n});return}if(!Number.isSafeInteger(u)){if(u>0)v.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:e,inclusive:!0,continue:!i.abort});else v.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:e,inclusive:!0,continue:!i.abort});return}}if(u<r)v.issues.push({origin:"number",input:u,code:"too_small",minimum:r,inclusive:!0,inst:n,continue:!i.abort});if(u>t)v.issues.push({origin:"number",input:u,code:"too_big",maximum:t,inclusive:!0,inst:n,continue:!i.abort})}}),go=l("$ZodCheckBigIntFormat",(n,i)=>{E.init(n,i);let[o,e]=Jt[i.format];n._zod.onattach.push((r)=>{let t=r._zod.bag;t.format=i.format,t.minimum=o,t.maximum=e}),n._zod.check=(r)=>{let t=r.value;if(t<o)r.issues.push({origin:"bigint",input:t,code:"too_small",minimum:o,inclusive:!0,inst:n,continue:!i.abort});if(t>e)r.issues.push({origin:"bigint",input:t,code:"too_big",maximum:e,inclusive:!0,inst:n,continue:!i.abort})}}),lo=l("$ZodCheckMaxSize",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.size!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;if(i.maximum<r)e._zod.bag.maximum=i.maximum}),n._zod.check=(e)=>{let r=e.value;if(r.size<=i.maximum)return;e.issues.push({origin:on(r),code:"too_big",maximum:i.maximum,inclusive:!0,input:r,inst:n,continue:!i.abort})}}),co=l("$ZodCheckMinSize",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.size!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(i.minimum>r)e._zod.bag.minimum=i.minimum}),n._zod.check=(e)=>{let r=e.value;if(r.size>=i.minimum)return;e.issues.push({origin:on(r),code:"too_small",minimum:i.minimum,inclusive:!0,input:r,inst:n,continue:!i.abort})}}),bo=l("$ZodCheckSizeEquals",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.size!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag;r.minimum=i.size,r.maximum=i.size,r.size=i.size}),n._zod.check=(e)=>{let r=e.value,t=r.size;if(t===i.size)return;let v=t>i.size;e.issues.push({origin:on(r),...v?{code:"too_big",maximum:i.size}:{code:"too_small",minimum:i.size},inclusive:!0,exact:!0,input:e.value,inst:n,continue:!i.abort})}}),Io=l("$ZodCheckMaxLength",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.length!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;if(i.maximum<r)e._zod.bag.maximum=i.maximum}),n._zod.check=(e)=>{let r=e.value;if(r.length<=i.maximum)return;let v=en(r);e.issues.push({origin:v,code:"too_big",maximum:i.maximum,inclusive:!0,input:r,inst:n,continue:!i.abort})}}),_o=l("$ZodCheckMinLength",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.length!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(i.minimum>r)e._zod.bag.minimum=i.minimum}),n._zod.check=(e)=>{let r=e.value;if(r.length>=i.minimum)return;let v=en(r);e.issues.push({origin:v,code:"too_small",minimum:i.minimum,inclusive:!0,input:r,inst:n,continue:!i.abort})}}),Uo=l("$ZodCheckLengthEquals",(n,i)=>{var o;E.init(n,i),(o=n._zod.def).when??(o.when=(e)=>{let r=e.value;return!tr(r)&&r.length!==void 0}),n._zod.onattach.push((e)=>{let r=e._zod.bag;r.minimum=i.length,r.maximum=i.length,r.length=i.length}),n._zod.check=(e)=>{let r=e.value,t=r.length;if(t===i.length)return;let v=en(r),u=t>i.length;e.issues.push({origin:v,...u?{code:"too_big",maximum:i.length}:{code:"too_small",minimum:i.length},inclusive:!0,exact:!0,input:e.value,inst:n,continue:!i.abort})}}),Lr=l("$ZodCheckStringFormat",(n,i)=>{var o,e;if(E.init(n,i),n._zod.onattach.push((r)=>{let t=r._zod.bag;if(t.format=i.format,i.pattern)t.patterns??(t.patterns=new Set),t.patterns.add(i.pattern)}),i.pattern)(o=n._zod).check??(o.check=(r)=>{if(i.pattern.lastIndex=0,i.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:i.format,input:r.value,...i.pattern?{pattern:i.pattern.toString()}:{},inst:n,continue:!i.abort})});else(e=n._zod).check??(e.check=()=>{})}),ko=l("$ZodCheckRegex",(n,i)=>{Lr.init(n,i),n._zod.check=(o)=>{if(i.pattern.lastIndex=0,i.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:i.pattern.toString(),inst:n,continue:!i.abort})}}),Do=l("$ZodCheckLowerCase",(n,i)=>{i.pattern??(i.pattern=eo),Lr.init(n,i)}),wo=l("$ZodCheckUpperCase",(n,i)=>{i.pattern??(i.pattern=vo),Lr.init(n,i)}),mo=l("$ZodCheckIncludes",(n,i)=>{E.init(n,i);let o=R(i.includes),e=new RegExp(typeof i.position==="number"?`^.{${i.position}}${o}`:o);i.pattern=e,n._zod.onattach.push((r)=>{let t=r._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(e)}),n._zod.check=(r)=>{if(r.value.includes(i.includes,i.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:i.includes,input:r.value,inst:n,continue:!i.abort})}}),So=l("$ZodCheckStartsWith",(n,i)=>{E.init(n,i);let o=new RegExp(`^${R(i.prefix)}.*`);i.pattern??(i.pattern=o),n._zod.onattach.push((e)=>{let r=e._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),n._zod.check=(e)=>{if(e.value.startsWith(i.prefix))return;e.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:i.prefix,input:e.value,inst:n,continue:!i.abort})}}),No=l("$ZodCheckEndsWith",(n,i)=>{E.init(n,i);let o=new RegExp(`.*${R(i.suffix)}$`);i.pattern??(i.pattern=o),n._zod.onattach.push((e)=>{let r=e._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),n._zod.check=(e)=>{if(e.value.endsWith(i.suffix))return;e.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:i.suffix,input:e.value,inst:n,continue:!i.abort})}});function Lg(n,i,o){if(n.issues.length)i.issues.push(...F(o,n.issues))}var zo=l("$ZodCheckProperty",(n,i)=>{E.init(n,i),n._zod.check=(o)=>{let e=i.schema._zod.run({value:o.value[i.property],issues:[]},{});if(e instanceof Promise)return e.then((r)=>Lg(r,o,i.property));Lg(e,o,i.property);return}}),Oo=l("$ZodCheckMimeType",(n,i)=>{E.init(n,i);let o=new Set(i.mime);n._zod.onattach.push((e)=>{e._zod.bag.mime=i.mime}),n._zod.check=(e)=>{if(o.has(e.value.type))return;e.issues.push({code:"invalid_value",values:i.mime,input:e.value.type,inst:n,continue:!i.abort})}}),jo=l("$ZodCheckOverwrite",(n,i)=>{E.init(n,i),n._zod.check=(o)=>{o.value=i.tx(o.value)}});class yn{constructor(n=[]){if(this.content=[],this.indent=0,this)this.args=n}indented(n){this.indent+=1,n(this),this.indent-=1}write(n){if(typeof n==="function"){n(this,{execution:"sync"}),n(this,{execution:"async"});return}let o=n.split(`
4
4
  `).filter((t)=>t),e=Math.min(...o.map((t)=>t.length-t.trimStart().length)),r=o.map((t)=>t.slice(e)).map((t)=>" ".repeat(this.indent*2)+t);for(let t of r)this.content.push(t)}compile(){let n=Function,i=this?.args,e=[...(this?.content??[""]).map((r)=>` ${r}`)];return new n(...i,e.join(`
5
5
  `))}}var Po={major:4,minor:4,patch:3};var z=l("$ZodType",(n,i)=>{var o;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=Po;let e=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))e.unshift(n);for(let r of e)for(let t of r._zod.onattach)t(n);if(e.length===0)(o=n._zod).deferred??(o.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let r=(v,u,g)=>{let $=vr(v),c;for(let I of u){if(I._zod.def.when){if(dt(v))continue;if(!I._zod.def.when(v))continue}else if($)continue;let m=v.issues.length,D=I._zod.check(v);if(D instanceof Promise&&g?.async===!1)throw new C;if(c||D instanceof Promise)c=(c??Promise.resolve()).then(async()=>{if(await D,v.issues.length===m)return;if(!$)$=vr(v,m)});else{if(v.issues.length===m)continue;if(!$)$=vr(v,m)}}if(c)return c.then(()=>{return v});return v},t=(v,u,g)=>{if(vr(v))return v.aborted=!0,v;let $=r(u,e,g);if($ instanceof Promise){if(g.async===!1)throw new C;return $.then((c)=>n._zod.parse(c,g))}return n._zod.parse($,g)};n._zod.run=(v,u)=>{if(u.skipChecks)return n._zod.parse(v,u);if(u.direction==="backward"){let $=n._zod.parse({value:v.value,issues:[]},{...u,skipChecks:!0});if($ instanceof Promise)return $.then((c)=>{return t(c,v,u)});return t($,v,u)}let g=n._zod.parse(v,u);if(g instanceof Promise){if(u.async===!1)throw new C;return g.then(($)=>r($,e,u))}return r(g,e,u)}}j(n,"~standard",()=>({validate:(r)=>{try{let t=Gt(n,r);return t.success?{value:t.data}:{issues:t.error?.issues}}catch(t){return Wt(n,r).then((v)=>v.success?{value:v.data}:{issues:v.error?.issues})}},vendor:"zod",version:1}))}),kr=l("$ZodString",(n,i)=>{z.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??st(n._zod.bag),n._zod.parse=(o,e)=>{if(i.coerce)try{o.value=String(o.value)}catch(r){}if(typeof o.value==="string")return o;return o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:n}),o}}),J=l("$ZodStringFormat",(n,i)=>{Lr.init(n,i),kr.init(n,i)}),Eo=l("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=Tt),J.init(n,i)}),Lo=l("$ZodUUID",(n,i)=>{if(i.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(e===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=Ur(e))}else i.pattern??(i.pattern=Ur());J.init(n,i)}),Go=l("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=Ft),J.init(n,i)}),Wo=l("$ZodURL",(n,i)=>{J.init(n,i),n._zod.check=(o)=>{try{let e=o.value.trim();if(!i.normalize&&i.protocol?.source===Ct.source){if(!/^https?:\/\//i.test(e)){o.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:o.value,inst:n,continue:!i.abort});return}}let r=new URL(e);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(r.hostname))o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:o.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:o.value,inst:n,continue:!i.abort})}if(i.normalize)o.value=r.href;else o.value=e;return}catch(e){o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:n,continue:!i.abort})}}}),Ao=l("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=Bt()),J.init(n,i)}),Vo=l("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=Yt),J.init(n,i)}),Xo=l("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=At),J.init(n,i)}),qo=l("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=Vt),J.init(n,i)}),Ko=l("$ZodULID",(n,i)=>{i.pattern??(i.pattern=Xt),J.init(n,i)}),Yo=l("$ZodXID",(n,i)=>{i.pattern??(i.pattern=qt),J.init(n,i)}),Qo=l("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=Kt),J.init(n,i)}),To=l("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=pt(i)),J.init(n,i)}),Fo=l("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=at),J.init(n,i)}),Bo=l("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=yt(i)),J.init(n,i)}),Ho=l("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=Qt),J.init(n,i)}),Mo=l("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=Ht),J.init(n,i),n._zod.bag.format="ipv4"}),xo=l("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=Mt),J.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(o)=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:n,continue:!i.abort})}}}),Ro=l("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=xt(i.delimiter)),J.init(n,i),n._zod.bag.format="mac"}),fo=l("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=Rt),J.init(n,i)}),Zo=l("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=ft),J.init(n,i),n._zod.check=(o)=>{let e=o.value.split("/");try{if(e.length!==2)throw Error();let[r,t]=e;if(!t)throw Error();let v=Number(t);if(`${v}`!==t)throw Error();if(v<0||v>128)throw Error();new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:n,continue:!i.abort})}}});function Co(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var ho=l("$ZodBase64",(n,i)=>{i.pattern??(i.pattern=Zt),J.init(n,i),n._zod.bag.contentEncoding="base64",n._zod.check=(o)=>{if(Co(o.value))return;o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:n,continue:!i.abort})}});function fg(n){if(!Cn.test(n))return!1;let i=n.replace(/[-_]/g,(e)=>e==="-"?"+":"/"),o=i.padEnd(Math.ceil(i.length/4)*4,"=");return Co(o)}var ao=l("$ZodBase64URL",(n,i)=>{i.pattern??(i.pattern=Cn),J.init(n,i),n._zod.bag.contentEncoding="base64url",n._zod.check=(o)=>{if(fg(o.value))return;o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:n,continue:!i.abort})}}),yo=l("$ZodE164",(n,i)=>{i.pattern??(i.pattern=ht),J.init(n,i)});function Zg(n,i=null){try{let o=n.split(".");if(o.length!==3)return!1;let[e]=o;if(!e)return!1;let r=JSON.parse(atob(e));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(i&&(!("alg"in r)||r.alg!==i))return!1;return!0}catch{return!1}}var po=l("$ZodJWT",(n,i)=>{J.init(n,i),n._zod.check=(o)=>{if(Zg(o.value,i.alg))return;o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:n,continue:!i.abort})}}),so=l("$ZodCustomStringFormat",(n,i)=>{J.init(n,i),n._zod.check=(o)=>{if(i.fn(o.value))return;o.issues.push({code:"invalid_format",format:i.format,input:o.value,inst:n,continue:!i.abort})}}),ii=l("$ZodNumber",(n,i)=>{z.init(n,i),n._zod.pattern=n._zod.bag.pattern??gn,n._zod.parse=(o,e)=>{if(i.coerce)try{o.value=Number(o.value)}catch(v){}let r=o.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;let t=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:n,...t?{received:t}:{}}),o}}),re=l("$ZodNumberFormat",(n,i)=>{$o.init(n,i),ii.init(n,i)}),bn=l("$ZodBoolean",(n,i)=>{z.init(n,i),n._zod.pattern=io,n._zod.parse=(o,e)=>{if(i.coerce)try{o.value=Boolean(o.value)}catch(t){}let r=o.value;if(typeof r==="boolean")return o;return o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:n}),o}}),ti=l("$ZodBigInt",(n,i)=>{z.init(n,i),n._zod.pattern=ro,n._zod.parse=(o,e)=>{if(i.coerce)try{o.value=BigInt(o.value)}catch(r){}if(typeof o.value==="bigint")return o;return o.issues.push({expected:"bigint",code:"invalid_type",input:o.value,inst:n}),o}}),ne=l("$ZodBigIntFormat",(n,i)=>{go.init(n,i),ti.init(n,i)}),ie=l("$ZodSymbol",(n,i)=>{z.init(n,i),n._zod.parse=(o,e)=>{let r=o.value;if(typeof r==="symbol")return o;return o.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:n}),o}}),te=l("$ZodUndefined",(n,i)=>{z.init(n,i),n._zod.pattern=oo,n._zod.values=new Set([void 0]),n._zod.parse=(o,e)=>{let r=o.value;if(typeof r>"u")return o;return o.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:n}),o}}),oe=l("$ZodNull",(n,i)=>{z.init(n,i),n._zod.pattern=to,n._zod.values=new Set([null]),n._zod.parse=(o,e)=>{let r=o.value;if(r===null)return o;return o.issues.push({expected:"null",code:"invalid_type",input:r,inst:n}),o}}),ee=l("$ZodAny",(n,i)=>{z.init(n,i),n._zod.parse=(o)=>o}),ve=l("$ZodUnknown",(n,i)=>{z.init(n,i),n._zod.parse=(o)=>o}),ue=l("$ZodNever",(n,i)=>{z.init(n,i),n._zod.parse=(o,e)=>{return o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:n}),o}}),$e=l("$ZodVoid",(n,i)=>{z.init(n,i),n._zod.parse=(o,e)=>{let r=o.value;if(typeof r>"u")return o;return o.issues.push({expected:"void",code:"invalid_type",input:r,inst:n}),o}}),ge=l("$ZodDate",(n,i)=>{z.init(n,i),n._zod.parse=(o,e)=>{if(i.coerce)try{o.value=new Date(o.value)}catch(u){}let r=o.value,t=r instanceof Date;if(t&&!Number.isNaN(r.getTime()))return o;return o.issues.push({expected:"date",code:"invalid_type",input:r,...t?{received:"Invalid Date"}:{},inst:n}),o}});function Ag(n,i,o){if(n.issues.length)i.issues.push(...F(o,n.issues));i.value[o]=n.value}var le=l("$ZodArray",(n,i)=>{z.init(n,i),n._zod.parse=(o,e)=>{let r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:n}),o;o.value=Array(r.length);let t=[];for(let v=0;v<r.length;v++){let u=r[v],g=i.element._zod.run({value:u,issues:[]},e);if(g instanceof Promise)t.push(g.then(($)=>Ag($,o,v)));else Ag(g,o,v)}if(t.length)return Promise.all(t).then(()=>o);return o}});function ni(n,i,o,e,r,t){let v=o in e;if(n.issues.length){if(r&&t&&!v)return;i.issues.push(...F(o,n.issues))}if(!v&&!r){if(!n.issues.length)i.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[o]});return}if(n.value===void 0){if(v)i.value[o]=void 0}else i.value[o]=n.value}function Cg(n){let i=Object.keys(n.shape);for(let e of i)if(!n.shape?.[e]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${e}": expected a Zod schema`);let o=jt(n.shape);return{...n,keys:i,keySet:new Set(i),numKeys:i.length,optionalKeys:new Set(o)}}function hg(n,i,o,e,r,t){let v=[],u=r.keySet,g=r.catchall._zod,$=g.def.type,c=g.optin==="optional",I=g.optout==="optional";for(let m in i){if(m==="__proto__")continue;if(u.has(m))continue;if($==="never"){v.push(m);continue}let D=g.run({value:i[m],issues:[]},e);if(D instanceof Promise)n.push(D.then((N)=>ni(N,o,m,i,c,I)));else ni(D,o,m,i,c,I)}if(v.length)o.issues.push({code:"unrecognized_keys",keys:v,input:i,inst:t});if(!n.length)return o;return Promise.all(n).then(()=>{return o})}var ag=l("$ZodObject",(n,i)=>{if(z.init(n,i),!Object.getOwnPropertyDescriptor(i,"shape")?.get){let u=i.shape;Object.defineProperty(i,"shape",{get:()=>{let g={...u};return Object.defineProperty(i,"shape",{value:g}),g}})}let e=Or(()=>Cg(i));j(n._zod,"propValues",()=>{let u=i.shape,g={};for(let $ in u){let c=u[$]._zod;if(c.values){g[$]??(g[$]=new Set);for(let I of c.values)g[$].add(I)}}return g});let r=_r,t=i.catchall,v;n._zod.parse=(u,g)=>{v??(v=e.value);let $=u.value;if(!r($))return u.issues.push({expected:"object",code:"invalid_type",input:$,inst:n}),u;u.value={};let c=[],I=v.shape;for(let m of v.keys){let D=I[m],N=D._zod.optin==="optional",T=D._zod.optout==="optional",W=D._zod.run({value:$[m],issues:[]},g);if(W instanceof Promise)c.push(W.then((Ut)=>ni(Ut,u,m,$,N,T)));else ni(W,u,m,$,N,T)}if(!t)return c.length?Promise.all(c).then(()=>u):u;return hg(c,$,u,g,e.value,n)}}),ce=l("$ZodObjectJIT",(n,i)=>{ag.init(n,i);let o=n._zod.parse,e=Or(()=>Cg(i)),r=(m)=>{let D=new yn(["shape","payload","ctx"]),N=e.value,T=(Z)=>{let L=Kn(Z);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};D.write("const input = payload.value;");let W=Object.create(null),Ut=0;for(let Z of N.keys)W[Z]=`key_${Ut++}`;D.write("const newResult = {};");for(let Z of N.keys){let L=W[Z],A=Kn(Z),kg=m[Z],Dg=kg?._zod?.optin==="optional",jc=kg?._zod?.optout==="optional";if(D.write(`const ${L} = ${T(Z)};`),Dg&&jc)D.write(`
@@ -65,5 +65,5 @@ var Pc=Object.defineProperty;var Jc=(n)=>n;function dc(n,i){this[n]=Jc.bind(null
65
65
 
66
66
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let v of n.seen.entries()){let u=v[1];if(i===v[0]){t(v);continue}if(n.external){let $=n.external.registry.get(v[0])?.id;if(i!==v[0]&&$){t(v);continue}}if(n.metadataRegistry.get(v[0])?.id){t(v);continue}if(u.cycle){t(v);continue}if(u.count>1){if(n.reused==="ref"){t(v);continue}}}}function cr(n,i){let o=n.seen.get(i);if(!o)throw Error("Unprocessed schema. This is a bug in Zod.");let e=(u)=>{let g=n.seen.get(u);if(g.ref===null)return;let $=g.def??g.schema,c={...$},I=g.ref;if(g.ref=null,I){e(I);let D=n.seen.get(I),N=D.schema;if(N.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))$.allOf=$.allOf??[],$.allOf.push(N);else Object.assign($,N);if(Object.assign($,c),u._zod.parent===I)for(let W in $){if(W==="$ref"||W==="allOf")continue;if(!(W in c))delete $[W]}if(N.$ref&&D.def)for(let W in $){if(W==="$ref"||W==="allOf")continue;if(W in D.def&&JSON.stringify($[W])===JSON.stringify(D.def[W]))delete $[W]}}let m=u._zod.parent;if(m&&m!==I){e(m);let D=n.seen.get(m);if(D?.schema.$ref){if($.$ref=D.schema.$ref,D.def)for(let N in $){if(N==="$ref"||N==="allOf")continue;if(N in D.def&&JSON.stringify($[N])===JSON.stringify(D.def[N]))delete $[N]}}}n.override({zodSchema:u,jsonSchema:$,path:g.path??[]})};for(let u of[...n.seen.entries()].reverse())e(u[0]);let r={};if(n.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let u=n.external.registry.get(i)?.id;if(!u)throw Error("Schema is missing an `id` property");r.$id=n.external.uri(u)}Object.assign(r,o.def??o.schema);let t=n.metadataRegistry.get(i)?.id;if(t!==void 0&&r.id===t)delete r.id;let v=n.external?.defs??{};for(let u of n.seen.entries()){let g=u[1];if(g.def&&g.defId){if(g.def.id===g.defId)delete g.def.id;v[g.defId]=g.def}}if(n.external);else if(Object.keys(v).length>0)if(n.target==="draft-2020-12")r.$defs=v;else r.definitions=v;try{let u=JSON.parse(JSON.stringify(r));return Object.defineProperty(u,"~standard",{value:{...i["~standard"],jsonSchema:{input:xr(i,"input",n.processors),output:xr(i,"output",n.processors)}},enumerable:!1,writable:!1}),u}catch(u){throw Error("Error converting schema to JSON.")}}function Q(n,i){let o=i??{seen:new Set};if(o.seen.has(n))return!1;o.seen.add(n);let e=n._zod.def;if(e.type==="transform")return!0;if(e.type==="array")return Q(e.element,o);if(e.type==="set")return Q(e.valueType,o);if(e.type==="lazy")return Q(e.getter(),o);if(e.type==="promise"||e.type==="optional"||e.type==="nonoptional"||e.type==="nullable"||e.type==="readonly"||e.type==="default"||e.type==="prefault")return Q(e.innerType,o);if(e.type==="intersection")return Q(e.left,o)||Q(e.right,o);if(e.type==="record"||e.type==="map")return Q(e.keyType,o)||Q(e.valueType,o);if(e.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return Q(e.in,o)||Q(e.out,o)}if(e.type==="object"){for(let r in e.shape)if(Q(e.shape[r],o))return!0;return!1}if(e.type==="union"){for(let r of e.options)if(Q(r,o))return!0;return!1}if(e.type==="tuple"){for(let r of e.items)if(Q(r,o))return!0;if(e.rest&&Q(e.rest,o))return!0;return!1}return!1}var Su=(n,i={})=>(o)=>{let e=gr({...o,processors:i});return P(n,e),lr(e,n),cr(e,n)},xr=(n,i,o={})=>(e)=>{let{libraryOptions:r,target:t}=e??{},v=gr({...r??{},target:t,io:i,processors:o});return P(n,v),lr(v,n),cr(v,n)};var e4={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Nu=(n,i,o,e)=>{let r=o;r.type="string";let{minimum:t,maximum:v,format:u,patterns:g,contentEncoding:$}=n._zod.bag;if(typeof t==="number")r.minLength=t;if(typeof v==="number")r.maxLength=v;if(u){if(r.format=e4[u]??u,r.format==="")delete r.format;if(u==="time")delete r.format}if($)r.contentEncoding=$;if(g&&g.size>0){let c=[...g];if(c.length===1)r.pattern=c[0].source;else if(c.length>1)r.allOf=[...c.map((I)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:I.source}))]}},zu=(n,i,o,e)=>{let r=o,{minimum:t,maximum:v,format:u,multipleOf:g,exclusiveMaximum:$,exclusiveMinimum:c}=n._zod.bag;if(typeof u==="string"&&u.includes("int"))r.type="integer";else r.type="number";let I=typeof c==="number"&&c>=(t??Number.NEGATIVE_INFINITY),m=typeof $==="number"&&$<=(v??Number.POSITIVE_INFINITY),D=i.target==="draft-04"||i.target==="openapi-3.0";if(I)if(D)r.minimum=c,r.exclusiveMinimum=!0;else r.exclusiveMinimum=c;else if(typeof t==="number")r.minimum=t;if(m)if(D)r.maximum=$,r.exclusiveMaximum=!0;else r.exclusiveMaximum=$;else if(typeof v==="number")r.maximum=v;if(typeof g==="number")r.multipleOf=g},Ou=(n,i,o,e)=>{o.type="boolean"},ju=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Pu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},Ju=(n,i,o,e)=>{if(i.target==="openapi-3.0")o.type="string",o.nullable=!0,o.enum=[null];else o.type="null"},du=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},Eu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Lu=(n,i,o,e)=>{o.not={}},Gu=(n,i,o,e)=>{},Wu=(n,i,o,e)=>{},Au=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Vu=(n,i,o,e)=>{let r=n._zod.def,t=rn(r.entries);if(t.every((v)=>typeof v==="number"))o.type="number";if(t.every((v)=>typeof v==="string"))o.type="string";o.enum=t},Xu=(n,i,o,e)=>{let r=n._zod.def,t=[];for(let v of r.values)if(v===void 0){if(i.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v==="bigint")if(i.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else t.push(Number(v));else t.push(v);if(t.length===0);else if(t.length===1){let v=t[0];if(o.type=v===null?"null":typeof v,i.target==="draft-04"||i.target==="openapi-3.0")o.enum=[v];else o.const=v}else{if(t.every((v)=>typeof v==="number"))o.type="number";if(t.every((v)=>typeof v==="string"))o.type="string";if(t.every((v)=>typeof v==="boolean"))o.type="boolean";if(t.every((v)=>v===null))o.type="null";o.enum=t}},qu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},Ku=(n,i,o,e)=>{let r=o,t=n._zod.pattern;if(!t)throw Error("Pattern not found in template literal");r.type="string",r.pattern=t.source},Yu=(n,i,o,e)=>{let r=o,t={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:u,mime:g}=n._zod.bag;if(v!==void 0)t.minLength=v;if(u!==void 0)t.maxLength=u;if(g)if(g.length===1)t.contentMediaType=g[0],Object.assign(r,t);else Object.assign(r,t),r.anyOf=g.map(($)=>({contentMediaType:$}));else Object.assign(r,t)},Qu=(n,i,o,e)=>{o.type="boolean"},Tu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Fu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Bu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Hu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Mu=(n,i,o,e)=>{if(i.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},xu=(n,i,o,e)=>{let r=o,t=n._zod.def,{minimum:v,maximum:u}=n._zod.bag;if(typeof v==="number")r.minItems=v;if(typeof u==="number")r.maxItems=u;r.type="array",r.items=P(t.element,i,{...e,path:[...e.path,"items"]})},Ru=(n,i,o,e)=>{let r=o,t=n._zod.def;r.type="object",r.properties={};let v=t.shape;for(let $ in v)r.properties[$]=P(v[$],i,{...e,path:[...e.path,"properties",$]});let u=new Set(Object.keys(v)),g=new Set([...u].filter(($)=>{let c=t.shape[$]._zod;if(i.io==="input")return c.optin===void 0;else return c.optout===void 0}));if(g.size>0)r.required=Array.from(g);if(t.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!t.catchall){if(i.io==="output")r.additionalProperties=!1}else if(t.catchall)r.additionalProperties=P(t.catchall,i,{...e,path:[...e.path,"additionalProperties"]})},Xi=(n,i,o,e)=>{let r=n._zod.def,t=r.inclusive===!1,v=r.options.map((u,g)=>P(u,i,{...e,path:[...e.path,t?"oneOf":"anyOf",g]}));if(t)o.oneOf=v;else o.anyOf=v},fu=(n,i,o,e)=>{let r=n._zod.def,t=P(r.left,i,{...e,path:[...e.path,"allOf",0]}),v=P(r.right,i,{...e,path:[...e.path,"allOf",1]}),u=($)=>("allOf"in $)&&Object.keys($).length===1,g=[...u(t)?t.allOf:[t],...u(v)?v.allOf:[v]];o.allOf=g},Zu=(n,i,o,e)=>{let r=o,t=n._zod.def;r.type="array";let v=i.target==="draft-2020-12"?"prefixItems":"items",u=i.target==="draft-2020-12"?"items":i.target==="openapi-3.0"?"items":"additionalItems",g=t.items.map((m,D)=>P(m,i,{...e,path:[...e.path,v,D]})),$=t.rest?P(t.rest,i,{...e,path:[...e.path,u,...i.target==="openapi-3.0"?[t.items.length]:[]]}):null;if(i.target==="draft-2020-12"){if(r.prefixItems=g,$)r.items=$}else if(i.target==="openapi-3.0"){if(r.items={anyOf:g},$)r.items.anyOf.push($);if(r.minItems=g.length,!$)r.maxItems=g.length}else if(r.items=g,$)r.additionalItems=$;let{minimum:c,maximum:I}=n._zod.bag;if(typeof c==="number")r.minItems=c;if(typeof I==="number")r.maxItems=I},Cu=(n,i,o,e)=>{let r=o,t=n._zod.def;r.type="object";let v=t.keyType,g=v._zod.bag?.patterns;if(t.mode==="loose"&&g&&g.size>0){let c=P(t.valueType,i,{...e,path:[...e.path,"patternProperties","*"]});r.patternProperties={};for(let I of g)r.patternProperties[I.source]=c}else{if(i.target==="draft-07"||i.target==="draft-2020-12")r.propertyNames=P(t.keyType,i,{...e,path:[...e.path,"propertyNames"]});r.additionalProperties=P(t.valueType,i,{...e,path:[...e.path,"additionalProperties"]})}let $=v._zod.values;if($){let c=[...$].filter((I)=>typeof I==="string"||typeof I==="number");if(c.length>0)r.required=c}},hu=(n,i,o,e)=>{let r=n._zod.def,t=P(r.innerType,i,e),v=i.seen.get(n);if(i.target==="openapi-3.0")v.ref=r.innerType,o.nullable=!0;else o.anyOf=[t,{type:"null"}]},au=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType},yu=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},pu=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);if(t.ref=r.innerType,i.io==="input")o._prefault=JSON.parse(JSON.stringify(r.defaultValue))},su=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType;let v;try{v=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}o.default=v},r$=(n,i,o,e)=>{let r=n._zod.def,t=r.in._zod.traits.has("$ZodTransform"),v=i.io==="input"?t?r.out:r.in:r.out;P(v,i,e);let u=i.seen.get(n);u.ref=v},n$=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType,o.readOnly=!0},i$=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType},qi=(n,i,o,e)=>{let r=n._zod.def;P(r.innerType,i,e);let t=i.seen.get(n);t.ref=r.innerType},t$=(n,i,o,e)=>{let r=n._zod.innerType;P(r,i,e);let t=i.seen.get(n);t.ref=r},Vi={string:Nu,number:zu,boolean:Ou,bigint:ju,symbol:Pu,null:Ju,undefined:du,void:Eu,never:Lu,any:Gu,unknown:Wu,date:Au,enum:Vu,literal:Xu,nan:qu,template_literal:Ku,file:Yu,success:Qu,custom:Tu,function:Fu,transform:Bu,map:Hu,set:Mu,array:xu,object:Ru,union:Xi,intersection:fu,tuple:Zu,record:Cu,nullable:hu,nonoptional:au,default:yu,prefault:pu,catch:su,pipe:r$,readonly:n$,promise:i$,optional:qi,lazy:t$};function Ki(n,i){if("_idmap"in n){let e=n,r=gr({...i,processors:Vi}),t={};for(let g of e._idmap.entries()){let[$,c]=g;P(c,r)}let v={},u={registry:e,uri:i?.uri,defs:t};r.external=u;for(let g of e._idmap.entries()){let[$,c]=g;lr(r,c),v[$]=cr(r,c)}if(Object.keys(t).length>0){let g=r.target==="draft-2020-12"?"$defs":"definitions";v.__shared={[g]:t}}return{schemas:v}}let o=gr({...i,processors:Vi});return P(n,o),lr(o,n),cr(o,n)}class o${get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(n){this.ctx.counter=n}get seen(){return this.ctx.seen}constructor(n){let i=n?.target??"draft-2020-12";if(i==="draft-4")i="draft-04";if(i==="draft-7")i="draft-07";this.ctx=gr({processors:Vi,target:i,...n?.metadata&&{metadata:n.metadata},...n?.unrepresentable&&{unrepresentable:n.unrepresentable},...n?.override&&{override:n.override},...n?.io&&{io:n.io}})}process(n,i={path:[],schemaPath:[]}){return P(n,this.ctx,i)}emit(n,i){if(i){if(i.cycles)this.ctx.cycles=i.cycles;if(i.reused)this.ctx.reused=i.reused;if(i.external)this.ctx.external=i.external}lr(this.ctx,n);let o=cr(this.ctx,n),{"~standard":e,...r}=o;return r}}var tl={};var zn={};s(zn,{xor:()=>al,xid:()=>ml,void:()=>xl,uuidv7:()=>cl,uuidv6:()=>ll,uuidv4:()=>gl,uuid:()=>$l,url:()=>bl,unknown:()=>Sr,union:()=>gt,undefined:()=>Hl,ulid:()=>wl,uint64:()=>Fl,uint32:()=>Yl,tuple:()=>T$,transform:()=>ct,templateLiteral:()=>lc,symbol:()=>Bl,superRefine:()=>Ig,success:()=>vc,stringbool:()=>wc,stringFormat:()=>Gl,string:()=>On,strictObject:()=>Cl,set:()=>nc,refine:()=>bg,record:()=>F$,readonly:()=>vg,promise:()=>cc,preprocess:()=>Sc,prefault:()=>p$,pipe:()=>Mi,partialRecord:()=>pl,optional:()=>Pn,object:()=>Zl,number:()=>O$,nullish:()=>ec,nullable:()=>Jn,null:()=>E$,nonoptional:()=>s$,never:()=>$t,nativeEnum:()=>ic,nanoid:()=>Ul,nan:()=>uc,meta:()=>kc,map:()=>rc,mac:()=>zl,looseRecord:()=>sl,looseObject:()=>hl,literal:()=>tc,lazy:()=>gg,ksuid:()=>Sl,keyof:()=>fl,jwt:()=>Ll,json:()=>mc,ipv6:()=>Ol,ipv4:()=>Nl,invertCodec:()=>gc,intersection:()=>Y$,int64:()=>Tl,int32:()=>Kl,int:()=>Hi,instanceof:()=>Dc,httpUrl:()=>Il,hostname:()=>Wl,hex:()=>Al,hash:()=>Vl,guid:()=>ul,function:()=>bc,float64:()=>ql,float32:()=>Xl,file:()=>oc,exactOptional:()=>Z$,enum:()=>lt,emoji:()=>_l,email:()=>vl,e164:()=>El,discriminatedUnion:()=>yl,describe:()=>Uc,date:()=>Rl,custom:()=>_c,cuid2:()=>Dl,cuid:()=>kl,codec:()=>$c,cidrv6:()=>Pl,cidrv4:()=>jl,check:()=>Ic,catch:()=>ig,boolean:()=>j$,bigint:()=>Ql,base64url:()=>dl,base64:()=>Jl,array:()=>Gn,any:()=>Ml,_function:()=>bc,_default:()=>a$,_ZodString:()=>xi,ZodXor:()=>X$,ZodXID:()=>yi,ZodVoid:()=>A$,ZodUnknown:()=>G$,ZodUnion:()=>An,ZodUndefined:()=>J$,ZodUUID:()=>p,ZodURL:()=>En,ZodULID:()=>ai,ZodType:()=>O,ZodTuple:()=>Q$,ZodTransform:()=>R$,ZodTemplateLiteral:()=>ug,ZodSymbol:()=>P$,ZodSuccess:()=>rg,ZodStringFormat:()=>d,ZodString:()=>Cr,ZodSet:()=>H$,ZodRecord:()=>fr,ZodReadonly:()=>eg,ZodPromise:()=>lg,ZodPreprocess:()=>og,ZodPrefault:()=>y$,ZodPipe:()=>Vn,ZodOptional:()=>bt,ZodObject:()=>Wn,ZodNumberFormat:()=>Nr,ZodNumber:()=>ar,ZodNullable:()=>C$,ZodNull:()=>d$,ZodNonOptional:()=>It,ZodNever:()=>W$,ZodNanoID:()=>Zi,ZodNaN:()=>tg,ZodMap:()=>B$,ZodMAC:()=>z$,ZodLiteral:()=>M$,ZodLazy:()=>$g,ZodKSUID:()=>pi,ZodJWT:()=>vt,ZodIntersection:()=>K$,ZodIPv6:()=>rt,ZodIPv4:()=>si,ZodGUID:()=>jn,ZodFunction:()=>cg,ZodFile:()=>x$,ZodExactOptional:()=>f$,ZodEnum:()=>Zr,ZodEmoji:()=>fi,ZodEmail:()=>Ri,ZodE164:()=>et,ZodDiscriminatedUnion:()=>q$,ZodDefault:()=>h$,ZodDate:()=>Ln,ZodCustomStringFormat:()=>hr,ZodCustom:()=>qn,ZodCodec:()=>Xn,ZodCatch:()=>ng,ZodCUID2:()=>hi,ZodCUID:()=>Ci,ZodCIDRv6:()=>it,ZodCIDRv4:()=>nt,ZodBoolean:()=>yr,ZodBigIntFormat:()=>ut,ZodBigInt:()=>pr,ZodBase64URL:()=>ot,ZodBase64:()=>tt,ZodArray:()=>V$,ZodAny:()=>L$});var Yi={};s(Yi,{uppercase:()=>Vr,trim:()=>Tr,toUpperCase:()=>Br,toLowerCase:()=>Fr,startsWith:()=>qr,slugify:()=>Hr,size:()=>Dr,regex:()=>Wr,property:()=>Ai,positive:()=>Ei,overwrite:()=>f,normalize:()=>Qr,nonpositive:()=>Gi,nonnegative:()=>Wi,negative:()=>Li,multipleOf:()=>ur,minSize:()=>y,minLength:()=>nr,mime:()=>Yr,maxSize:()=>$r,maxLength:()=>wr,lte:()=>x,lt:()=>h,lowercase:()=>Ar,length:()=>mr,includes:()=>Xr,gte:()=>Y,gt:()=>a,endsWith:()=>Kr});var Rr={};s(Rr,{time:()=>u$,duration:()=>$$,datetime:()=>e$,date:()=>v$,ZodISOTime:()=>Fi,ZodISODuration:()=>Bi,ZodISODateTime:()=>Qi,ZodISODate:()=>Ti});var Qi=l("ZodISODateTime",(n,i)=>{To.init(n,i),d.init(n,i)});function e$(n){return Tv(Qi,n)}var Ti=l("ZodISODate",(n,i)=>{Fo.init(n,i),d.init(n,i)});function v$(n){return Fv(Ti,n)}var Fi=l("ZodISOTime",(n,i)=>{Bo.init(n,i),d.init(n,i)});function u$(n){return Bv(Fi,n)}var Bi=l("ZodISODuration",(n,i)=>{Ho.init(n,i),d.init(n,i)});function $$(n){return Hv(Bi,n)}var ol=(n,i)=>{vn.init(n,i),n.name="ZodError",Object.defineProperties(n,{format:{value:(o)=>$n(n,o)},flatten:{value:(o)=>un(n,o)},addIssue:{value:(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,zr,2)}},addIssues:{value:(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,zr,2)}},isEmpty:{get(){return n.issues.length===0}}})},g$=l("ZodError",ol),H=l("ZodError",ol,{Parent:Error});var l$=Pr(H),c$=Jr(H),b$=dr(H),I$=Er(H),_$=Fn(H),U$=Bn(H),k$=Hn(H),D$=Mn(H),w$=xn(H),m$=Rn(H),S$=fn(H),N$=Zn(H);var el=new WeakMap;function dn(n,i,o){let e=Object.getPrototypeOf(n),r=el.get(e);if(!r)r=new Set,el.set(e,r);if(r.has(i))return;r.add(i);for(let t in o){let v=o[t];Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let u=v.bind(this);return Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:!0,value:u}),u},set(u){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:!0,value:u})}})}}var O=l("ZodType",(n,i)=>{return z.init(n,i),Object.assign(n["~standard"],{jsonSchema:{input:xr(n,"input"),output:xr(n,"output")}}),n.toJSONSchema=Su(n,{}),n.def=i,n.type=i.type,Object.defineProperty(n,"_def",{value:i}),n.parse=(o,e)=>l$(n,o,e,{callee:n.parse}),n.safeParse=(o,e)=>b$(n,o,e),n.parseAsync=async(o,e)=>c$(n,o,e,{callee:n.parseAsync}),n.safeParseAsync=async(o,e)=>I$(n,o,e),n.spa=n.safeParseAsync,n.encode=(o,e)=>_$(n,o,e),n.decode=(o,e)=>U$(n,o,e),n.encodeAsync=async(o,e)=>k$(n,o,e),n.decodeAsync=async(o,e)=>D$(n,o,e),n.safeEncode=(o,e)=>w$(n,o,e),n.safeDecode=(o,e)=>m$(n,o,e),n.safeEncodeAsync=async(o,e)=>S$(n,o,e),n.safeDecodeAsync=async(o,e)=>N$(n,o,e),dn(n,"ZodType",{check(...o){let e=this.def;return this.clone(k.mergeDefs(e,{checks:[...e.checks??[],...o.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...o){return this.check(...o)},clone(o,e){return q(this,o,e)},brand(){return this},register(o,e){return o.add(this,e),this},refine(o,e){return this.check(bg(o,e))},superRefine(o,e){return this.check(Ig(o,e))},overwrite(o){return this.check(f(o))},optional(){return Pn(this)},exactOptional(){return Z$(this)},nullable(){return Jn(this)},nullish(){return Pn(Jn(this))},nonoptional(o){return s$(this,o)},array(){return Gn(this)},or(o){return gt([this,o])},and(o){return Y$(this,o)},transform(o){return Mi(this,ct(o))},default(o){return a$(this,o)},prefault(o){return p$(this,o)},catch(o){return ig(this,o)},pipe(o){return Mi(this,o)},readonly(){return vg(this)},describe(o){let e=this.clone();return V.add(e,{description:o}),e},meta(...o){if(o.length===0)return V.get(this);let e=this.clone();return V.add(e,o[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(o){return o(this)}}),Object.defineProperty(n,"description",{get(){return V.get(n)?.description},configurable:!0}),n}),xi=l("_ZodString",(n,i)=>{kr.init(n,i),O.init(n,i),n._zod.processJSONSchema=(e,r,t)=>Nu(n,e,r,t);let o=n._zod.bag;n.format=o.format??null,n.minLength=o.minimum??null,n.maxLength=o.maximum??null,dn(n,"_ZodString",{regex(...e){return this.check(Wr(...e))},includes(...e){return this.check(Xr(...e))},startsWith(...e){return this.check(qr(...e))},endsWith(...e){return this.check(Kr(...e))},min(...e){return this.check(nr(...e))},max(...e){return this.check(wr(...e))},length(...e){return this.check(mr(...e))},nonempty(...e){return this.check(nr(1,...e))},lowercase(e){return this.check(Ar(e))},uppercase(e){return this.check(Vr(e))},trim(){return this.check(Tr())},normalize(...e){return this.check(Qr(...e))},toLowerCase(){return this.check(Fr())},toUpperCase(){return this.check(Br())},slugify(){return this.check(Hr())}})}),Cr=l("ZodString",(n,i)=>{kr.init(n,i),xi.init(n,i),n.email=(o)=>n.check($i(Ri,o)),n.url=(o)=>n.check(Nn(En,o)),n.jwt=(o)=>n.check(di(vt,o)),n.emoji=(o)=>n.check(Ii(fi,o)),n.guid=(o)=>n.check(Sn(jn,o)),n.uuid=(o)=>n.check(gi(p,o)),n.uuidv4=(o)=>n.check(li(p,o)),n.uuidv6=(o)=>n.check(ci(p,o)),n.uuidv7=(o)=>n.check(bi(p,o)),n.nanoid=(o)=>n.check(_i(Zi,o)),n.guid=(o)=>n.check(Sn(jn,o)),n.cuid=(o)=>n.check(Ui(Ci,o)),n.cuid2=(o)=>n.check(ki(hi,o)),n.ulid=(o)=>n.check(Di(ai,o)),n.base64=(o)=>n.check(ji(tt,o)),n.base64url=(o)=>n.check(Pi(ot,o)),n.xid=(o)=>n.check(wi(yi,o)),n.ksuid=(o)=>n.check(mi(pi,o)),n.ipv4=(o)=>n.check(Si(si,o)),n.ipv6=(o)=>n.check(Ni(rt,o)),n.cidrv4=(o)=>n.check(zi(nt,o)),n.cidrv6=(o)=>n.check(Oi(it,o)),n.e164=(o)=>n.check(Ji(et,o)),n.datetime=(o)=>n.check(e$(o)),n.date=(o)=>n.check(v$(o)),n.time=(o)=>n.check(u$(o)),n.duration=(o)=>n.check($$(o))});function On(n){return qv(Cr,n)}var d=l("ZodStringFormat",(n,i)=>{J.init(n,i),xi.init(n,i)}),Ri=l("ZodEmail",(n,i)=>{Go.init(n,i),d.init(n,i)});function vl(n){return $i(Ri,n)}var jn=l("ZodGUID",(n,i)=>{Eo.init(n,i),d.init(n,i)});function ul(n){return Sn(jn,n)}var p=l("ZodUUID",(n,i)=>{Lo.init(n,i),d.init(n,i)});function $l(n){return gi(p,n)}function gl(n){return li(p,n)}function ll(n){return ci(p,n)}function cl(n){return bi(p,n)}var En=l("ZodURL",(n,i)=>{Wo.init(n,i),d.init(n,i)});function bl(n){return Nn(En,n)}function Il(n){return Nn(En,{protocol:M.httpProtocol,hostname:M.domain,...k.normalizeParams(n)})}var fi=l("ZodEmoji",(n,i)=>{Ao.init(n,i),d.init(n,i)});function _l(n){return Ii(fi,n)}var Zi=l("ZodNanoID",(n,i)=>{Vo.init(n,i),d.init(n,i)});function Ul(n){return _i(Zi,n)}var Ci=l("ZodCUID",(n,i)=>{Xo.init(n,i),d.init(n,i)});function kl(n){return Ui(Ci,n)}var hi=l("ZodCUID2",(n,i)=>{qo.init(n,i),d.init(n,i)});function Dl(n){return ki(hi,n)}var ai=l("ZodULID",(n,i)=>{Ko.init(n,i),d.init(n,i)});function wl(n){return Di(ai,n)}var yi=l("ZodXID",(n,i)=>{Yo.init(n,i),d.init(n,i)});function ml(n){return wi(yi,n)}var pi=l("ZodKSUID",(n,i)=>{Qo.init(n,i),d.init(n,i)});function Sl(n){return mi(pi,n)}var si=l("ZodIPv4",(n,i)=>{Mo.init(n,i),d.init(n,i)});function Nl(n){return Si(si,n)}var z$=l("ZodMAC",(n,i)=>{Ro.init(n,i),d.init(n,i)});function zl(n){return Yv(z$,n)}var rt=l("ZodIPv6",(n,i)=>{xo.init(n,i),d.init(n,i)});function Ol(n){return Ni(rt,n)}var nt=l("ZodCIDRv4",(n,i)=>{fo.init(n,i),d.init(n,i)});function jl(n){return zi(nt,n)}var it=l("ZodCIDRv6",(n,i)=>{Zo.init(n,i),d.init(n,i)});function Pl(n){return Oi(it,n)}var tt=l("ZodBase64",(n,i)=>{ho.init(n,i),d.init(n,i)});function Jl(n){return ji(tt,n)}var ot=l("ZodBase64URL",(n,i)=>{ao.init(n,i),d.init(n,i)});function dl(n){return Pi(ot,n)}var et=l("ZodE164",(n,i)=>{yo.init(n,i),d.init(n,i)});function El(n){return Ji(et,n)}var vt=l("ZodJWT",(n,i)=>{po.init(n,i),d.init(n,i)});function Ll(n){return di(vt,n)}var hr=l("ZodCustomStringFormat",(n,i)=>{so.init(n,i),d.init(n,i)});function Gl(n,i,o={}){return Mr(hr,n,i,o)}function Wl(n){return Mr(hr,"hostname",M.hostname,n)}function Al(n){return Mr(hr,"hex",M.hex,n)}function Vl(n,i){let o=i?.enc??"hex",e=`${n}_${o}`,r=M[e];if(!r)throw Error(`Unrecognized hash format: ${e}`);return Mr(hr,e,r,i)}var ar=l("ZodNumber",(n,i)=>{ii.init(n,i),O.init(n,i),n._zod.processJSONSchema=(e,r,t)=>zu(n,e,r,t),dn(n,"ZodNumber",{gt(e,r){return this.check(a(e,r))},gte(e,r){return this.check(Y(e,r))},min(e,r){return this.check(Y(e,r))},lt(e,r){return this.check(h(e,r))},lte(e,r){return this.check(x(e,r))},max(e,r){return this.check(x(e,r))},int(e){return this.check(Hi(e))},safe(e){return this.check(Hi(e))},positive(e){return this.check(a(0,e))},nonnegative(e){return this.check(Y(0,e))},negative(e){return this.check(h(0,e))},nonpositive(e){return this.check(x(0,e))},multipleOf(e,r){return this.check(ur(e,r))},step(e,r){return this.check(ur(e,r))},finite(){return this}});let o=n._zod.bag;n.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??0.5),n.isFinite=!0,n.format=o.format??null});function O$(n){return Mv(ar,n)}var Nr=l("ZodNumberFormat",(n,i)=>{re.init(n,i),ar.init(n,i)});function Hi(n){return Rv(Nr,n)}function Xl(n){return fv(Nr,n)}function ql(n){return Zv(Nr,n)}function Kl(n){return Cv(Nr,n)}function Yl(n){return hv(Nr,n)}var yr=l("ZodBoolean",(n,i)=>{bn.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Ou(n,o,e,r)});function j$(n){return av(yr,n)}var pr=l("ZodBigInt",(n,i)=>{ti.init(n,i),O.init(n,i),n._zod.processJSONSchema=(e,r,t)=>ju(n,e,r,t),n.gte=(e,r)=>n.check(Y(e,r)),n.min=(e,r)=>n.check(Y(e,r)),n.gt=(e,r)=>n.check(a(e,r)),n.gte=(e,r)=>n.check(Y(e,r)),n.min=(e,r)=>n.check(Y(e,r)),n.lt=(e,r)=>n.check(h(e,r)),n.lte=(e,r)=>n.check(x(e,r)),n.max=(e,r)=>n.check(x(e,r)),n.positive=(e)=>n.check(a(BigInt(0),e)),n.negative=(e)=>n.check(h(BigInt(0),e)),n.nonpositive=(e)=>n.check(x(BigInt(0),e)),n.nonnegative=(e)=>n.check(Y(BigInt(0),e)),n.multipleOf=(e,r)=>n.check(ur(e,r));let o=n._zod.bag;n.minValue=o.minimum??null,n.maxValue=o.maximum??null,n.format=o.format??null});function Ql(n){return pv(pr,n)}var ut=l("ZodBigIntFormat",(n,i)=>{ne.init(n,i),pr.init(n,i)});function Tl(n){return ru(ut,n)}function Fl(n){return nu(ut,n)}var P$=l("ZodSymbol",(n,i)=>{ie.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Pu(n,o,e,r)});function Bl(n){return iu(P$,n)}var J$=l("ZodUndefined",(n,i)=>{te.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>du(n,o,e,r)});function Hl(n){return tu(J$,n)}var d$=l("ZodNull",(n,i)=>{oe.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Ju(n,o,e,r)});function E$(n){return ou(d$,n)}var L$=l("ZodAny",(n,i)=>{ee.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Gu(n,o,e,r)});function Ml(){return eu(L$)}var G$=l("ZodUnknown",(n,i)=>{ve.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Wu(n,o,e,r)});function Sr(){return vu(G$)}var W$=l("ZodNever",(n,i)=>{ue.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Lu(n,o,e,r)});function $t(n){return uu(W$,n)}var A$=l("ZodVoid",(n,i)=>{$e.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Eu(n,o,e,r)});function xl(n){return $u(A$,n)}var Ln=l("ZodDate",(n,i)=>{ge.init(n,i),O.init(n,i),n._zod.processJSONSchema=(e,r,t)=>Au(n,e,r,t),n.min=(e,r)=>n.check(Y(e,r)),n.max=(e,r)=>n.check(x(e,r));let o=n._zod.bag;n.minDate=o.minimum?new Date(o.minimum):null,n.maxDate=o.maximum?new Date(o.maximum):null});function Rl(n){return gu(Ln,n)}var V$=l("ZodArray",(n,i)=>{le.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>xu(n,o,e,r),n.element=i.element,dn(n,"ZodArray",{min(o,e){return this.check(nr(o,e))},nonempty(o){return this.check(nr(1,o))},max(o,e){return this.check(wr(o,e))},length(o,e){return this.check(mr(o,e))},unwrap(){return this.element}})});function Gn(n,i){return bu(V$,n,i)}function fl(n){let i=n._zod.def.shape;return lt(Object.keys(i))}var Wn=l("ZodObject",(n,i)=>{ce.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Ru(n,o,e,r),k.defineLazy(n,"shape",()=>{return i.shape}),dn(n,"ZodObject",{keyof(){return lt(Object.keys(this._zod.def.shape))},catchall(o){return this.clone({...this._zod.def,catchall:o})},passthrough(){return this.clone({...this._zod.def,catchall:Sr()})},loose(){return this.clone({...this._zod.def,catchall:Sr()})},strict(){return this.clone({...this._zod.def,catchall:$t()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(o){return k.extend(this,o)},safeExtend(o){return k.safeExtend(this,o)},merge(o){return k.merge(this,o)},pick(o){return k.pick(this,o)},omit(o){return k.omit(this,o)},partial(...o){return k.partial(bt,this,o[0])},required(...o){return k.required(It,this,o[0])}})});function Zl(n,i){let o={type:"object",shape:n??{},...k.normalizeParams(i)};return new Wn(o)}function Cl(n,i){return new Wn({type:"object",shape:n,catchall:$t(),...k.normalizeParams(i)})}function hl(n,i){return new Wn({type:"object",shape:n,catchall:Sr(),...k.normalizeParams(i)})}var An=l("ZodUnion",(n,i)=>{In.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Xi(n,o,e,r),n.options=i.options});function gt(n,i){return new An({type:"union",options:n,...k.normalizeParams(i)})}var X$=l("ZodXor",(n,i)=>{An.init(n,i),be.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Xi(n,o,e,r),n.options=i.options});function al(n,i){return new X$({type:"union",options:n,inclusive:!1,...k.normalizeParams(i)})}var q$=l("ZodDiscriminatedUnion",(n,i)=>{An.init(n,i),Ie.init(n,i)});function yl(n,i,o){return new q$({type:"union",options:i,discriminator:n,...k.normalizeParams(o)})}var K$=l("ZodIntersection",(n,i)=>{_e.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>fu(n,o,e,r)});function Y$(n,i){return new K$({type:"intersection",left:n,right:i})}var Q$=l("ZodTuple",(n,i)=>{oi.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Zu(n,o,e,r),n.rest=(o)=>n.clone({...n._zod.def,rest:o})});function T$(n,i,o){let e=i instanceof z,r=e?o:i;return new Q$({type:"tuple",items:n,rest:e?i:null,...k.normalizeParams(r)})}var fr=l("ZodRecord",(n,i)=>{Ue.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Cu(n,o,e,r),n.keyType=i.keyType,n.valueType=i.valueType});function F$(n,i,o){if(!i||!i._zod)return new fr({type:"record",keyType:On(),valueType:n,...k.normalizeParams(i)});return new fr({type:"record",keyType:n,valueType:i,...k.normalizeParams(o)})}function pl(n,i,o){let e=q(n);return e._zod.values=void 0,new fr({type:"record",keyType:e,valueType:i,...k.normalizeParams(o)})}function sl(n,i,o){return new fr({type:"record",keyType:n,valueType:i,mode:"loose",...k.normalizeParams(o)})}var B$=l("ZodMap",(n,i)=>{ke.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Hu(n,o,e,r),n.keyType=i.keyType,n.valueType=i.valueType,n.min=(...o)=>n.check(y(...o)),n.nonempty=(o)=>n.check(y(1,o)),n.max=(...o)=>n.check($r(...o)),n.size=(...o)=>n.check(Dr(...o))});function rc(n,i,o){return new B$({type:"map",keyType:n,valueType:i,...k.normalizeParams(o)})}var H$=l("ZodSet",(n,i)=>{De.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Mu(n,o,e,r),n.min=(...o)=>n.check(y(...o)),n.nonempty=(o)=>n.check(y(1,o)),n.max=(...o)=>n.check($r(...o)),n.size=(...o)=>n.check(Dr(...o))});function nc(n,i){return new H$({type:"set",valueType:n,...k.normalizeParams(i)})}var Zr=l("ZodEnum",(n,i)=>{we.init(n,i),O.init(n,i),n._zod.processJSONSchema=(e,r,t)=>Vu(n,e,r,t),n.enum=i.entries,n.options=Object.values(i.entries);let o=new Set(Object.keys(i.entries));n.extract=(e,r)=>{let t={};for(let v of e)if(o.has(v))t[v]=i.entries[v];else throw Error(`Key ${v} not found in enum`);return new Zr({...i,checks:[],...k.normalizeParams(r),entries:t})},n.exclude=(e,r)=>{let t={...i.entries};for(let v of e)if(o.has(v))delete t[v];else throw Error(`Key ${v} not found in enum`);return new Zr({...i,checks:[],...k.normalizeParams(r),entries:t})}});function lt(n,i){let o=Array.isArray(n)?Object.fromEntries(n.map((e)=>[e,e])):n;return new Zr({type:"enum",entries:o,...k.normalizeParams(i)})}function ic(n,i){return new Zr({type:"enum",entries:n,...k.normalizeParams(i)})}var M$=l("ZodLiteral",(n,i)=>{me.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Xu(n,o,e,r),n.values=new Set(i.values),Object.defineProperty(n,"value",{get(){if(i.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return i.values[0]}})});function tc(n,i){return new M$({type:"literal",values:Array.isArray(n)?n:[n],...k.normalizeParams(i)})}var x$=l("ZodFile",(n,i)=>{Se.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Yu(n,o,e,r),n.min=(o,e)=>n.check(y(o,e)),n.max=(o,e)=>n.check($r(o,e)),n.mime=(o,e)=>n.check(Yr(Array.isArray(o)?o:[o],e))});function oc(n){return Iu(x$,n)}var R$=l("ZodTransform",(n,i)=>{Ne.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Bu(n,o,e,r),n._zod.parse=(o,e)=>{if(e.direction==="backward")throw new Ir(n.constructor.name);o.addIssue=(t)=>{if(typeof t==="string")o.issues.push(k.issue(t,o.value,i));else{let v=t;if(v.fatal)v.continue=!1;v.code??(v.code="custom"),v.input??(v.input=o.value),v.inst??(v.inst=n),o.issues.push(k.issue(v))}};let r=i.transform(o.value,o);if(r instanceof Promise)return r.then((t)=>{return o.value=t,o.fallback=!0,o});return o.value=r,o.fallback=!0,o}});function ct(n){return new R$({type:"transform",transform:n})}var bt=l("ZodOptional",(n,i)=>{ei.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>qi(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function Pn(n){return new bt({type:"optional",innerType:n})}var f$=l("ZodExactOptional",(n,i)=>{ze.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>qi(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function Z$(n){return new f$({type:"optional",innerType:n})}var C$=l("ZodNullable",(n,i)=>{Oe.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>hu(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function Jn(n){return new C$({type:"nullable",innerType:n})}function ec(n){return Pn(Jn(n))}var h$=l("ZodDefault",(n,i)=>{je.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>yu(n,o,e,r),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function a$(n,i){return new h$({type:"default",innerType:n,get defaultValue(){return typeof i==="function"?i():k.shallowClone(i)}})}var y$=l("ZodPrefault",(n,i)=>{Pe.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>pu(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function p$(n,i){return new y$({type:"prefault",innerType:n,get defaultValue(){return typeof i==="function"?i():k.shallowClone(i)}})}var It=l("ZodNonOptional",(n,i)=>{Je.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>au(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function s$(n,i){return new It({type:"nonoptional",innerType:n,...k.normalizeParams(i)})}var rg=l("ZodSuccess",(n,i)=>{de.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Qu(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function vc(n){return new rg({type:"success",innerType:n})}var ng=l("ZodCatch",(n,i)=>{Ee.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>su(n,o,e,r),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function ig(n,i){return new ng({type:"catch",innerType:n,catchValue:typeof i==="function"?i:()=>i})}var tg=l("ZodNaN",(n,i)=>{Le.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>qu(n,o,e,r)});function uc(n){return cu(tg,n)}var Vn=l("ZodPipe",(n,i)=>{vi.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>r$(n,o,e,r),n.in=i.in,n.out=i.out});function Mi(n,i){return new Vn({type:"pipe",in:n,out:i})}var Xn=l("ZodCodec",(n,i)=>{Vn.init(n,i),_n.init(n,i)});function $c(n,i,o){return new Xn({type:"pipe",in:n,out:i,transform:o.decode,reverseTransform:o.encode})}function gc(n){let i=n._zod.def;return new Xn({type:"pipe",in:i.out,out:i.in,transform:i.reverseTransform,reverseTransform:i.transform})}var og=l("ZodPreprocess",(n,i)=>{Vn.init(n,i),Ge.init(n,i)}),eg=l("ZodReadonly",(n,i)=>{We.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>n$(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function vg(n){return new eg({type:"readonly",innerType:n})}var ug=l("ZodTemplateLiteral",(n,i)=>{Ae.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Ku(n,o,e,r)});function lc(n,i){return new ug({type:"template_literal",parts:n,...k.normalizeParams(i)})}var $g=l("ZodLazy",(n,i)=>{qe.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>t$(n,o,e,r),n.unwrap=()=>n._zod.def.getter()});function gg(n){return new $g({type:"lazy",getter:n})}var lg=l("ZodPromise",(n,i)=>{Xe.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>i$(n,o,e,r),n.unwrap=()=>n._zod.def.innerType});function cc(n){return new lg({type:"promise",innerType:n})}var cg=l("ZodFunction",(n,i)=>{Ve.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Fu(n,o,e,r)});function bc(n){return new cg({type:"function",input:Array.isArray(n?.input)?T$(n?.input):n?.input??Gn(Sr()),output:n?.output??Sr()})}var qn=l("ZodCustom",(n,i)=>{Ke.init(n,i),O.init(n,i),n._zod.processJSONSchema=(o,e,r)=>Tu(n,o,e,r)});function Ic(n){let i=new E({check:"custom"});return i._zod.check=n,i}function _c(n,i){return _u(qn,n??(()=>!0),i)}function bg(n,i={}){return Uu(qn,n,i)}function Ig(n,i){return ku(n,i)}var Uc=Du,kc=wu;function Dc(n,i={}){let o=new qn({type:"custom",check:"custom",fn:(e)=>e instanceof n,abort:!0,...k.normalizeParams(i)});return o._zod.bag.Class=n,o._zod.check=(e)=>{if(!(e.value instanceof n))e.issues.push({code:"invalid_type",expected:n.name,input:e.value,inst:o,path:[...o._zod.def.path??[]]})},o}var wc=(...n)=>mu({Codec:Xn,Boolean:yr,String:Cr},...n);function mc(n){let i=gg(()=>{return gt([On(n),O$(),j$(),E$(),Gn(i),F$(On(),i)])});return i}function Sc(n,i){return new og({type:"pipe",in:ct(n),out:i})}var $4={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function g4(n){G({customError:n})}function l4(){return G().customError}var _g;(function(n){})(_g||(_g={}));var S={...zn,...Yi,iso:Rr},c4=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function b4(n,i){let o=n.$schema;if(o==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(o==="http://json-schema.org/draft-07/schema#")return"draft-7";if(o==="http://json-schema.org/draft-04/schema#")return"draft-4";return i??"draft-2020-12"}function I4(n,i){if(!n.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let o=n.slice(1).split("/").filter(Boolean);if(o.length===0)return i.rootSchema;let e=i.version==="draft-2020-12"?"$defs":"definitions";if(o[0]===e){let r=o[1];if(!r||!i.defs[r])throw Error(`Reference not found: ${n}`);return i.defs[r]}throw Error(`Reference not found: ${n}`)}function Nc(n,i){if(n.not!==void 0){if(typeof n.not==="object"&&Object.keys(n.not).length===0)return S.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(n.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(n.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(n.if!==void 0||n.then!==void 0||n.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(n.dependentSchemas!==void 0||n.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(n.$ref){let r=n.$ref;if(i.refs.has(r))return i.refs.get(r);if(i.processing.has(r))return S.lazy(()=>{if(!i.refs.has(r))throw Error(`Circular reference not resolved: ${r}`);return i.refs.get(r)});i.processing.add(r);let t=I4(r,i),v=X(t,i);return i.refs.set(r,v),i.processing.delete(r),v}if(n.enum!==void 0){let r=n.enum;if(i.version==="openapi-3.0"&&n.nullable===!0&&r.length===1&&r[0]===null)return S.null();if(r.length===0)return S.never();if(r.length===1)return S.literal(r[0]);if(r.every((v)=>typeof v==="string"))return S.enum(r);let t=r.map((v)=>S.literal(v));if(t.length<2)return t[0];return S.union([t[0],t[1],...t.slice(2)])}if(n.const!==void 0)return S.literal(n.const);let o=n.type;if(Array.isArray(o)){let r=o.map((t)=>{let v={...n,type:t};return Nc(v,i)});if(r.length===0)return S.never();if(r.length===1)return r[0];return S.union(r)}if(!o)return S.any();let e;switch(o){case"string":{let r=S.string();if(n.format){let t=n.format;if(t==="email")r=r.check(S.email());else if(t==="uri"||t==="uri-reference")r=r.check(S.url());else if(t==="uuid"||t==="guid")r=r.check(S.uuid());else if(t==="date-time")r=r.check(S.iso.datetime());else if(t==="date")r=r.check(S.iso.date());else if(t==="time")r=r.check(S.iso.time());else if(t==="duration")r=r.check(S.iso.duration());else if(t==="ipv4")r=r.check(S.ipv4());else if(t==="ipv6")r=r.check(S.ipv6());else if(t==="mac")r=r.check(S.mac());else if(t==="cidr")r=r.check(S.cidrv4());else if(t==="cidr-v6")r=r.check(S.cidrv6());else if(t==="base64")r=r.check(S.base64());else if(t==="base64url")r=r.check(S.base64url());else if(t==="e164")r=r.check(S.e164());else if(t==="jwt")r=r.check(S.jwt());else if(t==="emoji")r=r.check(S.emoji());else if(t==="nanoid")r=r.check(S.nanoid());else if(t==="cuid")r=r.check(S.cuid());else if(t==="cuid2")r=r.check(S.cuid2());else if(t==="ulid")r=r.check(S.ulid());else if(t==="xid")r=r.check(S.xid());else if(t==="ksuid")r=r.check(S.ksuid())}if(typeof n.minLength==="number")r=r.min(n.minLength);if(typeof n.maxLength==="number")r=r.max(n.maxLength);if(n.pattern)r=r.regex(new RegExp(n.pattern));e=r;break}case"number":case"integer":{let r=o==="integer"?S.number().int():S.number();if(typeof n.minimum==="number")r=r.min(n.minimum);if(typeof n.maximum==="number")r=r.max(n.maximum);if(typeof n.exclusiveMinimum==="number")r=r.gt(n.exclusiveMinimum);else if(n.exclusiveMinimum===!0&&typeof n.minimum==="number")r=r.gt(n.minimum);if(typeof n.exclusiveMaximum==="number")r=r.lt(n.exclusiveMaximum);else if(n.exclusiveMaximum===!0&&typeof n.maximum==="number")r=r.lt(n.maximum);if(typeof n.multipleOf==="number")r=r.multipleOf(n.multipleOf);e=r;break}case"boolean":{e=S.boolean();break}case"null":{e=S.null();break}case"object":{let r={},t=n.properties||{},v=new Set(n.required||[]);for(let[g,$]of Object.entries(t)){let c=X($,i);r[g]=v.has(g)?c:c.optional()}if(n.propertyNames){let g=X(n.propertyNames,i),$=n.additionalProperties&&typeof n.additionalProperties==="object"?X(n.additionalProperties,i):S.any();if(Object.keys(r).length===0){e=S.record(g,$);break}let c=S.object(r).passthrough(),I=S.looseRecord(g,$);e=S.intersection(c,I);break}if(n.patternProperties){let g=n.patternProperties,$=Object.keys(g),c=[];for(let m of $){let D=X(g[m],i),N=S.string().regex(new RegExp(m));c.push(S.looseRecord(N,D))}let I=[];if(Object.keys(r).length>0)I.push(S.object(r).passthrough());if(I.push(...c),I.length===0)e=S.object({}).passthrough();else if(I.length===1)e=I[0];else{let m=S.intersection(I[0],I[1]);for(let D=2;D<I.length;D++)m=S.intersection(m,I[D]);e=m}break}let u=S.object(r);if(n.additionalProperties===!1)e=u.strict();else if(typeof n.additionalProperties==="object")e=u.catchall(X(n.additionalProperties,i));else e=u.passthrough();break}case"array":{let{prefixItems:r,items:t}=n;if(r&&Array.isArray(r)){let v=r.map((g)=>X(g,i)),u=t&&typeof t==="object"&&!Array.isArray(t)?X(t,i):void 0;if(u)e=S.tuple(v).rest(u);else e=S.tuple(v);if(typeof n.minItems==="number")e=e.check(S.minLength(n.minItems));if(typeof n.maxItems==="number")e=e.check(S.maxLength(n.maxItems))}else if(Array.isArray(t)){let v=t.map((g)=>X(g,i)),u=n.additionalItems&&typeof n.additionalItems==="object"?X(n.additionalItems,i):void 0;if(u)e=S.tuple(v).rest(u);else e=S.tuple(v);if(typeof n.minItems==="number")e=e.check(S.minLength(n.minItems));if(typeof n.maxItems==="number")e=e.check(S.maxLength(n.maxItems))}else if(t!==void 0){let v=X(t,i),u=S.array(v);if(typeof n.minItems==="number")u=u.min(n.minItems);if(typeof n.maxItems==="number")u=u.max(n.maxItems);e=u}else e=S.array(S.any());break}default:throw Error(`Unsupported type: ${o}`)}return e}function X(n,i){if(typeof n==="boolean")return n?S.any():S.never();let o=Nc(n,i),e=n.type||n.enum!==void 0||n.const!==void 0;if(n.anyOf&&Array.isArray(n.anyOf)){let u=n.anyOf.map(($)=>X($,i)),g=S.union(u);o=e?S.intersection(o,g):g}if(n.oneOf&&Array.isArray(n.oneOf)){let u=n.oneOf.map(($)=>X($,i)),g=S.xor(u);o=e?S.intersection(o,g):g}if(n.allOf&&Array.isArray(n.allOf))if(n.allOf.length===0)o=e?o:S.any();else{let u=e?o:X(n.allOf[0],i),g=e?0:1;for(let $=g;$<n.allOf.length;$++)u=S.intersection(u,X(n.allOf[$],i));o=u}if(n.nullable===!0&&i.version==="openapi-3.0")o=S.nullable(o);if(n.readOnly===!0)o=S.readonly(o);if(n.default!==void 0)o=o.default(n.default);let r={},t=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let u of t)if(u in n)r[u]=n[u];let v=["contentEncoding","contentMediaType","contentSchema"];for(let u of v)if(u in n)r[u]=n[u];for(let u of Object.keys(n))if(!c4.has(u))r[u]=n[u];if(Object.keys(r).length>0)i.registry.add(o,r);if(n.description)o=o.describe(n.description);return o}function zc(n,i){if(typeof n==="boolean")return n?S.any():S.never();let o;try{o=JSON.parse(JSON.stringify(n))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let e=b4(o,i?.defaultTarget),r=o.$defs||o.definitions||{},t={version:e,defs:r,refs:new Map,processing:new Set,rootSchema:o,registry:i?.registry??V};return X(o,t)}var Ug={};s(Ug,{string:()=>_4,number:()=>U4,date:()=>w4,boolean:()=>k4,bigint:()=>D4});function _4(n){return Kv(Cr,n)}function U4(n){return xv(ar,n)}function k4(n){return yv(yr,n)}function D4(n){return sv(pr,n)}function w4(n){return lu(Ln,n)}G(Un());export{_t as z,Ec as defineBrain,g$ as ZodError,Gc as PLUGIN_API_VERSION};
67
67
 
68
- //# debugId=A238A8D185765E3264756E2164756E21
68
+ //# debugId=4F15ACBD1685032364756E2164756E21
69
69
  //# sourceMappingURL=index.js.map