declare global { export type CollectionDocument = T & { id?: string insertTime?: D updateTime?: D [key: string]: any } /** * Represents a `boolean` value or an object with an `eval` JS expression. * Used for field-level `readonly` and `hidden` configuration. */ export type BoolOrEval = boolean | { eval: string } /** Structured field validator as defined in Go CollectionField.Validator */ export interface FieldImageValidator { /** Minimum allowed image width in pixels */ minWidth?: number /** Maximum allowed image width in pixels */ maxWidth?: number /** Minimum allowed image height in pixels */ minHeight?: number /** Maximum allowed image height in pixels */ maxHeight?: number /** Allow non-image uploads to bypass image dimension checks entirely */ allowNonImages?: boolean /** Allow image/* uploads to pass when dimensions cannot be determined */ allowUnknownDimensions?: boolean } export interface FieldValidator { /** Array of allowed primitive values the field may equal */ in?: any[] /** Built-in string format validator */ format?: "email" | "url" | "uuid" | "slug" /** Whether the field is required */ required?: boolean /** Whether zero-values are allowed when required is true */ allowZero?: boolean /** JS eval expression for custom validation */ eval?: string /** Minimum number of items for array fields */ minItems?: number /** Maximum number of items for array fields */ maxItems?: number /** Minimum number of characters for string values */ minLength?: number /** Maximum number of characters for string values */ maxLength?: number /** Regex pattern the string value must fully match */ pattern?: string /** Minimum numeric value */ min?: number /** Maximum numeric value */ max?: number /** Earliest allowed date/time value for date, time, and datetime fields */ minDate?: string /** Latest allowed date/time value for date, time, and datetime fields */ maxDate?: string /** Minimum decoded file size (e.g. 50KB) for file and file[] fields */ minFileSize?: string /** Maximum decoded file size (e.g. 5MB) */ maxFileSize?: string /** Allowed MIME types for file and file[] fields */ accept?: string[] /** Image dimension bounds for newly uploaded file and file[] images */ image?: FieldImageValidator } export interface ScoreConfig { expr?: { [key: string]: any } } export interface RegexConfig { weights?: { [field: string]: number } scoring?: "count" | "binary" | "log" } export interface NormalizeConfig { use?: string[] eval?: string } export interface NgramStopwordsConfig { presets?: string[] words?: string[] } export interface NgramQueryFilterConfig { minMatchRatio?: number } export interface CombinedCacheConfig { enabled?: boolean ttl?: string maxEntries?: number } export interface NgramInMemoryConfig { enabled?: boolean maxDocs?: number maxMemoryMB?: number } export interface NgramConfig { sizes?: number[] normalize?: NormalizeConfig stopwords?: NgramStopwordsConfig queryFilter?: NgramQueryFilterConfig inMemory?: NgramInMemoryConfig } export interface RrfConfig { k?: number topK?: number weights?: { [source: string]: number } /** Fusion strategy: "rrf" (default), "score_rrf", "score_sum", "rank_score", "hybrid" */ strategy?: "rrf" | "score_rrf" | "score_sum" | "rank_score" | "hybrid" /** Score normalization: "none" (default), "minmax", "zscore" */ normalize?: "none" | "minmax" | "zscore" /** Blend factor for "hybrid" strategy: 0.0 = pure rank, 1.0 = pure score */ scoreWeight?: number /** Per-source overrides for fine-grained fusion tuning */ sourceConfig?: { [source: string]: SourceFusionConfig } } /** Per-source overrides for rank fusion */ export interface SourceFusionConfig { /** Override global scoreWeight for this source */ scoreWeight?: number /** Score multiplier for this source (default 1.0) */ boost?: number } export interface VectorConfig { /** * Name of the embedding provider (server config: `embedding.providers`) or * of an embedding failover group (`embedding.groups`). Groups route across * their members (policy, breaker, bulk sharding) and look like one provider * to the collection. */ provider: string documentPrefix?: string queryPrefix?: string overflow?: "truncate" | "chunk" chunkSize?: number chunkOverlap?: number } export interface SearchExplainSource { mode?: string matched?: boolean rank?: number weight?: number score?: number /** Normalized score (only present when normalize is active) */ normalizedScore?: number contribution?: number details?: SearchExplanation } export interface SearchExplanation { algorithm?: string /** Fusion strategy used ("score_rrf", "hybrid", etc.). Omitted when default "rrf". */ strategy?: string /** Normalization mode used ("minmax", "zscore"). Omitted when "none". */ normalize?: string k?: number sources?: { [source: string]: SearchExplainSource } } export interface SearchMeta { score?: number mode?: string /** Present when the request uses qExplain=1 or qExplain=true. */ details?: SearchExplanation } /** Search configuration for a collection */ export interface SearchConfig { /** Search config name (used in query parameter qName) */ name: string /** Search mode: text, regex, eval, filter, ngram, vector or combined */ mode: | "text" | "regex" | "eval" | "filter" | "ngram" | "vector" | "combined" /** Fields to search in (for regex and ngram mode) */ fields?: string[] /** Meta information */ meta?: { [key: string]: any } /** JS eval expression (for eval mode) */ eval?: string /** MongoDB filter template (for filter mode) */ filter?: { [key: string]: any } /** Ngram search configuration */ ngram?: NgramConfig /** Result cache for combined searches */ combinedCache?: CombinedCacheConfig /** Regex search configuration */ regex?: RegexConfig /** Custom scoring for eval/filter search */ score?: ScoreConfig /** Vector search configuration */ vector?: VectorConfig /** Reciprocal rank fusion configuration */ rrf?: RrfConfig /** Execute synchronously (false) or via background queue (true). Vector mode defaults to true. */ async?: boolean /** Auto-regenerate enrichment data when the config changes */ autoRegenerate?: boolean } /** Query limits configuration for a collection */ export interface QueryLimitsConfig { /** Default limit for GET queries (if client doesn't specify) */ defaultLimit?: number /** Maximum allowed limit for GET queries */ maxLimit?: number } /** Bulk operation optimization configuration */ export interface BulkOptimizeConfig { /** Optimize bulk create operations */ create?: boolean /** Optimize bulk update operations */ update?: boolean /** Optimize bulk delete operations */ delete?: boolean } /** Bulk configuration for a collection */ export interface BulkConfig { /** Optimization settings for bulk operations */ optimize?: BulkOptimizeConfig } /** Collection index definition */ export interface CollectionIndex { /** Index name */ name?: string /** Index key fields (prefix with - for descending) */ key: string[] /** Whether the index enforces uniqueness */ unique?: boolean /** Whether to drop duplicate entries */ dropDups?: boolean /** Build index in background */ background?: boolean /** Only index documents that contain the indexed field */ sparse?: boolean /** Default language for text indexes */ defaultLanguage?: string /** Field that contains the language override */ languageOverride?: string } /** Audit configuration for a collection */ export interface AuditCollectionConfig { /** Whether audit logging is enabled for this collection */ enabled?: boolean /** List of actions to audit */ actions?: Array< | "create" | "update" | "delete" | "bulkCreate" | "bulkUpdate" | "bulkDelete" > /** * Document paths (dot notation, e.g. `security.twoFactor.secret`) whose * values are never written to the audit history. The values are dropped, * not replaced: the paths are recorded in `AuditEntry.redactedFields` * instead, so a client-side audit restore cannot write a placeholder into * the document. Snapshot backups (`snapshotPath`) are not affected. */ excludeFields?: string[] } /** One audit history entry as returned by `GET /api/v1/audit`. */ export interface AuditEntry { id?: string projectNamespace?: string projectName?: string collection: string action: string documentId?: string snapshot?: Record changes?: Record filter?: Record /** * Paths removed from `snapshot`/`changes` because the collection lists * them in `audit.excludeFields`. Metadata only — the values are gone. */ redactedFields?: string[] [key: string]: any } export interface UploadConfig { maxBodySize?: string allowedMimeTypes?: string[] } export type LocalizedText = string | Record export type ChoiceValue = string | number | boolean | null export type ChoiceStyle = Record export interface ChoiceItem { id?: ChoiceValue value?: ChoiceValue name?: LocalizedText label?: LocalizedText description?: LocalizedText badgeVariant?: "success" | "error" | "warning" | "info" | "neutral" chipVariant?: "success" | "error" | "warning" | "info" | "neutral" /** * Flat inline CSS properties for badge/chip rendering. * Supports camelCase, kebab-case, and CSS custom properties. * `bg` and `text` remain aliases for `background` and `color`. */ badgeStyle?: ChoiceStyle /** Alias for `badgeStyle`. */ chipStyle?: ChoiceStyle } export type EvalStringConfig = { eval: string select?: string[] } export type EvalHtmlConfig = { eval: string raw?: boolean select?: string[] } export interface PreviewTableColumn { source?: string label?: LocalizedText align?: "left" | "center" | "right" eval?: string raw?: boolean select?: string[] } export type PreviewSlotValue = string | EvalStringConfig export interface PreviewSlots { label?: PreviewSlotValue labelStyle?: PreviewSlotValue secondary?: PreviewSlotValue tertiary?: PreviewSlotValue badge?: PreviewSlotValue image?: PreviewSlotValue imageFallback?: PreviewSlotValue mediaFile?: string eval?: string raw?: boolean table?: Array select?: string[] } export type PreviewConfig = string | EvalHtmlConfig | PreviewSlots /** Image filter parameters — used in both CollectionConfig.imageFilter and ImagePackage.filter() */ export interface RemoveBackgroundParams { color?: string tolerance?: number fromEdges?: boolean edgeBlur?: number referenceWidth?: number } export interface DropShadowParams { color?: string opacity?: number blur?: number offsetX?: number offsetY?: number padding?: number referenceWidth?: number canvas?: "expand" | "fixed" background?: string } export interface ImageFilterParams { width?: number height?: number fit?: boolean fill?: boolean resampling?: | "nearestNeighbor" | "hermite" | "linear" | "catmullRom" | "lanczos" | "box" | "mitchellNetravali" | "bSpline" | "gaussian" | "bartlett" | "hann" | "hamming" | "blackman" | "welch" | "cosine" anchor?: | "center" | "topLeft" | "top" | "topRight" | "left" | "right" | "bottomLeft" | "bottom" | "bottomRight" brightness?: number saturation?: number contrast?: number gamma?: number blur?: number sharpen?: number invert?: boolean grayscale?: boolean quality?: number lossless?: boolean skipLargerDimension?: boolean skipLargerFilesize?: boolean outputType?: "jpg" | "jpeg" | "png" | "webp" | "bmp" | "tiff" | "gif" removeBackground?: RemoveBackgroundParams dropShadow?: DropShadowParams flatten?: string } /** Limits for asset image processing (`imageProcessing.limits`) */ export interface AssetImageLimitsConfig { maxInputBytes?: number maxPixels?: number } /** Asset image processing block (`imageProcessing`) */ export interface AssetImageProcessingConfig { access: "public" /** * Optional cache directory. An explicit value is project-controlled: * relative to the project's config.yml, ".." needs * security.allowUpperPaths, absolute needs security.allowAbsolutePaths. * Omit to use cache.image.path (default ../cache/image). * The project namespace is appended; the directory is created lazily. */ cachePath?: string allowOriginal?: boolean defaultFilter?: string allowedInputTypes?: Array<"image/jpeg" | "image/png" | "image/webp"> limits?: AssetImageLimitsConfig imageFilter: { [name: string]: ImageFilterParams[] } | string } /** Asset config entry */ export interface AssetConfig { name: string path: string imageProcessing?: AssetImageProcessingConfig } /** Collection config as returned by context.collection() – JSON-serialized from Go CollectionConfig */ export interface CollectionInfo { name: string defaultLanguage?: string upload?: UploadConfig permissions?: { [role: string]: PermissionSet } projections?: { [name: string]: ProjectionConfig } meta?: { [key: string]: any } fields?: CollectionFieldInfo[] /** Named image filter presets for file fields */ imageFilter?: { [name: string]: ImageFilterParams[] } /** Collection index definitions */ indexes?: CollectionIndex[] /** Audit configuration */ audit?: AuditCollectionConfig /** Bulk operation configuration */ bulk?: BulkConfig /** Query limits for GET requests */ queryLimits?: QueryLimitsConfig /** Fields that are read-only at collection level */ readonlyFields?: string[] /** Fields that are hidden at collection level */ hiddenFields?: string[] /** Search configurations */ search?: SearchConfig[] /** Reject unknown fields not defined in the fields array */ strictFields?: boolean [key: string]: any } /** Action endpoint descriptor as returned by context.api() for _actions resources */ export interface ActionInfo { name: string permissions?: { [role: string]: PermissionSet } meta?: ActionMeta audit?: AuditCollectionConfig [key: string]: any } export interface ActionMeta { label?: LocalizedText muiIcon?: string description?: LocalizedText group?: string hide?: boolean methods?: Record [key: string]: any } export interface ActionMethodMeta { query?: { title?: LocalizedText description?: LocalizedText fields?: CollectionFieldInfo[] } data?: { title?: LocalizedText description?: LocalizedText fields?: CollectionFieldInfo[] } execution?: ActionExecutionMeta output?: ActionOutputMeta [key: string]: any } export interface ActionExecutionMeta { kind?: "sync" | "sse" | string cancellable?: boolean [key: string]: any } export interface ActionMappedField extends Omit< CollectionFieldInfo, "name" > { /** Dot-path in action payload/result/progress. Preferred over `name` for mapped output configs. */ source?: string /** Legacy fallback for path-based mappings. */ name?: string } export interface ActionOutputProgressMapping { indexField?: string countField?: string statusField?: string | string[] messageField?: string fields?: ActionMappedField[] } export interface ActionOutputMapping { summary?: { fields?: ActionMappedField[] } details?: { fields?: ActionMappedField[] } progress?: ActionOutputProgressMapping } export interface ActionOutputMeta { display?: "summary" | "detail" | "raw" | "download" | "none" | string title?: LocalizedText fields?: CollectionFieldInfo[] mapping?: ActionOutputMapping [key: string]: any } export type MethodPermission = boolean | { allow: boolean; bulk?: boolean } export type SimpleMethodPermission = boolean | { allow: boolean } export interface AllowedMethodPermission { allow: boolean bulk?: boolean } export interface CollectionYourPermissions { get?: AllowedMethodPermission post?: AllowedMethodPermission put?: AllowedMethodPermission delete?: AllowedMethodPermission readonlyFields?: string[] hiddenFields?: string[] } export interface ActionYourPermissions { get?: { allow: boolean } post?: { allow: boolean } } export interface ProjectYourPermissions { _actions?: { [actionName: string]: ActionYourPermissions } [collectionName: string]: | CollectionYourPermissions | { [actionName: string]: ActionYourPermissions } | undefined } export interface PermissionSet { methods?: { get?: SimpleMethodPermission /** `true` = allow single POST, `{allow: true, bulk: true}` = allow single + bulk POST */ post?: MethodPermission /** `true` = allow single PUT, `{allow: true, bulk: true}` = allow single + bulk PUT */ put?: MethodPermission /** `true` = allow single DELETE, `{allow: true, bulk: true}` = allow single + bulk DELETE */ delete?: MethodPermission } /** MongoDB filter applied to all queries for this permission set */ filter?: { [key: string]: any } /** List of projection names this permission set is allowed to use */ validProjections?: string[] /** Fields that are read-only for this permission set */ readonlyFields?: string[] /** Fields that are hidden for this permission set */ hiddenFields?: string[] [key: string]: any } export interface ProjectionConfig { select?: { [field: string]: 0 | 1 } [key: string]: any } export interface CollectionFieldInfo { name: string type: string subFields?: CollectionFieldInfo[] index?: string[] validator?: FieldValidator meta?: { [key: string]: any } /** Field-level readonly — boolean or JS eval expression */ readonly?: BoolOrEval /** Field-level hidden — boolean or JS eval expression */ hidden?: BoolOrEval /** Reject unknown sub-fields not defined in subFields */ strictFields?: boolean } /** API info as returned by context.api() – JSON-serialized from Go API struct */ export interface ApiInfo { isOnline: boolean lastReload: string namespace: string meta?: { [key: string]: any } assets?: AssetConfig[] collections?: CollectionInfo[] actions?: ActionInfo[] jobs?: JobConfig[] errors?: { collection?: string; context?: string; error: any }[] [key: string]: any } /** Project info as returned by context.project() – JSON-serialized from Go Project struct */ export interface ProjectInfo { name: string description?: string namespace?: string users?: string[] configFile?: string api?: ApiInfo yourPermissions?: ProjectYourPermissions [key: string]: any } // ── Custom Tools (Admin) ───────────────────────────────────────────────── /** Project config entry (`meta.tools[]`). */ export interface AdminToolConfig { name: string label?: string | { [lang: string]: string } description?: string | { [lang: string]: string } icon?: string group?: string module: string | { eval: string } permissions?: string[] capabilities?: Array<"db" | "files" | "xlsx" | "ui" | "log" | "progress" | "state" | "action"> settings?: Record hidden?: boolean } /** File handle handed to tools (data URL, no live Blob). */ export interface AdminToolFile { src: string name: string type?: string size?: number } /** Fail-fast batch result; no rollback. */ export interface AdminToolBatchResult { ok: boolean failedIndex?: number error?: unknown } export interface AdminToolDb { find( collection: string, opts?: Record ): Promise count(collection: string, opts?: Record): Promise loadAll( collection: string, opts?: Record, onProgress?: (done: number, total: number) => void ): Promise create(collection: string, data: Record): Promise update(collection: string, id: string, data: Record): Promise> delete(collection: string, id: string): Promise updateMany(collection: string, items: Array<{ id: string; data: Record }>): Promise deleteMany(collection: string, ids: string[]): Promise } export interface AdminToolUi { supports(type: string): boolean slot(el: HTMLElement, element: any): void styles: CSSStyleSheet[] registerWidget(type: string, factory: (...args: any[]) => any, opts?: { replace?: boolean }): () => void render(el: HTMLElement, widget: Record): void | (() => void) field(opts: Record): any form(opts: Record): any [key: string]: any } export interface AdminToolI18n { lang: string languages: string[] t(key: string, vars?: Record): string text(value: string | Record | undefined | null, vars?: Record): string has(key: string): boolean add(lang: string, messages: Record): () => void add(messages: Record, lang?: string): () => void extend(lang: string, messages: Record): () => void extend(messages: Record, lang?: string): () => void onChange(cb: (lang: string) => void): () => void dispose?(): void } /** Browser context handed to a tool module. `context === ctx`. */ export interface AdminToolContext { context: AdminToolContext apiVersion: 1 uiVersion: 1 host: "tool" | "macro" | "server" capabilities: string[] project: ProjectInfo tool: AdminToolConfig auth: { id: string; username: string; role: number; permissions: string[] } | null db: AdminToolDb files: { get(input: File | Blob | string, name?: string): Promise } xlsx: any /** Runs a project action (requires capability `action`); resolves with the final event/body. */ action( name: string, options?: { method?: "get" | "post" | "put" | "delete" query?: Record data?: Record onProgress?: (event: Record) => void onUploadProgress?: (loaded: number, total: number) => void signal?: AbortSignal } ): Promise> state: Map lang: string languages: string[] i18n: AdminToolI18n theme: { mode: "light" | "dark"; tokens: Record } log(message: string, details?: unknown): void progress(done: number, total: number, label?: string): void signal: AbortSignal hostData: Record asset(specifier: string): string ui: AdminToolUi } export interface AdminToolModule { mount( el: HTMLElement, ctx: AdminToolContext ): void | (() => void) | Promise void)> messages?: Record> } export interface AdminToolException { status?: number msg: string json?: any } /** Represents a single audit log entry as received in audit.return hooks */ export interface AuditLogEntry { id?: string insertTime?: string updateTime?: string /** ID of the user who performed the action */ userId?: string /** Username of the user who performed the action */ username?: string /** Role of the user (0=admin, 1=user) */ userRole?: number /** Project namespace */ projectNamespace?: string /** Project display name */ projectName?: string /** Collection name */ collection?: string /** Action performed: create, bulkCreate, update, delete, bulkUpdate, bulkDelete, get, login, reload, shutdown */ action?: string /** Source information (type, collection, method, step, file, line) */ source?: { type?: string collection?: string method?: string step?: string file?: string line?: number } /** Document ID affected */ documentId?: string /** Full document snapshot at time of action */ snapshot?: { [key: string]: any } /** Changed fields (for updates) */ changes?: { [key: string]: any } /** Filter used (for queries/deletes) */ filter?: { [key: string]: any } /** Number of affected documents (e.g. deleteMany) */ count?: number /** Client IP address */ ip?: string /** Authentication method used (e.g. "jwt", "adminToken") */ authMethod?: string /** Label of the admin token used (if applicable) */ tokenLabel?: string /** Prefix of the admin token used (if applicable) */ tokenPrefix?: string [key: string]: any } export interface DbReadOptions { filter?: { [key: string]: any } selector?: { [key: string]: any } projection?: string offset?: number limit?: number sort?: string[] pipelineMod?: ( pipe: { [key: string]: any }[] ) => { [key: string]: any }[] } interface GetHookGetOnlyData { /** * true if only one document was requested via /COLLECTION/ID. * In audit.return hooks this is always true (entries are processed individually). */ one?: boolean /** * Get list of documents. * - In get.return hooks: array of collection documents * - In audit.return hooks: array with a single AuditLogEntry */ results(): CollectionDocument[] | AuditLogEntry[] } interface GetHookData { /** * filter map only valid for "get" hooks */ filter?: { [key: string]: any } /** * selector map only valid for "get" hooks */ selector?: { [key: string]: any } /** * offset only valid for "get" hooks */ offset?: number /** * limit only valid for "get" hooks */ limit?: number /** * sort only valid for "get" hooks */ sort?: string[] | string /** * pipelineMod is a function to modify the mongodb query pipeline */ pipelineMod?: ( pipe: { [key: string]: any }[] ) => { [key: string]: any }[] } interface PostHookData { /** * post data only valid in "post" and "put" hooks. * For bulk hooks (bulkCreate), this is an array of documents. */ data?: CollectionDocument | CollectionDocument[] /** * Number of created documents — only set in post.bulkReturn hook */ created?: number /** * Array of created document IDs — only set in post.bulkReturn hook */ ids?: string[] /** * Number of modified documents — only set in put.bulkReturn hook */ modified?: number /** * Number of deleted documents — only set in delete.bulkReturn hook */ deleted?: number } interface JobConfig { /** * meta object */ meta?: any /** * cron job interval specification */ cron?: string /** * job program type */ type: "javascript" /** * jobs program file */ file?: string /** * execution timeout in seconds */ timeout?: number } interface JobData { /** * job is object of job config */ job?: JobConfig } /** * Embedding provider as exposed by `config.server()` — mirror of * `ConfigEmbeddingProvider` (secrets and modelPath are stripped from the JSON). */ export interface EmbeddingProviderConfig { name: string /** "native" (ONNX in-process) or "flagembedding" (external HTTP endpoint) */ type: string model?: string dimensions?: number baseURL?: string documentPrefix?: string queryPrefix?: string /** flagembedding: HTTP bound; native: per-call bound (entry-only) */ timeoutPerAttempt?: string /** Group-only metric knob (feeds lowest-latency routing) */ slowThreshold?: string /** Weights/build tag; part of the model identity used by groups */ revision?: string /** false = endpoint/model has no sparse vectors (native skips the sparse session) */ sparse?: boolean } /** Single-query routing of an embedding group (`onSingleQuery`). */ export interface EmbeddingOnSingleQueryConfig { policy?: | "prefer-in-order" | "fastest-wins" | "round-robin" | "lowest-latency" | "weighted" /** Comma-separated names (YAML list is joined with commas before marshalling) */ preferredOrder?: string timeoutPerAttempt?: string timeoutTotal?: string autoFailback?: boolean raceDelay?: string raceMaxFanout?: number weights?: number[] /** Digits as string (Go field is a string, validated with Atoi; must be > 0) */ latencyWindow?: string retryAttempts?: number retryBackoff?: string retryBackoffMax?: string hedgeAfterSlow?: string } /** Bulk-write sharding of an embedding group (`onBulkWrite`). */ export interface EmbeddingOnBulkWriteConfig { distribution?: "round-robin" | "lowest-latency" | "weighted" maxConcurrentTotal?: number maxConcurrentPerEndpoint?: number timeoutPerAttempt?: string timeoutTotal?: string } /** Health/breaker timing of an embedding group (`health`). */ export interface EmbeddingHealthConfig { /** > 0 also enables late join/recovery of quarantined members */ checkInterval?: string checkTimeout?: string unhealthyAfterFailures?: number healthyAfterSuccesses?: number cooldownAfterUnhealthy?: string } /** Embedding failover group as exposed by `config.server()`. */ export interface EmbeddingGroupConfig { name: string description?: string members: string[] onSingleQuery?: EmbeddingOnSingleQueryConfig onBulkWrite?: EmbeddingOnBulkWriteConfig health?: EmbeddingHealthConfig } /** Embedding section as exposed by `config.server()`. */ export interface EmbeddingConfig { providers?: EmbeddingProviderConfig[] groups?: EmbeddingGroupConfig[] /** Directory of golden verification files (default testdata/embedding-golden) */ goldenPath?: string } /** * Member state from `GET …/admin/embedding/status` (server scope keeps * `lastError`, project scope redacts it). */ export interface EmbeddingMemberHealth { state: "live" | "degraded" | "quarantined" | "offline" breaker: "closed" | "open" | "half-open" lastError?: string latencyMs?: number successes?: number failures?: number slowCount?: number } /** Group state from `GET …/admin/embedding/status`. */ export interface EmbeddingGroupHealth { /** null while no member is live */ referenceMember: string | null members: { [member: string]: EmbeddingMemberHealth } } /** Project-scope payload: `{ namespace, health: { groups } }`. */ export interface EmbeddingHealthProjectResponse { namespace: string health: { groups: { [group: string]: EmbeddingGroupHealth } } } /** Server-scope payload: `{ groups }`. */ export interface EmbeddingHealthServerResponse { groups: { [group: string]: EmbeddingGroupHealth } } interface ConfigPackage { /** * get current namespace string * */ namespace(): string /** * get current project object * */ project(): ProjectInfo /** * Read a project secret from `secrets:` in the project config. * * Secrets are never part of `project()`, a project API response or any * other JSON projection — hooks and actions only. Values are substituted * from `config.yml.env` like every other `${VAR}`. * * @param name secret name * @returns the value, or `null` when no such secret is configured */ secret(name: string): string | null /** * Names of the configured project secrets (sorted). Values are never * included — this is for diagnostics and setup screens. */ secretNames(): string[] /** * get server config object (sensitive fields like jwtSecret, adminTokens, apiKeys are excluded) * */ server(): { api: { port: number secureCookies?: boolean accessTokenLifetime?: string refreshTokenLifetime?: string } security: { allowAbsolutePaths: boolean allowUpperPaths: boolean } llm?: { providers?: { name: string type: string baseURL: string defaultModel: string models?: string[] maxTokensPerRequest?: number }[] } /** Raw JSON of config.Server.Embedding (apiKey/modelPath stripped, JSON tags decide) */ embedding?: EmbeddingConfig audit?: { enabled: boolean defaultTTL: string defaultLimit?: number maxLimit?: number } ratelimit?: { enabled?: boolean loginInitialDelay?: string loginMaxDelay?: string loginResetAfter?: string } hook?: { cache: { maxEntries?: number defaultTTL?: string } ratelimit: { backoffInitialDelay?: string backoffMaxDelay?: string backoffResetAfter?: string windowSize?: string windowMaxHits?: number } } } } interface DbPackage { /** * read results from a collection * * @param colName collection name * @param options options map */ find(colName: string, options?: DbReadOptions): CollectionDocument[] /** * read count of documents for filter from a collection * * @param colName collection name * @param options options map (only filter is valid) */ count(colName: string, options?: DbReadOptions): number /** * create a document in a collection * * @param colName collection name * @param data data map */ create(colName: string, data: CollectionDocument): CollectionDocument /** * update a document in a collection * * Supports field-level operators in data: * - `{ "$inc": value }` — increment by value * - `{ "$mul": value }` — multiply by value * - `{ "$unset": true }` — remove the field * - `{ "$set": value }` — explicit set (same as plain value) * * Operators are converted to native MongoDB operators and executed * atomically in a single DB call. * * @param colName collection name * @param id id of entry * @param data new/changed data (may contain operators) * @param options optional: `{ raw: true }` to pass data as raw MongoDB update document */ update( colName: string, id: string, data: CollectionDocument, options?: { raw?: boolean } ): CollectionDocument /** * deletes one document by id from collection * * @param colName collection name * @param id id of entry */ delete(colName: string, id: string): { message: "ok" } /** * deletes documents by filter from collection * * @param colName collection name * @param options options map, only filter valid */ deleteMany( colName: string, options?: DbReadOptions ): { message: "ok"; removed: number } /** * update multiple documents matching a filter * * Use `changes` for simple field updates (supports operators like $inc, $mul). * Use `update` for raw MongoDB update documents. * * @param colName collection name * @param options options with filter and changes/update */ updateMany( colName: string, options: { filter?: { [key: string]: any } /** Field updates — may contain operators like { "$inc": 1 } */ changes?: { [key: string]: any } /** Raw MongoDB update document (e.g. { "$inc": { stock: -1 } }) */ update?: { [key: string]: any } } ): { message: "ok"; modified: number } } interface SmtpPackage { /** * send an email * * @param options email options map */ sendMail(options: { host?: string username?: string password?: string to: string | string[] cc?: string | string[] bcc?: string | string[] subject?: string from: string fromName?: string replyTo?: string plain?: string html?: string attach?: string | string[] }): void } interface FsPackage { /** * get directory path of api config file * */ configDir(): string /** * read a file relative to config dir and return its content * * @param path relative file path * @param options optional options */ readFile( path: string, options?: { bytes: boolean // if true return []byte instead of string } ): string | any /** * write data to a file relative to config dir * * @param path relative file path * @param data string or []byte data */ writeFile(path: string, data: string | any): null /** * stat file or directory * * @param path */ stat(path: string): { name: string size: number isDir: boolean modTime: string } /** * list directory entries * * @param path */ readDir(path: string): { name: string size: number isDir: boolean modTime: string }[] /** * make directory and all missing sub directories, no error if directory already exists * * @param path */ mkDir(path: string): void /** * remove file or empty directory * * @param path */ remove(path: string): void /** * copy file or directory * * @param src * @param dest */ copy(src: string, dest: string): void } interface TplPackage { /** * execute a template code and return result * * @param code template code * @param contextData template context map */ execute( code: string, contextData?: { [key: string]: any } ): string } interface HttpPackage { /** * http request — reads the entire response body into memory * * @param url url for request * @param options request options */ fetch( url: string, options?: { method?: string headers?: { [key: string]: string } body?: string /** timeout in seconds (default 10) */ timeout?: number } ): { status: number statusText: string headers: { [key: string]: string } trailer: { [key: string]: string } url: string body: { text(): string json(): any } } /** * streaming http request — response body is NOT read into memory. * Use body.read() to read line by line (ideal for SSE / newline-delimited * protocols like OpenAI streaming API). * * @param url url for request * @param options request options */ fetchStream( url: string, options?: { method?: string headers?: { [key: string]: string } body?: string /** timeout in seconds (default 0 = no timeout, hook timeout controls duration) */ timeout?: number } ): { status: number statusText: string headers: { [key: string]: string } body: { /** returns the next line as string, or null at EOF */ read(): string | null /** explicitly closes the response body (auto-closed at EOF) */ close(): void } } } interface DebugPackage { /** * dumps data to header and server log * * @param toDump data to dump */ dump(...toDump: any): void /** * get Sentry trace id */ sentryTraceId(): string /** * sleep * * @param ms sleep time in milliseconds */ sleep(ms: number): void } interface ResponsePackage { /** * set response header (must be called before writeHeader/write) * * @param name header name * @param value value */ header(name: string, value: any): void /** * set the HTTP status code — must be called before write(). * If not called, the first write() will implicitly send status 200. * * @param status HTTP status code */ writeHeader(status: number): void /** * write data directly to the HTTP response body. * Use for streaming responses (e.g. SSE to a chat widget). * * @param data string or byte data to write */ write(data: string | any): void /** * flush buffered data to the client immediately. * Essential for streaming / SSE to push chunks without waiting * for the full response to complete. */ flush(): void /** * write a Server-Sent Event and flush immediately. * Formats the output as SSE: "event: {event}\ndata: {data}\n\n" * If called with one argument, only "data: {data}\n\n" is written. * * @param event SSE event name (optional if using single-argument form) * @param data SSE data payload */ writeSSE(event: string, data: string): void writeSSE(data: string): void } interface UserPackage { /** * get JWT authentication */ auth(): { id: string username: string role: number permissions: string[] } } interface BcryptPackage { /** * hash password via bcrypt algo * * @param password clear text password * @param options hashing options */ hash( password: string, options?: { cost?: number } ): string /** * check password against hashed password via bcrypt algo * * @param password clear text password * @param hash hashed password */ check(password: string, hash: string): boolean } interface JwtPackage { /** * create a jwt signed token string * * @param claims data object * @param options options (secret, validityDuration = expiry in X seconds) */ create( claims: { [key: string]: any }, options?: { secret?: string validityDuration?: number } ): string /** * parse jwt token string * * @param token token string * @param options options (secret) */ parse( token: string, options?: { secret?: string } ): { error?: string valid: boolean method: { Name: string Hash: number } header: { alg: string typ: string } claims: { exp?: number [key: string]: any } } } interface CharsetPackage { /** * decode byte-oriented input using the given encoding * * supported encodings: utf-8, iso-8859-1 */ decode(input: string | Int8Array | number[], encoding: string): string /** * convert iso8859 to utf8 * * @param iso8859 iso string or bytes */ iso8859ToUtf8(iso8859: string | Int8Array | number[]): string } interface ImagePackage { /** * convert image from source file to target file with filters * * @param sourceFile * @param targetFile * @param filters */ filter( sourceFile: string, targetFile: string, filters: ImageFilterParams[] ): void } interface XmlPackage { /** * create xml string * * @param data object or array (map with string keys as nodes (-KEY will be attribute in parent node)) * @param options options */ create( data: { [key: string]: any }, options?: { rootElement?: string includeHeader?: boolean } ): string /** * parse xml string to json * * @param xml xml string * @param options options */ parse(xml: string, options?: {}): any } interface CookiePackage { /** * get cookie from http header * * @param name cookie name */ get(name: string): string /** * set cookie via http header * * @param name cookie name * @param value cookie value * @param options cookie options */ set( name: string, value: string, options?: { maxAge?: number path?: string domain?: string secure?: boolean httpOnly?: boolean sameSite?: "strict" | "lax" | "none" } ): void } interface PdfPackage { /** * generate pdf from html * * @param html html string * @param options options * * @returns []byte of pdf data */ fromHTML( html: string, options?: { copies?: number // Number of copies to print into the pdf file (default 1) dpi?: number // Change the dpi explicitly (this has no effect on X11 based systems) grayscale?: boolean // PDF will be generated in grayscale imageDpi?: number // When embedding images scale them down to this dpi (default 600) imageQuality?: number // When jpeg compressing images use this quality (default 94) lowQuality?: boolean // Generates lower quality pdf/ps. Useful to shrink the result document space marginBottom?: number // Set the page bottom margin marginLeft?: number // Set the page left margin (default 10mm) marginRight?: number // Set the page right margin (default 10mm) marginTop?: number // Set the page top margin noCollate?: boolean // Do not collate when printing multiple copies (default collate) noPdfCompression?: boolean // Do not use lossless compression on pdf objects orientation?: "Portrait" | "Landscape" // Set orientation to Landscape or Portrait (default Portrait) pageHeight?: number // Page height pageSize?: string // Set paper size to: A4, Letter, etc. (default A4) pageWidth?: number // Page width title?: string // The title of the generated pdf file (The title of the first document is used if not specified) // page settings printMediaType?: boolean // Use print media-type instead of screen footerCenter?: string // Centered footer text footerFontName?: string // Set footer font name (default Arial) footerFontSize?: number // Set footer font size (default 12) footerLeft?: string // Left aligned footer text footerLine?: boolean // Display line above the footer footerRight?: string // Right aligned footer text footerSpacing?: number // Spacing between footer and content in mm (default 0) footerHTML?: string // URL to footer html headerCenter?: string // Centered header text headerFontName?: string // Set header font name (default Arial) headerFontSize?: number // Set header font size (default 12) headerLeft?: string // Left aligned header text headerLine?: boolean // Display line below the header headerRight?: string // Right aligned header text headerSpacing?: number // Spacing between header and content in mm (default 0) headerHTML?: string // URL to header html } ): any /** * process existing pdf data * * @param command pdfcpu command * @param pdfData []byte of pdf data, multiple []byte as array of pdf's to merge or object with description to create * @param options options * * @returns []byte of new pdf data */ cpu( command: "watermark" | "stamp" | "merge" | "rotate" | "create", pdfData: any | any[], options?: { pages?: (string | number)[] description?: { fontname?: string points?: number rtl?: boolean position?: | "full" | "tl" | "tc" | "tr" | "l" | "c" | "r" | "bl" | "bc" | "br" offset?: string scalefactor?: number | string aligntext?: "left" | "center" | "right" | "justified" strokecolor?: string fillcolor?: string backgroundcolor?: string rotation?: number diagonal?: 1 | 2 opacity?: number rendermode?: 0 | 1 | 2 margins?: number | string border?: number | string url?: string } mode?: "text" | "image" | "pdf" bytes?: any // []byte of watermark image file?: string // file for pdf watermark text?: string // text for text watermark rotation?: number } ): any } /** Byte encodings shared by the crypto/base64 hook helpers. */ export type ByteEncoding = "hex" | "base64" | "base64url" | "bytes" interface CryptoPackage { /** * get hex of sha256 hash * * @param sata string * * @returns hex hash */ sha256(data: string): string /** * get hex of md5 hash * * @param sata string * * @returns hex hash */ md5(data: string): string /** * Cryptographically secure random bytes (`crypto/rand`, never `Math.random`). * * `n` is the number of **bytes**, not characters; allowed range 1–4096. * Without options the raw bytes are returned (JSON output base64-encodes them, * like `fs.readFile(..., { bytes: true })`). * * @param n number of random bytes (1–4096) * @param options.encoding `hex` | `base64` | `base64url` | `bytes` (default `bytes`) */ randomBytes(n: number): Int8Array randomBytes(n: number, options: { encoding: "bytes" }): Int8Array randomBytes( n: number, options: { encoding: "hex" | "base64" | "base64url" } ): string randomBytes( n: number, options: { encoding: ByteEncoding } ): string | Int8Array /** * URL-safe token from `n` random bytes. * * Default encoding is unpadded `base64url`: `randomToken(32)` yields 43 * characters and 256 bit. `encoding: "bytes"` is rejected — a token is a string. * * @param n number of random bytes (1–4096) * @param options.encoding `base64url` (default) | `base64` | `hex` */ randomToken(n: number): string randomToken( n: number, options: { encoding: "hex" | "base64" | "base64url" } ): string /** * HMAC signature over `data`, keyed with `key`. * * Supported algorithms: `sha1` (TOTP/RFC 6238 requires it), `sha256`, * `sha512`. MD5 is not offered. `key` must not be empty. Output defaults * to hex. * * @param alg hash algorithm, case-insensitive * @param key secret key (string = UTF-8, or bytes) * @param data payload (string = UTF-8, or bytes) * @param options.encoding `hex` (default) | `base64` | `base64url` | `bytes` */ hmac( alg: "sha1" | "sha256" | "sha512" | (string & {}), key: string | Int8Array, data: string | Int8Array ): string hmac( alg: "sha1" | "sha256" | "sha512" | (string & {}), key: string | Int8Array, data: string | Int8Array, options: { encoding: "bytes" } ): Int8Array hmac( alg: "sha1" | "sha256" | "sha512" | (string & {}), key: string | Int8Array, data: string | Int8Array, options: { encoding: "hex" | "base64" | "base64url" } ): string hmac( alg: string, key: string | Int8Array, data: string | Int8Array, options: { encoding: ByteEncoding } ): string | Int8Array /** * Constant-time comparison of two values (`hmac.Equal`). * * Use this for signatures, tokens and TOTP codes — never `===`, which * returns early and leaks how many leading characters matched. * Different lengths return `false` immediately: the length is not secret. */ timingSafeEqual( a: string | Int8Array, b: string | Int8Array ): boolean } /** * Time-based one-time passwords (RFC 6238 / RFC 4226). * * All functions accept the secret as a base32 string (lowercase and * grouping whitespace allowed, as authenticator apps display it) or as * bytes. Stateless: replay protection, rate limiting and lockout are the * hook's responsibility. */ interface TotpPackage { /** * Current code for the given time step. * * @param secret base32 string or bytes * @param options.digits 6 (default), 7 or 8 * @param options.period time step in seconds (default 30) * @param options.algorithm `sha1` (default) | `sha256` | `sha512` * @param options.t unix seconds to generate for (default: now) */ generate(secret: string | Int8Array, options?: TotpOptions): string /** * Verify a user-supplied code in constant time. * * Returns `false` for wrong-length or non-numeric codes (user input), * never throws for them. The default window is ±1 step (clock skew). * * @param secret base32 string or bytes * @param code the entered digits * @param options.window accepted steps before/after (0–10, default 1) */ verify( secret: string | Int8Array, code: string, options?: TotpOptions & { window?: number } ): boolean /** * `otpauth://totp/...` URI for enrollment (QR code / manual entry). * * @param options.secret base32 string or bytes (required) * @param options.account account label, e.g. the user's mail (required) * @param options.issuer issuer name shown by the app (recommended) */ uri(options: TotpOptions & { secret: string | Int8Array account: string issuer?: string }): string } export interface TotpOptions { /** 6 (default), 7 or 8 */ digits?: number /** time step in seconds (1–3600, default 30) */ period?: number /** `sha1` (default) | `sha256` | `sha512` */ algorithm?: "sha1" | "sha256" | "sha512" /** unix seconds to generate/verify for (default: now) */ t?: number } interface JsonPackage { /** * parse json string to json * @param str json string */ parse(str: string): any /** * stringify json string * @param json json object */ stringify(json: any): string } interface ExecPackage { command( cmd: string, options?: { args?: string[] stdin?: string dir?: string env?: string[] timeout?: number returnObject?: boolean combineOutput?: boolean } ): string command< T extends { args?: string[] stdin?: string dir?: string env?: string[] timeout?: number returnObject?: boolean combineOutput?: boolean }, >( cmd: string, options: T ): T["returnObject"] extends true ? T["combineOutput"] extends true ? { output: string; exitCode: number } : { stdout: string; stderr: string; exitCode: number } : string } /** RFC 4648 encoding variant shared by the base64 helpers. */ export type BaseVariant = "base64" | "base64url" | "base32" export interface Base64Options { /** * Alphabet: `base64` (default, `+/`), `base64url` (`-_`) or `base32` * (RFC 4648 §6, uppercase). */ variant?: BaseVariant /** * RFC padding. Default: `true` for `base64`, `false` for `base64url` * and `base32` (JWT parts and TOTP secrets are unpadded). */ padding?: boolean } export interface Base64DecodeOptions extends Base64Options { /** Return raw bytes instead of a string (default: false). */ returnBytes?: boolean } interface Base64Package { /** * Encode a string/bytes value. Without options this is padded standard * base64 — the historical, unchanged behaviour. */ encode(data: string | Int8Array, options?: Base64Options): string /** * Decode. Without an explicit `padding`, both padded and unpadded input * are accepted; `base32` additionally accepts lowercase and grouped * input ("MZXW 6YTB OI"). Alphabets stay strict. */ decode(data: string): string decode( data: string, options: Base64DecodeOptions & { returnBytes: true } ): Int8Array decode( data: string, options: Base64DecodeOptions & { returnBytes?: false } ): string decode( data: string, options: Base64DecodeOptions & { returnBytes: boolean } ): string | Int8Array } /** * Project-scoped in-memory cache. * * Entries survive across requests but are cleared on project reload. * Configured via project config `hook.cache` or server config `hook.cache`. */ interface CachePackage { /** * Store a value in the cache. * * @param key Cache key * @param value Any JSON-serializable value * @param ttlMs Optional time-to-live in milliseconds (overrides defaultTTL) */ set(key: string, value: any, ttlMs?: number): void /** * Retrieve a value from the cache. * * @param key Cache key * @returns The cached value, or `null` if not found / expired. */ get(key: string): any | null /** * Check whether a key exists (and is not expired) in the cache. * * @param key Cache key */ has(key: string): boolean /** * Delete a single key from the cache. * * @param key Cache key * @returns `true` if the key existed, `false` otherwise. */ delete(key: string): boolean /** * Remove all entries from the cache. */ clear(): void /** * Return the number of entries currently in the cache. */ count(): number } /** * Project-scoped rate limiter with two strategies: * - **Backoff**: Exponential back-off per key (e.g. login brute-force protection). * - **Window**: Sliding-window counter per key (e.g. API call quotas). * * Configured via project config `hook.ratelimit` or server config `hook.ratelimit`. */ interface RatelimitPackage { /** * Check whether a key is currently blocked by the exponential back-off strategy. * * @param key Rate-limit key (e.g. IP address or user ID) * @returns `{ blocked, retryAfterMs }` — if blocked, retryAfterMs indicates how long to wait. */ backoffCheck(key: string): { blocked: boolean; retryAfterMs: number } /** * Record a failure for the given key, increasing its back-off delay. * * @param key Rate-limit key */ backoffRecord(key: string): void /** * Reset the back-off state for a key (e.g. after a successful login). * * @param key Rate-limit key */ backoffReset(key: string): void /** * Check the sliding-window strategy for a key. * * @param key Rate-limit key * @returns `{ allowed, retryAfterMs }` — if not allowed, retryAfterMs indicates how long to wait. */ windowCheck(key: string): { allowed: boolean; retryAfterMs: number } /** * Reset the sliding-window counter for a key. * * @param key Rate-limit key */ windowReset(key: string): void /** * Return the current hit count in the sliding window for a key. * * @param key Rate-limit key */ windowCount(key: string): number } /** * Options for channel.subscribe(). */ interface ChannelSubscribeOptions { /** Maximum number of buffered messages per subscriber (default: 64). */ bufferSize?: number /** * Behaviour when the buffer is full. * - "drop-oldest" (default): discard the oldest message * - "drop-newest": discard the incoming message */ onFull?: "drop-oldest" | "drop-newest" /** Time-to-live per message in milliseconds. Expired messages are skipped on receive. */ messageTTL?: number /** Replay the last N messages from the channel's ring-buffer to the new subscriber. */ lastN?: number /** Replay only messages younger than maxAge milliseconds. */ maxAge?: number } /** * A subscription to a real-time channel. * Returned by channel.subscribe(). */ interface ChannelSubscription { /** * Blocks until a message arrives, the client disconnects, or the * subscription/channel is closed. * * @returns The message data, or `null` when the client disconnects. * @throws `{error: string, code: "channel_closed"}` when the * subscription or channel is closed (e.g. project reload). */ receive(): any /** Manually close the subscription (idempotent). */ close(): void } /** * Real-time pub/sub channel package. * * Channels are in-memory, project-scoped, and named freely (not bound * to collections). Every subscriber receives an independent deep-copy * of each message. */ interface ChannelPackage { /** * Subscribe to a named channel. The calling hook will block until * the client disconnects or the subscription is closed. * The execution timeout is automatically disabled for hooks that subscribe. * * @param name Channel name (arbitrary string). * @param options Optional subscribe options. */ subscribe( name: string, options?: ChannelSubscribeOptions ): ChannelSubscription /** * Publish data to all current subscribers of a named channel. * This is a fire-and-forget operation; if no one is subscribed, the * message is buffered in the channel's ring-buffer for future replay. * * @param name Channel name. * @param data Arbitrary data (will be deep-copied per subscriber). */ send(name: string, data: any): void } export interface HookContext extends GetHookData, GetHookGetOnlyData, PostHookData, JobData { request(): { method: string remoteAddr: string clientIp(): string host: string url: string path: string param(p: string): string query(q: string): string header(h: string): string body(): string /** * bodyBytes returns the raw request body bytes for later decoding via charset.decode */ bodyBytes(): Int8Array } api(): ApiInfo project(): ProjectInfo collection(): CollectionInfo config: ConfigPackage db: DbPackage smtp: SmtpPackage fs: FsPackage tpl: TplPackage http: HttpPackage debug: DebugPackage response: ResponsePackage user: UserPackage bcrypt: BcryptPackage jwt: JwtPackage charset: CharsetPackage image: ImagePackage xml: XmlPackage cookie: CookiePackage pdf: PdfPackage crypto: CryptoPackage totp: TotpPackage json: JsonPackage exec: ExecPackage base64: Base64Package channel: ChannelPackage cache: CachePackage ratelimit: RatelimitPackage } export interface HookException { status?: number html?: string string?: string bytes?: any json?: any file?: string log?: boolean [key: string]: any } export interface HookResponse extends GetHookData, PostHookData { data?: CollectionDocument results?: any } var context: HookContext } export { HookResponse, HookException, HookContext, CollectionDocument }