import type { RequestHandler } from 'express'; import type { Application } from 'express'; import { HttpResponse, Ng2RestFetchRequestConfig, RestResponseWrapper, } from 'ng2-rest/src'; import { Observable } from 'rxjs'; import { _ } from 'tnp-core/src'; import { CoreModels } from 'tnp-core/src'; import type { ControllerConfig } from './config/controller-config'; import type { MethodConfig } from './config/method-config'; import type { EndpointContext } from './endpoint-context'; import { ExpressRequest, ExpressResponse } from './express-types'; import { TaonUploadedFile } from './helpers/express-request-to-form-data'; import { Translation } from '@taon-dev/i18n/src'; // ! TODO make it as a nice way to wrap normal request export class TaonRestResponseWrapper extends RestResponseWrapper {} export const BaseTaonClassesNames = [ 'BaseCrudController', 'BaseController', 'BaseAbstractEntity', 'BaseEntity', 'BaseContext', 'BaseCustomRepository', 'BaseFileUploadMiddleware', 'BaseMiddleware', 'BaseClass', 'BaseInjector', 'BaseMigration', 'BaseProvider', 'BaseRepository', 'BaseSubscriberForEntity', 'BaseCliWorkerController', 'PortsController', 'PortsContext', ] as const; export const TaonTempDatabasesFolder = 'databases'; export const TaonTempRoutesFolder = 'routes'; export namespace Models { export const DatabasesFolder = TaonTempDatabasesFolder; export type FrameworkMode = | 'backend-frontend(tcp+udp)' | 'backend-frontend(cloudflare)' | 'remote-backend(tcp+udp)' | 'backend-frontend(ipc-electron)' | 'backend-frontend(websql-electron)' | 'backend-frontend(websql)'; //#region models / class types export enum ClassType { ENTITY = 'ENTITY', CONTROLLER = 'CONTROLLER', REPOSITORY = 'REPOSITORY', PROVIDER = 'PROVIDER', SUBSCRIBER = 'SUBSCRIBER', MIGRATION = 'MIGRATION', MIDDLEWARE = 'MIDDLEWARE', } export const ClassTypeKey = { [ClassType.ENTITY]: 'entities', [ClassType.CONTROLLER]: 'controllers', [ClassType.REPOSITORY]: 'repositories', [ClassType.PROVIDER]: 'providers', [ClassType.SUBSCRIBER]: 'subscribers', [ClassType.MIGRATION]: 'migrations', [ClassType.MIDDLEWARE]: 'middlewares', } as { [key in ClassType]: keyof ContextOptions< any, any, any, any, any, any, any, any >; }; //#endregion //#region models / middleware type export type MiddlewareType = [Function, any[]]; //#endregion //#region models / db recreate mode /** * DROP_DB__RUN_MIGRATIONS (default for development) * Drop all tables + recreate them + run migrations * synchronize: true , dropSchema: true * use migrations: true * * PRESERVE_DATA__RUN_MIGRATIONS (default for production) * Do not drop tables, only run migrations * synchronize: false, dropSchema: false * use migrations: true */ export enum DBRecreateMode { DROP_DB__RUN_MIGRATIONS = 'DROP_DB__RUN_MIGRATIONS', PRESERVE_DATA__RUN_MIGRATIONS = 'PRESERVE_DATA__RUN_MIGRATIONS', } export type DBRecreateModeType = `${DBRecreateMode}`; //#endregion //#region models / database connection options export class DatabaseConfigTypeOrm { /** * database name */ database?: string; /** * only for file base db: sqlite, sqljs */ location?: string; synchronize: boolean; dropSchema: boolean; type?: CoreModels.DatabaseType; /** * Persists db on disk/local-storage if serverless db */ autoSave?: boolean; /** * for websql db mode * true by default */ useLocalForage?: boolean; logging: boolean; databasePort?: number; databaseHost?: string; databaseUsername?: string; databasePassword?: string; } //#endregion //#region models / database config export class KVDatabaseConfig { static from( databasePartialConfig: Partial, ): KVDatabaseConfig { return _.merge(new KVDatabaseConfig(), databasePartialConfig); } /** * json kv db location */ declare dbLocationFn?: (options?: { port?: string | number; contextName?: string; baseLocation?: string; repositoryClassName?: string; cwd?: string; ctx?: EndpointContext; }) => string; } export class DatabaseConfig extends DatabaseConfigTypeOrm { /** * Default value 'DROP_ALL'. * * Tell framework what is happening with db * when context is starting. */ public recreateMode?: DBRecreateModeType; static from( databasePartialConfig: Partial< Omit< DatabaseConfig, 'synchronize' | 'dropSchema' | 'databaseConfigTypeORM' > >, ): DatabaseConfig { return _.merge(new DatabaseConfig(), databasePartialConfig); } get databaseConfigTypeORM(): DatabaseConfigTypeOrm { //#region @websqlFunc const result = _.cloneDeep(this) as DatabaseConfig; if (result.recreateMode) { if (result.recreateMode === 'DROP_DB__RUN_MIGRATIONS') { result.synchronize = true; result.dropSchema = true; } else if (result.recreateMode === 'PRESERVE_DATA__RUN_MIGRATIONS') { result.synchronize = false; result.dropSchema = false; } } delete result.recreateMode; return result as any; //#endregion } } //#endregion //#region models / session // export type ISession = { // secret?: string; // saveUninitialized?: boolean; // /** // * max age of session // */ // cookieMaxAge?: number; // secure?: boolean; // resave?: boolean; // }; //#endregion //#region models / context options export type ConnectionOptionsLogs = { http?: boolean; socketConnections?: boolean; realtime?: boolean; framework?: boolean; db?: boolean; migrations?: boolean; routes?: boolean; }; export interface ContextOptions< CONTEXTS, CONTROLLERS, ENTITIES, REPOSITORIES, PROVIDERS, SUBSCRIBERS, MIGRATIONS, MIDDLEWARES, > { appId?: string; contextName: string; /** * if defined and different from contextName * - context will NOT be initialized */ activeContext?: string | null; /** * IMPORTANT! provide full url that starts with http:// or https:// * host/port for initing backend server */ host?: string; /** * Needs to be specified in docker environment only */ hostPortNumber?: number; /** * IMPORTANT! provide full url that starts with http:// or https:// * frontend host only needed when we are * using withCredentials for fetch * and session cookie * or realtime communication */ frontendHost?: string; /** * Needs to be specified in docker environment only */ frontendHostPortNumber?: number; /** * User ipc for communication between BE/FE * when electron is used as a platform * Default: true */ useIpcWhenElectron?: boolean; /** * taon contexts here * (module like structure) */ contexts?: CONTEXTS; /** * taon controller here * (glue between frontend and backend) */ controllers?: CONTROLLERS; /** * taon entities * (entities are used to create tables in db) */ entities?: ENTITIES; /** * taon repositories * (repositories are used to access data from db) */ repositories?: REPOSITORIES; /** * taon providers * (context singletons) */ providers?: PROVIDERS; /** * taon subscribers * (subscribers are used to listen to db events) */ subscribers?: SUBSCRIBERS; /** * taon migrations * (migrations are used to update db schema and achieve proper CI/CD) */ migrations?: MIGRATIONS; /** * taon middlewares * middlewares are used to intercept requests * and responses in the context */ middlewares?: MIDDLEWARES; /** * Should context use session: * - on backend for fetch * - cors with credentials * * * @default true */ useSession?: boolean; /** * taon is not going to write .rest files to cwd() */ skipWritingServerRoutes?: boolean; /** * TODO - this is still in progress * @deprecated */ productionMode?: boolean; /** * If you want your context to never be started as separated server * use abstract: true * @default: false */ abstract?: boolean; logs?: boolean | ConnectionOptionsLogs; database?: boolean | Partial; kv_database?: boolean | Partial; /** * disable default realtime communication through TCP upgrade sockets */ disabledRealtime?: boolean; /** * Will be removed soon - cloud will handle certs and https * @deprecated */ https?: { key: string; cert: string; }; /** * TODO - will be removed soon * @deprecated */ publicAssets?: { serverPath: string; locationOnDisk: string }[]; /** * by default cwd === process.cwd() */ cwd?: string; } //#endregion //#region models / http export namespace Http { export type ContextENDPOINT = { target: Function; initFN: Function }; export type FormlyFromType = 'material' | 'bootstrap'; export type ExpressContext = ( req: ExpressRequest, res: ExpressResponse, ) => T; export type SyncResponse = string | T; export interface TaonStreamResponseOptions { stream: ReadableStream; statusCode?: number; contentType?: string; /** * Causes Content-Disposition: attachment */ filename?: string; /** * inline | attachment * default attachment when filename is provided */ disposition?: 'inline' | 'attachment'; /** * Only when actually known. * Streaming ZIP usually won't know this. */ contentLength?: number; headers?: Record; } export type ResponseFuncOpt = { /** * send to user response with circural dependencies */ circResponse?: (anyResponse: any) => SyncResponse; /** * send stream to user - it does not end conneciton */ streamResponse?: ( streamOptions: TaonStreamResponseOptions, ) => SyncResponse; }; export type SyncResponseFunc = ( options?: ResponseFuncOpt, ) => SyncResponse; export type MixResponse = SyncResponse | ExpressContext; export type PromiseObservableMix = Promise & { observable: Observable; }; export interface ClientAction { /** * @deprecated use request() mehods instead */ readonly received?: PromiseObservableMix>; request?( fetchConfig?: Ng2RestFetchRequestConfig, ): PromiseObservableMix>; } export interface RequestResults { bodyFormDataFiles?: TaonUploadedFile[]; t: Translation; expressPath: string; } export interface AsyncResponse { ( req?: ExpressRequest, res?: ExpressResponse, results?: RequestResults, ): Promise | SyncResponseFunc>; } export type Response = AsyncResponse & ClientAction; //#region @websql export interface AuthCallBack { (methodReference: Function): RequestHandler; } //#endregion } //#endregion //#region models / start params export interface TaonInitializeParams { onlyMigrationRun?: boolean; onlyMigrationRevertToTimestamp?: number; overrideExpressApp?: Application; overrideHost?: string; overrideContextName?: string; cloudflareEnv?: any; } export interface TaonCtrlBeforeEachRequestParams { req: ExpressRequest; res: ExpressResponse; expressPath: string; classConfig: Partial; methodConfig: Partial>; t: Translation; } export interface StartParams extends TaonInitializeParams { port?: number; args?: string[]; } export interface TaonCtxCloneParams { useAsRemoteContext?: boolean; overrideRemoteHost?: string; overrideContextName?: string; overrideUseSession?: boolean; overrideHost?: string; sourceContext?: EndpointContext; } //#endregion } export type TaonPaginationSortDirection = 'asc' | 'desc' | ''; export interface TaonPaginationSort { field: string; direction: TaonPaginationSortDirection; } export interface TaonPaginationQuery { pageNumber?: number; pageSize?: number; /** * Global search. */ search?: string; /** * Column-specific filtering. */ filters?: Record; sort?: TaonPaginationSort; /** * Optional custom query method defined on controller. */ callQueryMethod?: keyof T; } //#region multer file uplaod repsonse export interface MulterFileUploadResponse { ok: boolean; originalName: string; /** * R2 object key or local generated filename. * * Examples: * files/2026/08/07/uuid-photo.jpg * uuid-photo.jpg * * name change to this to avoid confusion with originalname * (similar to originalname with added uniq part) */ savedAs: string; size: number; mimetype: string; } //#endregion