UNPKG

alepha

Version:

Alepha is a convention-driven TypeScript framework for building robust, end-to-end type-safe applications, from serverless APIs to full-stack React apps.

1,564 lines (1,563 loc) 49.6 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { Validator } from "typebox/compile"; import * as TypeBoxValue from "typebox/value"; import * as TypeBox from "typebox"; import { Static as Static$1, StaticDecode, StaticDecode as Static, StaticDecode as StaticDecode$1, StaticEncode, StaticEncode as StaticEncode$1, TAny, TAny as TAny$1, TArray, TArray as TArray$1, TArrayOptions, TBigInt, TBoolean, TBoolean as TBoolean$1, TInteger, TInteger as TInteger$1, TKeysToIndexer, TKeysToIndexer as TKeysToIndexer$1, TNull, TNull as TNull$1, TNumber, TNumber as TNumber$1, TNumberOptions, TNumberOptions as TNumberOptions$1, TObject, TObject as TObject$1, TObjectOptions, TObjectOptions as TObjectOptions$1, TOmit, TOptional, TOptionalAdd, TOptionalAdd as TOptionalAdd$1, TPick, TPick as TPick$1, TProperties, TProperties as TProperties$1, TRecord, TRecord as TRecord$1, TSchema, TSchema as TSchema$1, TSchemaOptions, TString, TString as TString$1, TStringOptions, TStringOptions as TStringOptions$1, TTuple, TUnion, TUnion as TUnion$1, TUnsafe, TUnsafe as TUnsafe$1, TVoid } from "typebox"; import TypeBoxFormat from "typebox/format"; import { TLocalizedValidationError } from "typebox/error"; import { Readable } from "node:stream"; import { ReadableStream as ReadableStream$1 } from "node:stream/web"; //#region src/constants/KIND.d.ts /** * Used for identifying descriptors. * * @internal */ declare const KIND: unique symbol; //#endregion //#region src/constants/MODULE.d.ts /** * Used for identifying modules. * * @internal */ declare const MODULE: unique symbol; //#endregion //#region src/interfaces/Service.d.ts /** * In Alepha, a service is a class that can be instantiated or an abstract class. Nothing more, nothing less... */ type Service<T extends object = any> = InstantiableClass<T> | AbstractClass<T> | RunFunction<T>; type RunFunction<T extends object = any> = (...args: any[]) => T | void; type InstantiableClass<T extends object = any> = new (...args: any[]) => T; /** * Abstract class is a class that cannot be instantiated directly! * It widely used for defining interfaces. */ type AbstractClass<T extends object = any> = abstract new (...args: any[]) => T; /** * Service substitution allows you to register a class as a different class. * Providing class A, but using class B instead. * This is useful for testing, mocking, or providing a different implementation of a service. * * class A is mostly an AbstractClass, while class B is an InstantiableClass. */ interface ServiceSubstitution<T extends object = any> { /** * Every time someone asks for this class, it will be provided with the 'use' class. */ provide: Service<T>; /** * Service to use instead of the 'provide' service. * * Syntax is inspired by Angular's DI system. */ use: Service<T>; /** * If true, if the service already exists -> just ignore the substitution and do not throw an error. * Mostly used for plugins to enforce a substitution without throwing an error. */ optional?: boolean; } /** * Every time you register a service, you can use this type to define it. * * alepha.with( ServiceEntry ) * or * alepha.with( provide: ServiceEntry, use: MyOwnServiceEntry ) * * And yes, you declare the *type* of the service, not the *instance*. */ type ServiceEntry<T extends object = any> = Service<T> | ServiceSubstitution<T>; declare function isClass(func: any): func is InstantiableClass; //#endregion //#region src/helpers/descriptor.d.ts interface DescriptorArgs<T extends object = {}> { options: T; alepha: Alepha; service: InstantiableClass<Service>; module?: Service; } interface DescriptorConfig { propertyKey: string; service: InstantiableClass<Service>; module?: Service; } declare abstract class Descriptor<T extends object = {}> { protected readonly alepha: Alepha; readonly options: T; readonly config: DescriptorConfig; constructor(args: DescriptorArgs<T>); /** * Called automatically by Alepha after the descriptor is created. */ protected onInit(): void; } type DescriptorFactory<TDescriptor extends Descriptor = Descriptor> = { (options: TDescriptor["options"]): TDescriptor; [KIND]: InstantiableClass<TDescriptor>; }; type DescriptorFactoryLike<T extends object = any> = { (options: T): any; [KIND]: any; }; declare const createDescriptor: <TDescriptor extends Descriptor>(descriptor: InstantiableClass<TDescriptor> & { [MODULE]?: Service; }, options: TDescriptor["options"]) => TDescriptor; //#endregion //#region src/descriptors/$inject.d.ts /** * Get the instance of the specified type from the context. * * ```ts * class A { } * class B { * a = $inject(A); * } * ``` */ declare const $inject: <T extends object>(type: Service<T>, opts?: InjectOptions<T>) => T; declare class InjectDescriptor extends Descriptor {} interface InjectOptions<T extends object = any> { /** * - 'transient' → Always a new instance on every inject. Zero caching. * - 'singleton' → One instance per Alepha runtime (per-thread). Never disposed until Alepha shuts down. (default) * - 'scoped' → One instance per AsyncLocalStorage context. * - A new scope is created when Alepha handles a request, a scheduled job, a queue worker task... * - You can also start a manual scope via alepha.context.run(() => { ... }). * - When the scope ends, the scoped registry is discarded. * * @default "singleton" */ lifetime?: "transient" | "singleton" | "scoped"; /** * Constructor arguments to pass when creating a new instance. */ args?: ConstructorParameters<InstantiableClass<T>>; /** * Parent that requested the instance. * * @internal */ parent?: Service | null; } //#endregion //#region src/descriptors/$module.d.ts /** * Wrap Services and Descriptors into a Module. * * - A module is just a Service extended {@link Module}. * - You must attach a `name` to it. * - Name must follow the pattern: `project.module.submodule`. * * @example * ```ts * import { $module } from "alepha"; * import { MyService } from "./MyService.ts"; * * // export MyService, so it can be used everywhere * export * from "./MyService.ts"; * * export default $module({ * name: "my.project.module", * // MyService will have a module context "my.project.module" * services: [MyService], * }); * ``` * * ## Why Modules? * * ### Logging * * By default, AlephaLogger will log the module name in the logs. * This helps to identify where the logs are coming from. * * You can also set different log levels for different modules. * It means you can set 'some.very.specific.module' to 'debug' and keep the rest of the application to 'info'. * * ### Modulith * * Force to structure your application in modules, even if it's a single deployable unit. * It helps to keep a clean architecture and avoid monolithic applications. * * You can also use `MODULE_INCLUDE` and `MODULE_EXCLUDE` environment variables to load only specific modules. * * A strict mode is planned to enforce module boundaries. Throwing errors when a service from another module is injected. * * ### When not to use Modules? * * Small applications does not need modules. It's better to keep it simple. * Modules are more useful when the application grows and needs to be structured. * If we speak with `$actions`, a module should be used when you have more than 30 actions in a single module. */ declare const $module: <T extends object = {}>(options: ModuleDescriptorOptions<T>) => Service<Module<T>>; interface ModuleDescriptorOptions<T extends object> { /** * Name of the module. * * It should be in the format of `project.module.submodule`. */ name: string; /** * List of services to register in the module. */ services?: Array<Service>; /** * List of $descriptors to register in the module. */ descriptors?: Array<DescriptorFactoryLike>; /** * By default, module will register all services. * You can override this behavior by providing a register function. * It's useful when you want to register services conditionally or in a specific order. */ register?: (alepha: Alepha, options: T) => void; } /** * Base class for all modules. */ declare abstract class Module<T extends object = {}> { abstract readonly config: ModuleDescriptorOptions<T>; abstract register(alepha: Alepha): void; static NAME_REGEX: RegExp; options: T; /** * Check if a Service is a Module. */ static is(ctor: Service): boolean; /** * Get the Module of a Service. */ static of(ctor: Service): Service<Module> | undefined; } type WithModule<T extends object = any> = T & { [MODULE]?: Service; }; //#endregion //#region src/interfaces/Async.d.ts /** * Represents a value that can be either a value or a promise of value. */ type Async<T> = T | Promise<T>; /** * Represents a function that returns an async value. */ type AsyncFn = (...args: any[]) => Async<any>; /** * Transforms a type T into a promise if it is not already a promise. */ type MaybePromise<T> = T extends Promise<any> ? T : Promise<T>; //#endregion //#region src/interfaces/LoggerInterface.d.ts type LogLevel = "ERROR" | "WARN" | "INFO" | "DEBUG" | "TRACE" | "SILENT"; interface LoggerInterface { trace(message: string, data?: unknown): void; debug(message: string, data?: unknown): void; info(message: string, data?: unknown): void; warn(message: string, data?: unknown): void; error(message: string, data?: unknown): void; } //#endregion //#region src/providers/AlsProvider.d.ts type AsyncLocalStorageData = any; declare class AlsProvider { static create: () => AsyncLocalStorage<AsyncLocalStorageData> | undefined; als?: AsyncLocalStorage<AsyncLocalStorageData>; constructor(); createContextId(): string; run<R>(callback: () => R, data?: Record<string, any>): R; exists(): boolean; get<T>(key: string): T | undefined; set<T>(key: string, value: T): void; } //#endregion //#region src/providers/Json.d.ts /** * Mimics the JSON global object with stringify and parse methods. * * Used across the codebase via dependency injection. */ declare class Json { stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string; parse(text: string, reviver?: (this: any, key: string, value: any) => any): any; } //#endregion //#region src/errors/AlephaError.d.ts /** * Default error class for Alepha. */ declare class AlephaError extends Error { name: string; } //#endregion //#region src/errors/TypeBoxError.d.ts declare class TypeBoxError extends AlephaError { readonly name = "TypeBoxError"; readonly cause: TLocalizedValidationError; readonly value: { path: string; message: string; }; constructor(error: TLocalizedValidationError); } interface TypeBoxErrorParams { requiredProperties?: string[]; } //#endregion //#region src/helpers/FileLike.d.ts interface FileLike { /** * Filename. * @default "file" */ name: string; /** * Mandatory MIME type of the file. * @default "application/octet-stream" */ type: string; /** * Size of the file in bytes. * * Always 0 for streams, as the size is not known until the stream is fully read. * * @default 0 */ size: number; /** * Last modified timestamp in milliseconds since epoch. * * Always the current timestamp for streams, as the last modified time is not known. * We use this field to ensure compatibility with File API. * * @default Date.now() */ lastModified: number; /** * Returns a ReadableStream or Node.js Readable stream of the file content. * * For streams, this is the original stream. */ stream(): StreamLike; /** * Returns the file content as an ArrayBuffer. * * For streams, this reads the entire stream into memory. */ arrayBuffer(): Promise<ArrayBuffer>; /** * Returns the file content as a string. * * For streams, this reads the entire stream into memory and converts it to a string. */ text(): Promise<string>; /** * Optional file path, if the file is stored on disk. * * This is not from the File API, but rather a custom field to indicate where the file is stored. */ filepath?: string; } /** * TypeBox view of FileLike. */ type TFile = TUnsafe$1<FileLike>; declare const isTypeFile: (value: TSchema$1) => value is TFile; declare const isFileLike: (value: any) => value is FileLike; type StreamLike = ReadableStream | ReadableStream$1 | Readable | NodeJS.ReadableStream; type TStream = TUnsafe$1<StreamLike>; //#endregion //#region src/providers/TypeProvider.d.ts declare const isUUID: typeof TypeBoxFormat.IsUuid; declare const isEmail: typeof TypeBoxFormat.IsEmail; declare const isURL: typeof TypeBoxFormat.IsUrl; declare class TypeGuard { isFile: (value: TSchema$1) => value is TFile; isBigInt: (value: TSchema$1) => value is TString$1; isUUID: (value: TSchema$1) => value is TString$1; isObject: typeof TypeBox.IsObject; isNumber: typeof TypeBox.IsNumber; isString: typeof TypeBox.IsString; isBoolean: typeof TypeBox.IsBoolean; isAny: typeof TypeBox.IsAny; isArray: typeof TypeBox.IsArray; isOptional: typeof TypeBox.IsOptional; isUnion: typeof TypeBox.IsUnion; isInteger: typeof TypeBox.IsInteger; isNull: typeof TypeBox.IsNull; isUndefined: typeof TypeBox.IsUndefined; isUnsafe: typeof TypeBox.IsUnsafe; isRecord: typeof TypeBox.IsRecord; isTuple: typeof TypeBox.IsTuple; isVoid: typeof TypeBox.IsVoid; isLiteral: typeof TypeBox.IsLiteral; isSchema: typeof TypeBox.IsSchema; } declare module "typebox" { interface TString { format?: string; minLength?: number; maxLength?: number; } interface TNumber { format?: "int64"; } } declare class TypeProvider { static format: typeof TypeBoxFormat; static translateError(error: TypeBoxError, locale?: string): string; static setLocale(locale: string): void; static isValidBigInt(value: string | number): boolean; /** * Default maximum length for strings. * * It can be set to a larger value: * ```ts * TypeProvider.DEFAULT_STRING_MAX_LENGTH = 1000000; * TypeProvider.DEFAULT_STRING_MAX_LENGTH = undefined; // no limit (not recommended) * ``` */ static DEFAULT_STRING_MAX_LENGTH: number | undefined; /** * Maximum length for short strings, such as names or titles. */ static DEFAULT_SHORT_STRING_MAX_LENGTH: number | undefined; /** * Maximum length for long strings, such as descriptions or comments. * It can be overridden in the string options. * * It can be set to a larger value: * ```ts * TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH = 2048; * ``` */ static DEFAULT_LONG_STRING_MAX_LENGTH: number | undefined; /** * Maximum length for rich strings, such as HTML or Markdown. * This is a large value to accommodate rich text content. * > It's also the maximum length of PG's TEXT type. * * It can be overridden in the string options. * * It can be set to a larger value: * ```ts * TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH = 1000000; * ``` */ static DEFAULT_RICH_STRING_MAX_LENGTH: number | undefined; /** * Maximum number of items in an array. * This is a default value to prevent excessive memory usage. * It can be overridden in the array options. */ static DEFAULT_ARRAY_MAX_ITEMS: number; raw: typeof TypeBox.Type; any: typeof TypeBox.Any; void: typeof TypeBox.Void; undefined: typeof TypeBox.Undefined; record: typeof TypeBox.Record; partial: typeof TypeBox.Partial; union: typeof TypeBox.Union; tuple: typeof TypeBox.Tuple; interface: typeof TypeBox.Interface; null: typeof TypeBox.Null; const: typeof TypeBox.Literal; codec: typeof TypeBox.Codec; /** * Type guards to check the type of schema. * This is not a runtime type check, but a compile-time type guard. * * @example * ```ts * if (t.schema.isString(schema)) { * // schema is TString * } * ``` */ readonly schema: TypeGuard; pick<T extends TObject$1, Indexer extends PropertyKey[]>(schema: T, keys: [...Indexer], options?: TObjectOptions$1): TPick$1<T, TKeysToIndexer$1<Indexer>>; omit<T extends TObject$1, Indexer extends PropertyKey[]>(schema: T, keys: [...Indexer], options?: TObjectOptions$1): TOmit<T, TKeysToIndexer$1<Indexer>>; /** * Create a schema for an object. * By default, additional properties are not allowed. * * @example * ```ts * const userSchema = t.object({ * id: t.int(), * name: t.string(), * }); * ``` */ object<T extends TProperties$1>(properties: T, options?: TObjectOptions$1): TObject$1<T>; /** * Create a schema for an array. * By default, the maximum number of items is limited to prevent excessive memory usage. * * @see TypeProvider.DEFAULT_ARRAY_MAX_ITEMS */ array<T extends TSchema$1>(schema: T, options?: TArrayOptions): TArray$1<T>; /** * Create a schema for a string. * For db or input fields, consider using `t.text()` instead, which has length limits. * * If you need a string with specific format (e.g. email, uuid), consider using the corresponding method (e.g. `t.email()`, `t.uuid()`). */ string(options?: TStringOptions$1): TString$1; /** * Create a schema for a string with length limits. * For internal strings without length limits, consider using `t.string()` instead. * * Default size is "regular", which has a max length of 255 characters. */ text(options?: TTextOptions): TString$1; /** * Create a schema for a JSON object. * This is a record with string keys and any values. */ json(options?: TSchemaOptions): TRecord$1<string, TAny$1>; /** * Create a schema for a boolean. */ boolean(options?: TSchemaOptions): TBoolean$1; /** * Create a schema for a number. */ number(options?: TNumberOptions$1): TNumber$1; /** * Create a schema for a signed 32-bit integer. */ int(options?: TNumberOptions$1): TInteger$1; /** * @alias `t.int()` */ integer(options?: TNumberOptions$1): TInteger$1; /** * Mimic a signed 64-bit integer. * * This is NOT a true int64, as JavaScript cannot represent all int64 values. * It is a number that is an integer and between -9007199254740991 and 9007199254740991. * Use `t.bigint()` for true int64 values represented as strings. */ int64(options?: TNumberOptions$1): TNumber$1; /** * Make a schema optional. */ optional<T extends TSchema$1>(schema: T): TOptionalAdd$1<T>; /** * Make a schema nullable. */ nullable<T extends TSchema$1>(schema: T, options?: TObjectOptions$1): TUnion$1<[TNull$1, T]>; /** * Create a schema that maps all properties of an object schema to nullable. */ nullify: <T extends TSchema$1>(schema: T, options?: TObjectOptions$1) => TypeBox.TMappedInstantiate<{}, { callstack: []; }, TypeBox.TIdentifier<"K">, TypeBox.TKeyOfInstantiate<{}, { callstack: []; }, T>, TypeBox.TRef<"K">, TUnion$1<[TypeBox.TIndexInstantiate<{}, { callstack: []; }, T, TypeBox.TRef<"K">>, TNull$1]>>; /** * Create a schema for a string enum. */ enum<T extends string[]>(values: [...T], options?: TStringOptions$1): TUnsafe$1<T[number]>; /** * Create a schema for a bigint. * This is NOT a BigInt object, but a string that represents a bigint. */ bigint(options?: TStringOptions$1): TypeBox.TCodec<TString$1, bigint>; /** * Create a schema for a url. */ url(options?: TStringOptions$1): TypeBox.TCodec<TString$1, URL>; /** * Create a schema for binary data represented as a string. */ binary(options: TStringOptions$1): TypeBox.TCodec<TString$1, Uint8Array<ArrayBuffer>>; /** * Create a schema for uuid. */ uuid(options?: TStringOptions$1): TString$1; /** * Create a schema for a file-like object. * * File like mimics the File API in browsers, but is adapted to work in Node.js as well. * * Implementation of file-like objects is handled by "alepha/file" package. */ file(options?: { maxSize?: number; }): TFile; /** * @experimental */ stream(): TStream; email(options?: TStringOptions$1): TString$1; e164(options?: TStringOptions$1): TString$1; bcp47(options?: TStringOptions$1): TString$1; /** * Create a schema for short text, such as names or titles. * Default max length is 64 characters. */ shortText(options?: TStringOptions$1): TString$1; /** * Create a schema for long text, such as descriptions or comments. * Default max length is 1024 characters. */ longText(options?: TStringOptions$1): TString$1; /** * Create a schema for rich text, such as HTML or Markdown. * Default max length is 65535 characters. */ richText(options?: TStringOptions$1): TString$1; /** * Create a schema for a string enum e.g. LIKE_THIS. */ snakeCase: (options?: TStringOptions$1) => TString$1; /** * Create a schema for an object with a value and label. */ valueLabel: (options?: TObjectOptions$1) => TObject$1<{ value: TString$1; label: TString$1; description: TypeBox.TOptional<TString$1>; }>; } type TextLength = "short" | "regular" | "long" | "rich"; interface TTextOptions extends TStringOptions$1 { /** * Predefined size of the text. * * - `short` - short text, such as names or titles. Default max length is 64 characters. * - `regular` - regular text, such as single-line input. Default max length is 255 characters. * - `long` - long text, such as descriptions or comments. Default max length is 1024 characters. * - `rich` - rich text, such as HTML or Markdown. Default max length is 65535 characters. * * You can override the default max length by specifying `maxLength` in the options. * * @default "regular" */ size?: TextLength; /** * Trim whitespace from both ends of the string. * * @default true */ trim?: boolean; } declare const t: TypeProvider; //#endregion //#region src/providers/SchemaCodec.d.ts declare abstract class SchemaCodec { protected cache: Map<TSchema$1, Validator>; protected guard: TypeGuard; /** * Encode the value to a string format. */ abstract encodeToString(schema: TSchema$1, value: any): string; /** * Encode the value to a binary format. */ abstract encodeToBinary(schema: TSchema$1, value: any): Uint8Array; /** * Transform a specific type for this codec. * Return undefined to use the default schema, or return a new schema to replace it. * * Override this method to customize how specific types are handled in this codec. * For example, a ProtobufCodec might keep BigInt as-is instead of converting to string. */ protected abstract transformType(schema: TSchema$1): TSchema$1 | false | void; encode<T extends TSchema$1>(schema: T, value: any): StaticEncode$1<T>; decode<T extends TSchema$1>(schema: T, value: any): StaticDecode$1<T>; protected validator<T extends TSchema$1>(schema: T): Validator<{}, T>; /** * Transform the schema for this codec. * Override this method to provide custom schema transformations. * This method should recursively transform all nested schemas. */ protected transformSchema<T extends TSchema$1>(schema: T): TSchema$1; /** * Preprocess the value based on the schema before encoding. * * - Remove `undefined` values from objects. { a: 1, b: undefined } => { a: 1 } */ beforeEncode: (schema: any, value: any) => any; /** * Preprocess the value based on the schema before validation. * * - If the value is `null` and the schema does not allow `null`, it converts it to `undefined`. * - If the value is a string and the schema has a `~options.trim` flag, it trims whitespace from the string. */ beforeDecode: (schema: any, value: any) => any; /** * Used by `preprocess` to determine if a schema allows null values. */ protected isSchemaNullable: (schema: any) => boolean; } //#endregion //#region src/providers/JsonSchemaCodec.d.ts declare class JsonSchemaCodec extends SchemaCodec { protected readonly json: Json; protected readonly encoder: TextEncoder; protected readonly decoder: TextDecoder; protected transformType(schema: TSchema$1): TSchema$1 | false | void; encodeToString(schema: TSchema$1, value: any): string; encodeToBinary(schema: TSchema$1, value: any): Uint8Array; decode<T extends TSchema$1>(schema: T, value: any): StaticDecode$1<T>; } //#endregion //#region src/providers/CodecManager.d.ts type Encoding = "object" | "string" | "binary"; interface EncodeOptions<T extends Encoding = Encoding> { /** * The output encoding format: * - 'object': Returns native types (objects, BigInt, Date, etc.) * - 'string': Returns JSON string * - 'binary': Returns Uint8Array (for protobuf, msgpack, etc.) */ as?: T; /** * The encoder to use (e.g., 'json', 'protobuf', 'msgpack') * Defaults to 'json' */ encoder?: string; } type EncodeResult<T extends TSchema$1, E extends Encoding> = E extends "string" ? string : E extends "binary" ? Uint8Array : StaticEncode$1<T>; interface DecodeOptions { /** * The encoder to use (e.g., 'json', 'protobuf', 'msgpack') * Defaults to 'json' */ encoder?: string; } /** * CodecManager manages multiple codec formats and provides a unified interface * for encoding and decoding data with different formats. */ declare class CodecManager { protected readonly codecs: Map<string, SchemaCodec>; protected readonly jsonCodec: JsonSchemaCodec; default: string; constructor(); /** * Register a new codec format. * @param name - The name of the codec (e.g., 'json', 'protobuf') * @param codec - The codec implementation */ register(name: string, codec: SchemaCodec): void; /** * Get a specific codec by name. * @param name - The name of the codec * @returns The codec instance * @throws {AlephaError} If the codec is not found */ get(name: string): SchemaCodec; /** * Encode data using the specified codec and output format. */ encode<T extends TSchema$1, E extends Encoding = "object">(schema: T, value: any, options?: EncodeOptions<E>): EncodeResult<T, E>; /** * Decode data using the specified codec. */ decode<T extends TSchema$1>(schema: T, value: any, options?: DecodeOptions): StaticDecode$1<T>; } //#endregion //#region src/providers/EventManager.d.ts declare class EventManager { protected logFn?: () => LoggerInterface | undefined; /** * List of events that can be triggered. Powered by $hook(). */ protected events: Record<string, Array<Hook>>; constructor(logFn?: () => LoggerInterface | undefined); protected get log(): LoggerInterface | undefined; /** * Registers a hook for the specified event. */ on<T extends keyof Hooks>(event: T, hookOrFunc: Hook<T> | ((payload: Hooks[T]) => Async<void>)): () => void; /** * Emits the specified event with the given payload. */ emit<T extends keyof Hooks>(func: T, payload: Hooks[T], options?: { /** * If true, the hooks will be executed in reverse order. * This is useful for "stop" hooks that should be executed in reverse order. * * @default false */ reverse?: boolean; /** * If true, the hooks will be logged with their execution time. * * @default false */ log?: boolean; /** * If true, errors will be caught and logged instead of throwing. * * @default false */ catch?: boolean; }): Promise<void>; } //#endregion //#region src/providers/StateManager.d.ts declare class StateManager<S extends Record<string, any> = State> { protected readonly als: AlsProvider; protected readonly events: EventManager; protected store: Partial<S>; constructor(store?: Partial<S>); /** * Get a value from the state with proper typing */ get<Key extends keyof S>(key: Key): S[Key] | undefined; /** * Set a value in the state */ set<Key extends keyof S>(key: Key, value: S[Key] | undefined): this; /** * Check if a key exists in the state */ has<Key extends keyof S>(key: Key): boolean; /** * Delete a key from the state (set to undefined) */ del<Key extends keyof S>(key: Key): this; /** * Clear all state */ clear(): this; /** * Get all keys that exist in the state */ keys(): (keyof S)[]; } //#endregion //#region src/Alepha.d.ts /** * Core container of the Alepha framework. * * It is responsible for managing the lifecycle of services, * handling dependency injection, * and providing a unified interface for the application. * * @example * ```ts * import { Alepha, run } from "alepha"; * * class MyService { * // business logic here * } * * const alepha = Alepha.create({ * // state, env, and other properties * }) * * alepha.with(MyService); * * run(alepha); // trigger .start (and .stop) automatically * ``` * * ### Alepha Factory * * Alepha.create() is an enhanced version of new Alepha(). * - It merges `process.env` with the provided state.env when available. * - It populates the test hooks for Vitest or Jest environments when available. * * new Alepha() is fine if you don't need these helpers. * * ### Platforms & Environments * * Alepha is designed to work in various environments: * - **Browser**: Runs in the browser, using the global `window` object. * - **Serverless**: Runs in serverless environments like Vercel or Vite. * - **Test**: Runs in test environments like Jest or Vitest. * - **Production**: Runs in production environments, typically with NODE_ENV set to "production". * * You can check the current environment using the following methods: * * - `isBrowser()`: Returns true if the App is running in a browser environment. * - `isServerless()`: Returns true if the App is running in a serverless environment. * - `isTest()`: Returns true if the App is running in a test environment. * - `isProduction()`: Returns true if the App is running in a production environment. * * ### State & Environment * * The state of the Alepha container is stored in the `store` property. * Most important property is `store.env`, which contains the environment variables. * * ```ts * const alepha = Alepha.create({ env: { MY_VAR: "value" } }); * * // You can access the environment variables using alepha.env * console.log(alepha.env.MY_VAR); // "value" * * // But you should use $env() descriptor to get typed values from the environment. * class App { * env = $env( * t.object({ * MY_VAR: t.text(), * }) * ); * } * ``` * * ### Modules * * Modules are a way to group services together. * You can register a module using the `$module` descriptor. * * ```ts * import { $module } from "alepha"; * * class MyLib {} * * const myModule = $module({ * name: "my.project.module", * services: [MyLib], * }); * ``` * * Do not use modules for small applications. * * ### Hooks * * Hooks are a way to run async functions from all registered providers/services. * You can register a hook using the `$hook` descriptor. * * ```ts * import { $hook } from "alepha"; * * class App { * log = $logger(); * onCustomerHook = $hook({ * on: "my:custom:hook", * handler: () => { * this.log?.info("App is being configured"); * }, * }); * } * * Alepha.create() * .with(App) * .start() * .then(alepha => alepha.events.emit("my:custom:hook")); * ``` * * Hooks are fully typed. You can create your own hooks by using module augmentation: * * ```ts * declare module "alepha" { * interface Hooks { * "my:custom:hook": { * arg1: string; * } * } * } * ``` * * @module alepha */ declare class Alepha { /** * Creates a new instance of the Alepha container with some helpers: * * - merges `process.env` with the provided state.env when available. * - populates the test hooks for Vitest or Jest environments when available. * * If you are not interested about these helpers, you can use the constructor directly. */ static create(state?: Partial<State>): Alepha; /** * Flag indicating whether the App won't accept any further changes. * Pass to true when #start() is called. */ protected locked: boolean; /** * True if the App has been configured. */ protected configured: boolean; /** * True if the App has started. */ protected started: boolean; /** * True if the App is ready. */ protected ready: boolean; /** * A promise that resolves when the App has started. */ protected starting?: PromiseWithResolvers<this>; /** * Initial state of the container. * * > Used to initialize the StateManager. */ protected init: State; /** * During the instantiation process, we keep a list of pending instantiations. * > It allows us to detect circular dependencies. */ protected pendingInstantiations: Service[]; /** * Cache for environment variables. * > It allows us to avoid parsing the same schema multiple times. */ protected cacheEnv: Map<TSchema, any>; /** * List of modules that are registered in the container. * * Modules are used to group services and provide a way to register them in the container. */ protected modules: Array<Module>; /** * List of service substitutions. * * Services registered here will be replaced by the specified service when injected. */ protected substitutions: Map<Service, { use: Service; }>; /** * Configuration states for services. * * Used to configure services when they are instantiated. */ protected configurations: Map<Service, object>; /** * Registry of descriptors. */ protected descriptorRegistry: Map<Service<Descriptor<{}>>, Descriptor<{}>[]>; /** * List of all services + how they are provided. */ protected registry: Map<Service, ServiceDefinition>; /** * Node.js feature that allows to store context across asynchronous calls. * * This is used for logging, tracing, and other context-related features. * * Mocked for browser environments. */ get context(): AlsProvider; /** * Event manager to handle lifecycle events and custom events. */ get events(): EventManager; /** * State manager to store arbitrary values. */ get state(): StateManager<Record<string, any>>; /** * Codec manager for encoding and decoding data with different formats. * * Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface. */ get codec(): CodecManager; /** * Get logger instance. */ get log(): LoggerInterface | undefined; /** * The environment variables for the App. */ get env(): Readonly<Env>; constructor(init?: Partial<State>); /** * True when start() is called. * * -> No more services can be added, it's over, bye! */ isLocked(): boolean; /** * Returns whether the App is configured. * * It means that Alepha#configure() has been called. * * > By default, configure() is called automatically when start() is called, but you can also call it manually. */ isConfigured(): boolean; /** * Returns whether the App has started. * * It means that #start() has been called but maybe not all services are ready. */ isStarted(): boolean; /** * True if the App is ready. It means that Alepha is started AND ready() hook has beed called. */ isReady(): boolean; /** * True if the App is running in a browser environment. */ isBrowser(): boolean; /** * Returns whether the App is running in Vite dev mode. */ isViteDev(): boolean; /** * Returns whether the App is running in a serverless environment. */ isServerless(): boolean; /** * Returns whether the App is in test mode. (Running in a test environment) * * > This is automatically set when running tests with Jest or Vitest. */ isTest(): boolean; /** * Returns whether the App is in production mode. (Running in a production environment) * * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps. */ isProduction(): boolean; /** * Starts the App. * * - Lock any further changes to the container. * - Run "configure" hook for all services. Descriptors will be processed. * - Run "start" hook for all services. Providers will connect/listen/... * - Run "ready" hook for all services. This is the point where the App is ready to serve requests. * * @return A promise that resolves when the App has started. */ start(): Promise<this>; /** * Stops the App. * * - Run "stop" hook for all services. * * Stop will NOT reset the container. * Stop will NOT unlock the container. * * > Stop is used to gracefully shut down the application, nothing more. There is no "restart". * * @return A promise that resolves when the App has stopped. */ stop(): Promise<void>; /** * Check if entry is registered in the container. */ has(entry: ServiceEntry, opts?: { /** * Check if the entry is registered in the pending instantiation stack. * * @default true */ inStack?: boolean; /** * Check if the entry is registered in the container registry. * * @default true */ inRegistry?: boolean; /** * Check if the entry is registered in the substitutions. * * @default true */ inSubstitutions?: boolean; /** * Where to look for registered services. * * @default this.registry */ registry?: Map<Service, ServiceDefinition>; }): boolean; /** * Registers the specified service in the container. * * - If the service is ALREADY registered, the method does nothing. * - If the service is NOT registered, a new instance is created and registered. * * Method is chainable, so you can register multiple services in a single call. * * > ServiceEntry allows to provide a service **substitution** feature. * * @example * ```ts * class A { value = "a"; } * class B { value = "b"; } * class M { a = $inject(A); } * * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b" * ``` * * > **Substitution** is an advanced feature that allows you to replace a service with another service. * > It's useful for testing or for providing different implementations of a service. * > If you are interested in configuring a service, use Alepha#configure() instead. * * @param serviceEntry - The service to register in the container. * @param configure - Optional configuration object to merge with the service's options. * @return Current instance of Alepha. */ with<T extends { options?: object; } & object>(serviceEntry: ServiceEntry<T> | { default: ServiceEntry<T>; }, configure?: Partial<T["options"]>): this; /** * Get an instance of the specified service from the container. * * @see {@link InjectOptions} for the available options. */ inject<T extends object>(service: Service<T>, opts?: InjectOptions<T>): T; /** * Configures the specified service with the provided state. * If service is not registered, it will do nothing. * * It's recommended to use this method on the `configure` hook. * @example * ```ts * class AppConfig { * configure = $hook({ * name: "configure", * handler: (a) => { * a.configure(MyProvider, { some: "data" }); * } * }) * } * ``` */ configure<T extends { options?: object; }>(service: Service<T>, state: Partial<T["options"]>): this; /** * Applies environment variables to the provided schema and state object. * * It replaces also all templated $ENV inside string values. * * @param schema - The schema object to apply environment variables to. * @return The schema object with environment variables applied. */ parseEnv<T extends TObject$1>(schema: T): Static$1<T>; /** * Dump the current dependency graph of the App. * * This method returns a record where the keys are the names of the services. */ graph(): Record<string, { from: string[]; as?: string[]; module?: string; }>; descriptors<TDescriptor extends Descriptor>(factory: { [KIND]: InstantiableClass<TDescriptor>; } | string): Array<TDescriptor>; protected new<T extends object>(service: Service<T>, args?: any[]): T; protected processDescriptor(value: Descriptor, propertyKey?: string): void; } interface Hook<T extends keyof Hooks = any> { caller?: Service; priority?: "first" | "last"; callback: (payload: Hooks[T]) => Async<void>; } /** * This is how we store services in the Alepha container. */ interface ServiceDefinition<T extends object = any> { /** * The instance of the class or type definition. * Mostly used for caching / singleton but can be used for other purposes like forcing the instance. */ instance: T; /** * List of classes which use this class. */ parents: Array<Service | null>; } interface Env { [key: string]: string | boolean | number | undefined; /** * Optional environment variable that indicates the current environment. */ NODE_ENV?: "dev" | "test" | "production"; /** * Optional name of the application. */ APP_NAME?: string; /** * Optional root module name. */ MODULE_NAME?: string; } interface State { log?: LoggerInterface; env?: Readonly<Env>; /** * If defined, the Alepha container will only register this service and its dependencies. */ target?: Service; beforeAll?: (run: any) => any; afterAll?: (run: any) => any; afterEach?: (run: any) => any; onTestFinished?: (run: any) => any; } interface Hooks { echo: any; /** * Triggered during the configuration phase. Before the start phase. */ configure: Alepha; /** * Triggered during the start phase. When `Alepha#start()` is called. */ start: Alepha; /** * Triggered during the ready phase. After the start phase. */ ready: Alepha; /** * Triggered during the stop phase. * * - Stop should be called after a SIGINT or SIGTERM signal in order to gracefully shutdown the application. (@see `run()` method) * */ stop: Alepha; /** * Triggered when a state value is mutated. */ "state:mutate": { /** * The key of the state that was mutated. */ key: keyof State; /** * The new value of the state. */ value: any; /** * The previous value of the state. */ prevValue: any; }; } interface Configurable<T extends object = any> { options: T; } //#endregion //#region src/interfaces/Run.d.ts interface RunOptions { /** * Environment variables to be used by the application. * It will be merged with the current process environment. */ env?: Env; /** * A callback that will be executed before the application starts. */ configure?: (alepha: Alepha) => Async<void>; /** * A callback that will be executed once the application is ready. * This is useful for initializing resources or starting background tasks. */ ready?: (alepha: Alepha) => Async<void>; /** * If true, the application will .stop() after the ready callback is executed. * Useful for one-time tasks! */ once?: boolean; /** * If true, the application will run in cluster mode. */ cluster?: boolean; } //#endregion //#region src/constants/OPTIONS.d.ts /** * Used for descriptors options. * * @internal */ declare const OPTIONS: unique symbol; //#endregion //#region src/descriptors/$cursor.d.ts /** * Get Alepha instance and Class definition from the current context. * This should be used inside a descriptor only. * * ```ts * import { $cursor } from "alepha"; * * const $ = () => { * * const { context, definition } = $cursor(); * * // context - alepha instance * // definition - class which is creating this descriptor * * return {}; * } * * ``` * * @internal */ declare const $cursor: () => CursorDescriptor; /** * /!\ Global variable /!\ * * Store the current context and definition during injection phase. * * @internal */ declare const __alephaRef: { context?: Alepha; definition?: Service & { [MODULE]?: Service; }; parent?: Service; }; /** * Cursor descriptor. */ interface CursorDescriptor { context: Alepha; definition?: Service; module?: Service; } //#endregion //#region src/descriptors/$env.d.ts /** * Get typed values from environment variables. * * @example * ```ts * const alepha = Alepha.create({ * env: { * // Alepha.create() will also use process.env when running on Node.js * HELLO: "world", * } * }); * * class App { * log = $logger(); * * // program expect a var env "HELLO" as string to works * env = $env(t.object({ * HELLO: t.text() * })); * * sayHello = () => this.log.info("Hello ${this.env.HELLO}") * } * * run(alepha.with(App)); * ``` */ declare const $env: <T extends TObject$1>(type: T) => Static$1<T>; //#endregion //#region src/descriptors/$hook.d.ts /** * Registers a new hook. * * ```ts * import { $hook } from "alepha"; * * class MyProvider { * onStart = $hook({ * name: "start", // or "configure", "ready", "stop", ... * handler: async (app) => { * // await db.connect(); ... * } * }); * } * ``` * * Hooks are used to run async functions from all registered providers/services. * * You can't register a hook after the App has started. * * It's used under the hood by the `configure`, `start`, and `stop` methods. * Some modules also use hooks to run their own logic. (e.g. `@alepha/server`). * * You can create your own hooks by using module augmentation: * * ```ts * declare module "alepha" { * * interface Hooks { * "my:custom:hook": { * arg1: string; * } * } * } * * await alepha.events.emit("my:custom:hook", { arg1: "value" }); * ``` * */ declare const $hook: { <T extends keyof Hooks>(options: HookOptions<T>): HookDescriptor<T>; [KIND]: typeof HookDescriptor; }; interface HookOptions<T extends keyof Hooks> { /** * The name of the hook. "configure", "start", "ready", "stop", ... */ on: T; /** * The handler to run when the hook is triggered. */ handler: (args: Hooks[T]) => Async<any>; /** * Force the hook to run first or last on the list of hooks. */ priority?: "first" | "last"; /** * Empty placeholder, not implemented yet. :-) */ before?: object | Array<object>; /** * Empty placeholder, not implemented yet. :-) */ after?: object | Array<object>; } declare class HookDescriptor<T extends keyof Hooks> extends Descriptor<HookOptions<T>> { called: number; protected onInit(): void; } //#endregion //#region src/errors/AppNotStartedError.d.ts declare class AppNotStartedError extends AlephaError { readonly name = "AppNotStartedError"; constructor(); } //#endregion //#region src/errors/CircularDependencyError.d.ts declare class CircularDependencyError extends AlephaError { readonly name = "CircularDependencyError"; constructor(provider: string, parents?: string[]); } //#endregion //#region src/errors/ContainerLockedError.d.ts declare class ContainerLockedError extends AlephaError { readonly name = "ContainerLockedError"; constructor(message?: string); } //#endregion //#region src/errors/TooLateSubstitutionError.d.ts declare class TooLateSubstitutionError extends AlephaError { readonly name = "TooLateSubstitutionError"; constructor(original: string, substitution: string); } //#endregion //#region src/index.d.ts /** * Run Alepha application, trigger start lifecycle. * * ```ts * import { Alepha, run } from "alepha"; * import { MyService } from "./services/MyService.ts"; * * const alepha = new Alepha({ env: { APP_NAME: "MyAlephaApp" } }); * * alepha.with(MyService); * * export default run(alepha); * ``` */ declare const run: (entry: Alepha | Service | Array<Service>, opts?: RunOptions) => Alepha; //#endregion export { $cursor, $env, $hook, $inject, $module, AbstractClass, Alepha, AlephaError, AlsProvider, AppNotStartedError, Async, AsyncFn, AsyncLocalStorageData, CircularDependencyError, CodecManager, Configurable, ContainerLockedError, CursorDescriptor, DecodeOptions, Descriptor, DescriptorArgs, DescriptorConfig, DescriptorFactory, DescriptorFactoryLike, EncodeOptions, EncodeResult, Encoding, Env, FileLike, Hook, HookDescriptor, HookOptions, Hooks, InjectDescriptor, InjectOptions, InstantiableClass, JsonSchemaCodec, KIND, LogLevel, LoggerInterface, MaybePromise, Module, ModuleDescriptorOptions, OPTIONS, RunFunction, SchemaCodec, Service, ServiceEntry, ServiceSubstitution, State, StateManager, type Static, type StaticDecode, type StaticEncode, StreamLike, type TAny, type TArray, type TBigInt, type TBoolean, TFile, type TInteger, type TKeysToIndexer, type TNull, type TNumber, type TNumberOptions, type TObject, type TObjectOptions, type TOptional, type TOptionalAdd, type TPick, type TProperties, type TRecord, type TSchema, TStream, type TString, type TStringOptions, TTextOptions, type TTuple, type TUnion, type TUnsafe, type TVoid, TextLength, TooLateSubstitutionError, TypeBox, TypeBoxError, TypeBoxErrorParams, TypeBoxFormat, TypeBoxValue, TypeGuard, TypeProvider, WithModule, __alephaRef, createDescriptor, isClass, isEmail, isFileLike, isTypeFile, isURL, isUUID, run, t }; //# sourceMappingURL=index.d.ts.map