{"version":3,"sources":["jsdelivr-header.js","/npm/alepha@0.18.2/src/core/constants/KIND.ts","/npm/alepha@0.18.2/src/core/constants/MODULE.ts","/npm/alepha@0.18.2/src/core/constants/OPTIONS.ts","/npm/alepha@0.18.2/src/core/errors/AlephaError.ts","/npm/alepha@0.18.2/src/core/errors/CircularDependencyError.ts","/npm/alepha@0.18.2/src/core/errors/ContainerLockedError.ts","/npm/alepha@0.18.2/src/core/errors/TooLateSubstitutionError.ts","/npm/alepha@0.18.2/src/core/errors/MissingContextError.ts","/npm/alepha@0.18.2/src/core/helpers/ref.ts","/npm/alepha@0.18.2/src/core/primitives/$context.ts","/npm/alepha@0.18.2/src/core/helpers/primitive.ts","/npm/alepha@0.18.2/src/core/interfaces/Service.ts","/npm/alepha@0.18.2/src/core/primitives/$module.ts","/npm/alepha@0.18.2/src/core/providers/AlsProvider.ts","/npm/alepha@0.18.2/src/core/primitives/$inject.ts","/npm/alepha@0.18.2/src/core/providers/Json.ts","/npm/alepha@0.18.2/src/core/providers/SchemaCodec.ts","/npm/alepha@0.18.2/src/core/providers/JsonSchemaCodec.ts","/npm/alepha@0.18.2/src/core/primitives/$hook.ts","/npm/alepha@0.18.2/src/core/helpers/FileLike.ts","/npm/alepha@0.18.2/src/core/providers/TypeProvider.ts","/npm/alepha@0.18.2/src/core/providers/KeylessJsonSchemaCodec.ts","/npm/alepha@0.18.2/src/core/errors/TypeBoxError.ts","/npm/alepha@0.18.2/src/core/providers/SchemaValidator.ts","/npm/alepha@0.18.2/src/core/providers/CodecManager.ts","/npm/alepha@0.18.2/src/core/providers/EventManager.ts","/npm/alepha@0.18.2/src/core/primitives/$atom.ts","/npm/alepha@0.18.2/src/core/providers/StateManager.ts","/npm/alepha@0.18.2/src/core/Alepha.ts","/npm/alepha@0.18.2/src/core/errors/AppNotStartedError.ts","/npm/alepha@0.18.2/src/core/helpers/createPagination.ts","/npm/alepha@0.18.2/src/core/helpers/jsonSchemaToTypeBox.ts","/npm/alepha@0.18.2/src/core/primitives/$env.ts","/npm/alepha@0.18.2/src/core/primitives/$memoize.ts","/npm/alepha@0.18.2/src/core/primitives/$mode.ts","/npm/alepha@0.18.2/src/core/primitives/$pipeline.ts","/npm/alepha@0.18.2/src/core/primitives/$scope.ts","/npm/alepha@0.18.2/src/core/primitives/$use.ts","/npm/alepha@0.18.2/src/core/schemas/pageQuerySchema.ts","/npm/alepha@0.18.2/src/core/schemas/pageSchema.ts","/npm/alepha@0.18.2/src/core/index.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,kVCDA,MAAa,KAAsB,OAAO,IAAI,eCAjC,OAAwB,OAAO,IAAI,iBCAnC,QAAyB,OAAO,IAAI,kBCAjD,IAAa,YAAb,cAAiC,MAC/B,KAAO,eCJI,wBAAb,cAA6C,YAC3C,KAAgB,0BAEhB,WAAA,CAAY,EAAkB,GAC5B,MACE,kEAAkE,GAAS,KAAK,GAAS,GAAG,UAAY,KAAK,MAAM,S,GCL5G,qBAAb,cAA0C,YACxC,KAAgB,uBAEhB,WAAA,CACE,EAAU,wDAEV,MAAM,E,GCNG,yBAAb,cAA8C,YAC5C,KAAgB,2BAEhB,WAAA,CAAY,EAAkB,GAC5B,MACE,4DAA4D,oBAA2B,sB,GCLhF,oBAAb,cAAyC,YACvC,KAAgB,sBAEhB,WAAA,GACE,MAAM,4DACN,KAAK,KAAO,qB,GCEhB,MAAa,YAMT,GCkBS,SAAA,KACX,IAAK,YAAY,OACf,MAAM,IAAI,oBAGZ,MAAO,CACL,OAAQ,YAAY,OACpB,QAAS,YAAY,QACrB,OAAQ,YAAY,UAAU,QAC/B,ECrBH,IAAsB,UAAtB,MACE,OAEA,QACA,OAEA,WAAA,CAAY,GACV,KAAK,OAAS,EAAK,OACnB,KAAK,QAAU,EAAK,QACpB,KAAK,OAAS,CACZ,YAAa,GACb,QAAS,EAAK,QACd,OAAQ,EAAK,O,CAOjB,MAAA,GAAyB,GAc3B,MAAa,gBAAA,CACX,EACA,KAEA,MAA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AM,KAAK,EACd,EAAO,KAAK,E,CAahB,OAPC,WAAmB,SAAW,EAG3B,EAAI,oBACL,WAAmB,aAAe,GAGjC,EAAO,gBAAkB,EAAO,aAAe,EAAI,kBAC9C,EAGL,GAAM,SACR,YAAY,EAAO,GACZ,IAGT,YAAW,UACT,IASE,SARM,GAAM,YAAY,UAElB,EAAO,QAET,GAAM,aACF,EAAK,MAAM,GAGf,GAAM,KAER,aADM,EAAO,OACN,EAGT,GAAuB,iBAAZ,QAGT,IAAK,MAAM,IAFG,CAAC,UAAW,SAAU,UAAW,qBAG7C,QAAQ,KAAK,GAAM,MAAO,IACX,sBAAT,EACF,EAAO,KAAK,MAAM,qBAAsB,GAExC,EAAO,KAAK,KAAK,kBAAmB,CAAE,SAExC,UACQ,EAAO,OACb,QAAQ,IAAI,KACZ,QAAQ,KAAK,E,OACN,GACP,EAAO,KAAK,MAAM,wBAAyB,GAC3C,QAAQ,KAAK,E,WAKd,GACP,EAAO,KAAK,MAAM,yBAA0B,GACrB,iBAAZ,SACT,QAAQ,KAAK,E,KAKZ,EAAA,EAMT,YAAY,OAAA,IAAe,IAAI,kBAK/B,MAAM,YAAA,CACJ,EACA,KAEA,MAAM,EAAU,OAAO,OACvB,GAAI,QAAQ,UACV,IAAK,IAAI,EAAI,EAAG,EAAI,EAAS,IAC3B,QAAQ,YAGV,IAAI,EAAO,IACN,EACH,IAAK,IACA,GAAM,IACT,SAAU,GAAG,GAAM,KAAK,UAAY,OAAO,QAAQ,QAAQ,MAE7D,SAAS,GACT,S","file":"/npm/alepha@0.18.2/dist/core/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/alepha@0.18.2/dist/core/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/**\n * Used for identifying primitives.\n *\n * @internal\n */\nexport const KIND: unique symbol = Symbol.for(\"Alepha.Kind\");\n","/**\n * Used for identifying modules.\n *\n * @internal\n */\nexport const MODULE: unique symbol = Symbol.for(\"Alepha.Module\");\n","/**\n * Used for primitives options.\n *\n * @internal\n */\nexport const OPTIONS: unique symbol = Symbol.for(\"Alepha.Options\");\n","// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Default error class for Alepha.\n */\nexport class AlephaError extends Error {\n  name = \"AlephaError\";\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n","import { AlephaError } from \"./AlephaError.ts\";\n\nexport class CircularDependencyError extends AlephaError {\n  readonly name = \"CircularDependencyError\";\n\n  constructor(provider: string, parents?: string[]) {\n    super(\n      `Instance not available. Looks like a circular dependency. ? -> ${parents?.map((name) => `${name} -> `).join(\"\")}${provider} -> ?`,\n    );\n  }\n}\n","import { AlephaError } from \"./AlephaError.ts\";\n\nexport class ContainerLockedError extends AlephaError {\n  readonly name = \"ContainerLockedError\";\n\n  constructor(\n    message = \"Container is locked. No more providers can be added.\",\n  ) {\n    super(message);\n  }\n}\n","import { AlephaError } from \"./AlephaError.ts\";\n\nexport class TooLateSubstitutionError extends AlephaError {\n  readonly name = \"TooLateSubstitutionError\";\n\n  constructor(original: string, substitution: string) {\n    super(\n      `Service already substituted. Please, substitute Service '${original}' with Service '${substitution}' before using it.`,\n    );\n  }\n}\n","import { AlephaError } from \"./AlephaError.ts\";\n\nexport class MissingContextError extends AlephaError {\n  readonly name = \"MissingContextError\";\n\n  constructor() {\n    super(\"Missing context. Did you forget to call Alepha.create()?\");\n    this.name = \"MissingContextError\";\n  }\n}\n","import type { Alepha } from \"../Alepha.ts\";\nimport { MODULE } from \"../constants/MODULE.ts\";\nimport type { Service } from \"../interfaces/Service.ts\";\n\n/**\n * Store the current context and definition during injection phase.\n *\n * @internal\n */\nexport const __alephaRef: {\n  alepha?: Alepha;\n  service?: Service & {\n    [MODULE]?: Service;\n  };\n  parent?: Service;\n} = {};\n\n/**\n * Note:\n *\n * This file is used to share context between $primitives and the Alepha core during the injection phase.\n *\n * There is no side effect as long as Alepha is not used concurrently in multiple contexts (which is not the case).\n *\n * // __alephaRef === undefined\n * // begin alepha.with()\n * //   __alephaRef.context = alepha\n * //   ... injection phase ...\n * //   __alephaRef.context = undefined\n * // end alepha.with()\n * // __alephaRef === undefined\n *\n * As .with() is synchronous, there is no risk of context leakage.\n *\n * ---------------------------------------------------------------------------------------------------------------------\n *\n * Why this helper?\n *\n * It allows to avoid passing Alepha instance to every $hook, $inject, etc. calls. It's a beautiful syntactic sugar.\n *\n * With sugar:\n *\n * class A {\n *   on = $hook( ... ) // <- __alephaRef is set here\n * }\n *\n * Without sugar:\n *\n * class A {\n *   constructor(alepha: Alepha) {\n *     this.on = $hook(alepha, ... ) // <- no need of __alephaRef\n *   }\n * }\n *\n * One main goal of Alepha is working with classes but without the class verbosity.\n * Forcing to pass Alepha instance in constructors would be a step back in that direction!\n */\n","import type { Alepha } from \"../Alepha.ts\";\nimport { MODULE } from \"../constants/MODULE.ts\";\nimport { MissingContextError } from \"../errors/MissingContextError.ts\";\nimport { __alephaRef } from \"../helpers/ref.ts\";\nimport type { Service } from \"../interfaces/Service.ts\";\n\n/**\n * Get Alepha instance and current service from the current context.\n *\n * It can only be used inside $primitive functions.\n *\n * ```ts\n * import { $context } from \"alepha\";\n *\n * const $hello = () => {\n *   const { alepha, service, module } = $context();\n *\n *   // alepha - alepha instance\n *   // service - class which is creating this primitive, this is NOT the instance but the service definition\n *   // module - module definition, if any\n *\n *   return {};\n * }\n *\n * class MyService {\n *   hello = $hello();\n * }\n *\n * const alepha = new Alepha().with(MyService);\n * ```\n *\n * @internal\n */\nexport const $context = (): ContextPrimitive => {\n  if (!__alephaRef.alepha) {\n    throw new MissingContextError();\n  }\n\n  return {\n    alepha: __alephaRef.alepha,\n    service: __alephaRef.service,\n    module: __alephaRef.service?.[MODULE],\n  };\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ContextPrimitive {\n  /**\n   * Alepha instance.\n   */\n  alepha: Alepha;\n  /**\n   * Service definition which is creating this primitive.\n   * This is NOT the instance but the service definition.\n   */\n  service?: Service;\n  /**\n   * Module definition, if any.\n   */\n  module?: Service;\n}\n","import { Alepha } from \"../Alepha.ts\";\nimport { KIND } from \"../constants/KIND.ts\";\nimport { MODULE } from \"../constants/MODULE.ts\";\nimport type { InstantiableClass, Service } from \"../interfaces/Service.ts\";\nimport { $context } from \"../primitives/$context.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface PrimitiveArgs<T extends object = {}> {\n  options: T;\n  alepha: Alepha;\n  service: InstantiableClass<Service>;\n  module?: Service;\n}\n\nexport interface PrimitiveConfig {\n  propertyKey: string;\n  service: InstantiableClass<Service>;\n  module?: Service;\n}\n\nexport abstract class Primitive<T extends object = {}> {\n  protected readonly alepha: Alepha;\n\n  public readonly options: T;\n  public readonly config: PrimitiveConfig;\n\n  constructor(args: PrimitiveArgs<T>) {\n    this.alepha = args.alepha;\n    this.options = args.options;\n    this.config = {\n      propertyKey: \"\",\n      service: args.service,\n      module: args.module,\n    };\n  }\n\n  /**\n   * Called automatically by Alepha after the primitive is created.\n   */\n  protected onInit(): void {\n    // this method can be overridden by subclasses to perform initialization logic.\n    // - use onInit instead of the constructor when you need to access `config.propertyKey`\n    // - onInit must be synchronous\n  }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type PrimitiveFactoryLike<T extends object = any> = {\n  (options: T): any;\n  [KIND]: any;\n};\n\nexport const createPrimitive = <TPrimitive extends Primitive>(\n  primitive: InstantiableClass<TPrimitive> & { [MODULE]?: Service },\n  options: TPrimitive[\"options\"],\n): TPrimitive => {\n  const { alepha, service } = $context();\n\n  if (MODULE in primitive && primitive[MODULE]) {\n    alepha.with(primitive[MODULE]);\n  }\n\n  return alepha.inject(primitive, {\n    lifetime: \"transient\",\n    args: [\n      {\n        options,\n        alepha: alepha,\n        service: service ?? Alepha,\n      },\n    ],\n  });\n};\n","// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * In Alepha, a service is a class that can be instantiated or an abstract class. Nothing more, nothing less...\n */\nexport type Service<T extends object = any> =\n  | InstantiableClass<T>\n  | AbstractClass<T>\n  | RunFunction<T>;\n\nexport type RunFunction<T extends object = any> = (...args: any[]) => T | void;\n\nexport type InstantiableClass<T extends object = any> = new (\n  ...args: any[]\n) => T;\n\n/**\n * Abstract class is a class that cannot be instantiated directly!\n * It widely used for defining interfaces.\n */\nexport type AbstractClass<T extends object = any> = abstract new (\n  ...args: any[]\n) => T;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Service substitution allows you to register a class as a different class.\n * Providing class A, but using class B instead.\n * This is useful for testing, mocking, or providing a different implementation of a service.\n *\n * class A is mostly an AbstractClass, while class B is an InstantiableClass.\n */\nexport interface ServiceSubstitution<T extends object = any> {\n  /**\n   * Every time someone asks for this class, it will be provided with the 'use' class.\n   */\n  provide: Service<T>;\n\n  /**\n   * Service to use instead of the 'provide' service.\n   *\n   * Syntax is inspired by Angular's DI system.\n   */\n  use: Service<T>;\n\n  /**\n   * If true, if the service already exists -> just ignore the substitution and do not throw an error.\n   * Mostly used for plugins to enforce a substitution without throwing an error.\n   */\n  optional?: boolean;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Every time you register a service, you can use this type to define it.\n *\n * alepha.with( ServiceEntry )\n * or\n * alepha.with( provide: ServiceEntry, use: MyOwnServiceEntry )\n *\n * And yes, you declare the *type* of the service, not the *instance*.\n */\nexport type ServiceEntry<T extends object = any> =\n  | Service<T>\n  | ServiceSubstitution<T>;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function isClass(func: any): func is InstantiableClass {\n  // Classes have a non-writable prototype.constructor\n  if (typeof func !== \"function\") return false;\n\n  const descriptor = Object.getOwnPropertyDescriptor(func, \"prototype\");\n  return !!descriptor && !descriptor.writable;\n}\n","import type { Alepha } from \"../Alepha.ts\";\nimport { KIND } from \"../constants/KIND.ts\";\nimport { MODULE } from \"../constants/MODULE.ts\";\nimport { AlephaError } from \"../errors/AlephaError.ts\";\nimport type { PrimitiveFactoryLike } from \"../helpers/primitive.ts\";\nimport type { Service } from \"../interfaces/Service.ts\";\nimport type { Atom } from \"./$atom.ts\";\n\n/**\n * Wrap Services and Primitives into a Module.\n *\n * - A module is just a Service with some extra {@link Module}.\n * - You must attach a `name` to it.\n * - Name must follow the pattern: `project.module.submodule`. (e.g. `myapp.users.auth`).\n *\n * @example\n * ```ts\n * import { $module } from \"alepha\";\n * import { MyService } from \"./MyService.ts\";\n *\n * // export MyService, so it can be used everywhere (optional)\n * export * from \"./MyService.ts\";\n *\n * export default $module({\n *  name: \"my.project.module\",\n *  // MyService will have a module context \"my.project.module\"\n *  services: [MyService],\n * });\n * ```\n *\n * ### Why Modules?\n *\n * #### Logging\n *\n * By default, AlephaLogger will log the module name in the logs.\n * This helps to identify where the logs are coming from.\n *\n * You can also set different log levels for different modules.\n * It means you can set 'some.very.specific.module' to 'debug' and keep the rest of the application to 'info'.\n *\n * #### Modulith\n *\n * Force to structure your application in modules, even if it's a single deployable unit.\n * It helps to keep a clean architecture and avoid monolithic applications.\n *\n * A strict mode flag will probably come to enforce module boundaries.\n * -> Throwing errors when a service from another module is injected.\n * But it's not implemented yet.\n *\n * ### When not to use Modules?\n *\n * Small applications does not need modules. It's better to keep it simple.\n * Modules are more useful when the application grows and needs to be structured.\n * If we speak with number of `$actions`, a module should be used when you have more than 30 actions in a single module.\n * Meaning that if you have 100 actions, you should have at least 3 modules.\n */\nexport const $module = <T extends object = {}>(\n  options: ModulePrimitiveOptions,\n): Service<Module> => {\n  const { services = [], primitives = [], name } = options;\n\n  // ensure name is valid\n  if (!name || !Module.NAME_REGEX.test(name)) {\n    throw new AlephaError(\n      `Invalid module name '${name}'. It should be in the format of 'project.module.submodule'`,\n    );\n  }\n\n  const $ = class extends Module {\n    options = options;\n\n    register(alepha: Alepha): void {\n      if (options.atoms) {\n        for (const atom of options.atoms) {\n          alepha.store.register(atom);\n        }\n      }\n\n      if (typeof options.register === \"function\") {\n        options.register(alepha);\n        return;\n      }\n\n      for (const service of services) {\n        alepha.inject(service, {\n          parent: this.constructor as Service<Module>,\n        });\n      }\n    }\n  };\n\n  // force name property\n  Object.defineProperty($, \"name\", {\n    value: name,\n    writable: false,\n  });\n\n  for (const service of services) {\n    if (!Module.is(service)) {\n      (service as WithModule)[MODULE] = $;\n    }\n  }\n\n  for (const factory of primitives) {\n    if (typeof factory[KIND] === \"function\") {\n      factory[KIND][MODULE] = $;\n    }\n  }\n\n  return $; // module as Service<Module<T>>;\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ModulePrimitiveOptions {\n  /**\n   * Name of the module.\n   *\n   * It should be in the format of `project.module.submodule`.\n   */\n  name: string;\n\n  /**\n   * List all services related to this module.\n   *\n   * If you don't declare 'register' function, all services will be registered automatically.\n   * If you declare 'register' function, you must handle the registration of ALL services manually.\n   */\n  services?: Array<Service>;\n\n  /**\n   * List of $primitives to register in the module.\n   */\n  primitives?: Array<PrimitiveFactoryLike>;\n\n  /**\n   * By default, module will register ALL services.\n   * You can override this behavior by providing a register function.\n   * It's useful when you want to register services conditionally or in a specific order.\n   *\n   * Again, if you declare 'register', you must handle the registration of ALL services manually.\n   */\n  register?: (alepha: Alepha) => void;\n\n  /**\n   * List of atoms to register in the module.\n   */\n  atoms?: Array<Atom<any>>;\n}\n\n/**\n * Base class for all modules.\n */\nexport abstract class Module {\n  public abstract readonly options: ModulePrimitiveOptions;\n\n  public abstract register(alepha: Alepha): void;\n\n  static NAME_REGEX = /^[a-z-]+(\\.[a-z-][a-z0-9-]*)*$/;\n\n  /**\n   * Check if a Service is a Module.\n   */\n  static is(ctor: Service): boolean {\n    return ctor.prototype instanceof Module;\n  }\n\n  /**\n   * Get the Module of a Service.\n   *\n   * Returns undefined if the Service is not part of a Module.\n   */\n  static of(ctor: Service): Service<Module> | undefined {\n    return (ctor as WithModule)[MODULE];\n  }\n}\n\n/**\n * Helper type to add Module metadata to a Service.\n */\nexport type WithModule<T extends object = any> = T & {\n  [MODULE]?: Service;\n};\n","import type { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type AsyncLocalStorageData = any;\nexport type StateScope = \"current\" | \"app\" | \"parent\";\n\nexport const ALS_PARENT = Symbol(\"als.parent\");\n\nexport class AlsProvider {\n  static create = (): AsyncLocalStorage<AsyncLocalStorageData> | undefined => {\n    return undefined;\n  };\n\n  public als?: AsyncLocalStorage<AsyncLocalStorageData>;\n\n  constructor() {\n    this.als = AlsProvider.create();\n  }\n\n  public createContextId(): string {\n    return crypto.randomUUID();\n  }\n\n  public run<R>(callback: () => R, data: Record<string, any> = {}): R {\n    if (!this.als) {\n      return callback();\n    }\n\n    const parent = this.als.getStore() ?? undefined;\n\n    data.registry ??= new Map();\n    data.context ??= this.createContextId();\n\n    return this.als.run({ ...data, [ALS_PARENT]: parent }, callback);\n  }\n\n  public exists(): boolean {\n    return !!this.get(\"context\");\n  }\n\n  public get<T>(key: string, scope?: StateScope): T | undefined {\n    if (!this.als) {\n      return undefined;\n    }\n\n    const store = this.als.getStore();\n    if (!store) {\n      return undefined;\n    }\n\n    if (scope === \"app\") {\n      return undefined;\n    }\n\n    if (scope === \"current\") {\n      return key in store ? (store[key] as T) : undefined;\n    }\n\n    if (scope === \"parent\") {\n      return store[ALS_PARENT]?.[key] as T | undefined;\n    }\n\n    // Default: walk up the tree from current layer to root\n    if (key in store) {\n      return store[key] as T;\n    }\n\n    let current = store[ALS_PARENT];\n    while (current) {\n      if (key in current) {\n        return current[key] as T;\n      }\n      current = current[ALS_PARENT];\n    }\n\n    return undefined;\n  }\n\n  public has(key: string): boolean {\n    if (!this.als) {\n      return false;\n    }\n\n    const store = this.als.getStore();\n    if (!store) {\n      return false;\n    }\n\n    if (key in store) {\n      return true;\n    }\n\n    let current = store[ALS_PARENT];\n    while (current) {\n      if (key in current) {\n        return true;\n      }\n      current = current[ALS_PARENT];\n    }\n\n    return false;\n  }\n\n  public set<T>(key: string, value: T): void {\n    if (!this.als) {\n      return;\n    }\n\n    const store = this.als.getStore();\n    if (store) {\n      store[key] = value;\n    }\n  }\n}\n","import { Primitive } from \"../helpers/primitive.ts\";\nimport type { InstantiableClass, Service } from \"../interfaces/Service.ts\";\nimport { $context } from \"./$context.ts\";\n\n/**\n * Get the instance of the specified type from the context.\n *\n * ```ts\n * class A { }\n * class B {\n *   a = $inject(A);\n * }\n * ```\n */\nexport const $inject = <T extends object>(\n  type: Service<T>,\n  opts: InjectOptions<T> = {},\n): T => {\n  const { alepha, service } = $context();\n\n  // _ = $inject(Alepha)\n  if (type === alepha.constructor) {\n    return alepha as T;\n  }\n\n  return alepha.inject(type, {\n    // keep the parent for better error messages and circular dependencies detection\n    parent: service ?? (alepha.constructor as Service),\n    ...opts,\n  });\n};\n\nexport class InjectPrimitive extends Primitive {}\n\nexport interface InjectOptions<T extends object = any> {\n  /**\n   * - 'transient' → Always a new instance on every inject. Zero caching.\n   * - 'singleton' → One instance per Alepha runtime (per-thread). Never disposed until Alepha shuts down. (default)\n   * - 'scoped' → One instance per AsyncLocalStorage context.\n   *   - A new scope is created when Alepha handles a request, a scheduled job, a queue worker task...\n   *   - You can also start a manual scope via alepha.context.run(() => { ... }).\n   *   - When the scope ends, the scoped registry is discarded.\n   *\n   * @default \"singleton\"\n   */\n  lifetime?: \"transient\" | \"singleton\" | \"scoped\";\n\n  /**\n   * Constructor arguments to pass when creating a new instance.\n   */\n  args?: ConstructorParameters<InstantiableClass<T>>;\n\n  /**\n   * Parent that requested the instance.\n   *\n   * @internal\n   */\n  parent?: Service | null;\n}\n","/**\n * Mimics the JSON global object with stringify and parse methods.\n *\n * Used across the codebase via dependency injection.\n */\nexport class Json {\n  stringify = JSON.stringify;\n  parse = JSON.parse;\n}\n","import type { Static, TSchema } from \"./TypeProvider.ts\";\n\nexport abstract class SchemaCodec {\n  /**\n   * Encode the value to a string format.\n   */\n  public abstract encodeToString<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): string;\n\n  /**\n   * Encode the value to a binary format.\n   */\n  public abstract encodeToBinary<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): Uint8Array;\n\n  /**\n   * Decode string, binary, or other formats to the schema type.\n   */\n  public abstract decode<T>(schema: TSchema, value: unknown): T;\n}\n","import type { TSchema } from \"typebox\";\nimport { $inject } from \"../primitives/$inject.ts\";\nimport { Json } from \"./Json.ts\";\nimport { SchemaCodec } from \"./SchemaCodec.ts\";\nimport type { Static } from \"./TypeProvider.ts\";\n\nexport class JsonSchemaCodec extends SchemaCodec {\n  protected readonly json = $inject(Json);\n  protected readonly encoder = new TextEncoder();\n  protected readonly decoder = new TextDecoder();\n\n  public encodeToString<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): string {\n    return this.json.stringify(value);\n  }\n\n  public encodeToBinary<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): Uint8Array {\n    return this.encoder.encode(this.encodeToString(schema, value));\n  }\n\n  public decode<T>(schema: TSchema, value: unknown): T {\n    if (value instanceof Uint8Array) {\n      const text = this.decoder.decode(value);\n      return this.json.parse(text);\n    }\n\n    if (typeof value === \"string\") {\n      // Only parse if it looks like JSON (starts with { or [)\n      const trimmed = value.trim();\n      if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n        return this.json.parse(value);\n      }\n      // Return plain strings as-is\n      return value as T;\n    }\n\n    return value as T;\n  }\n}\n","import type { Hooks } from \"../Alepha.ts\";\nimport { KIND } from \"../constants/KIND.ts\";\nimport { createPrimitive, Primitive } from \"../helpers/primitive.ts\";\nimport type { Async } from \"../interfaces/Async.ts\";\nimport type { Service } from \"../interfaces/Service.ts\";\n\n/**\n * Registers a new hook.\n *\n * ```ts\n * import { $hook } from \"alepha\";\n *\n * class MyProvider {\n *   onStart = $hook({\n *     name: \"start\", // or \"configure\", \"ready\", \"stop\", ...\n *     handler: async (app) => {\n *       // await db.connect(); ...\n *     }\n *   });\n * }\n * ```\n *\n * Hooks are used to run async functions from all registered providers/services.\n *\n * You can't register a hook after the App has started.\n *\n * It's used under the hood by the `configure`, `start`, and `stop` methods.\n * Some modules also use hooks to run their own logic. (e.g. `alepha/server`).\n *\n * You can create your own hooks by using module augmentation:\n *\n * ```ts\n * declare module \"alepha\" {\n *\n *   interface Hooks {\n *     \"my:custom:hook\": {\n *       arg1: string;\n *     }\n *   }\n * }\n *\n * await alepha.events.emit(\"my:custom:hook\", { arg1: \"value\" });\n * ```\n *\n */\nexport const $hook = <T extends keyof Hooks>(options: HookOptions<T>) =>\n  createPrimitive(HookPrimitive<T>, options);\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface HookOptions<T extends keyof Hooks> {\n  /**\n   * The name of the hook. \"configure\", \"start\", \"ready\", \"stop\", ...\n   */\n  on: T;\n\n  /**\n   * The handler to run when the hook is triggered.\n   */\n  handler: (args: Hooks[T]) => Async<any>;\n\n  /**\n   * Force the hook to run first or last on the list of hooks.\n   */\n  priority?: \"first\" | \"last\";\n\n  /**\n   * Run this hook before the hooks owned by the specified services.\n   */\n  before?: object | Array<object>;\n\n  /**\n   * Run this hook after the hooks owned by the specified services.\n   */\n  after?: object | Array<object>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class HookPrimitive<T extends keyof Hooks> extends Primitive<\n  HookOptions<T>\n> {\n  public called = 0;\n\n  protected onInit() {\n    const handler = this.options.handler;\n\n    const resolveDeps = (\n      deps?: object | Array<object>,\n    ): Service[] | undefined => {\n      if (!deps) return undefined;\n      const arr = Array.isArray(deps) ? deps : [deps];\n      return arr.map((dep) => dep.constructor as Service);\n    };\n\n    this.alepha.events.on(this.options.on, {\n      caller: this.config.service,\n      priority: this.options.priority,\n      before: resolveDeps(this.options.before),\n      after: resolveDeps(this.options.after),\n      callback: (args: any) => {\n        this.called += 1;\n        return handler(args);\n      },\n    });\n  }\n}\n\n$hook[KIND] = HookPrimitive;\n","import type { Readable } from \"node:stream\";\nimport type { ReadableStream as WebReadableStream } from \"node:stream/web\";\nimport type { TSchema, TUnsafe } from \"typebox\";\n\nexport interface FileLike {\n  /**\n   * Filename.\n   * @default \"file\"\n   */\n  name: string;\n\n  /**\n   * Mandatory MIME type of the file.\n   * @default \"application/octet-stream\"\n   */\n  type: string;\n\n  /**\n   * Size of the file in bytes.\n   *\n   * Always 0 for streams, as the size is not known until the stream is fully read.\n   *\n   * @default 0\n   */\n  size: number;\n\n  /**\n   * Last modified timestamp in milliseconds since epoch.\n   *\n   * Always the current timestamp for streams, as the last modified time is not known.\n   * We use this field to ensure compatibility with File API.\n   *\n   * @default Date.now()\n   */\n  lastModified: number;\n\n  /**\n   * Returns a ReadableStream or Node.js Readable stream of the file content.\n   *\n   * For streams, this is the original stream.\n   */\n  stream(): StreamLike;\n\n  /**\n   * Returns the file content as an ArrayBuffer.\n   *\n   * For streams, this reads the entire stream into memory.\n   */\n  arrayBuffer(): Promise<ArrayBuffer>;\n\n  /**\n   * Returns the file content as a string.\n   *\n   * For streams, this reads the entire stream into memory and converts it to a string.\n   */\n  text(): Promise<string>;\n\n  // -- node specific fields --\n\n  /**\n   * Optional file path, if the file is stored on disk.\n   *\n   * This is not from the File API, but rather a custom field to indicate where the file is stored.\n   */\n  filepath?: string;\n}\n\n/**\n * TypeBox view of FileLike.\n */\nexport type TFile = TUnsafe<FileLike>;\n\nexport const isTypeFile = (value: TSchema): value is TFile => {\n  return (\n    value &&\n    typeof value === \"object\" &&\n    \"format\" in value &&\n    value.format === \"binary\"\n  );\n};\n\nexport const isFileLike = (value: any): value is FileLike => {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    !Array.isArray(value) &&\n    typeof value.name === \"string\" &&\n    typeof value.type === \"string\" &&\n    typeof value.size === \"number\" &&\n    typeof value.stream.bind(value) === \"function\"\n  );\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n// TODO: remove it, replace with WebStream\nexport type StreamLike =\n  | ReadableStream\n  | WebReadableStream\n  | Readable\n  | NodeJS.ReadableStream;\n\nexport type TStream = TUnsafe<StreamLike>;\n","import type {\n  TAny,\n  TArray,\n  TArrayOptions,\n  TBoolean,\n  TInteger,\n  TInterface,\n  TKeysToIndexer,\n  TNull,\n  TNumber,\n  TNumberOptions,\n  TObject,\n  TObjectOptions,\n  TOmit,\n  TOptionalAdd,\n  TPartial,\n  TPick,\n  TProperties,\n  TRecord,\n  TSchema,\n  TSchemaOptions,\n  TString,\n  TStringOptions,\n  TUnion,\n  TUnsafe,\n} from \"typebox\";\nimport { Type } from \"typebox\";\nimport Format from \"typebox/format\";\nimport { Settings } from \"typebox/system\";\nimport * as Value from \"typebox/value\";\nimport { OPTIONS } from \"../constants/OPTIONS.ts\";\nimport type { TypeBoxError } from \"../errors/TypeBoxError.ts\";\nimport { isTypeFile, type TFile, type TStream } from \"../helpers/FileLike.ts\";\n\nexport { Type, Value, Format };\n\n// https://github.com/sinclairzx81/typebox/blob/main/changelog/1.1.0.md\nSettings.Set({ correctiveParse: true });\n\nexport type {\n  StaticDecode,\n  StaticDecode as Static,\n  StaticEncode,\n  TAny,\n  TArray,\n  TBigInt,\n  TBoolean,\n  TInteger,\n  TKeysToIndexer,\n  TNull,\n  TNumber,\n  TNumberOptions,\n  TObject,\n  TObjectOptions,\n  TOptional,\n  TOptionalAdd,\n  TPick,\n  TProperties,\n  TRecord,\n  TSchema,\n  TString,\n  TStringOptions,\n  TTuple,\n  TUnion,\n  TUnsafe,\n  TVoid,\n} from \"typebox\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class TypeGuard {\n  // -------------------------------------------------------------------------------------------------------------------\n  isBigInt = (value: TSchema): value is TString =>\n    Type.IsString(value) && \"format\" in value && value.format === \"bigint\";\n  isUUID = (value: TSchema): value is TString =>\n    Type.IsString(value) && \"format\" in value && value.format === \"uuid\";\n  isObject = Type.IsObject;\n  isNumber = Type.IsNumber;\n  isString = Type.IsString;\n  isBoolean = Type.IsBoolean;\n  isAny = Type.IsAny;\n  isArray = Type.IsArray;\n  isOptional = Type.IsOptional;\n  isUnion = Type.IsUnion;\n  isInteger = Type.IsInteger;\n  isNull = Type.IsNull;\n  isUndefined = Type.IsUndefined;\n  isUnsafe = Type.IsUnsafe;\n  isRecord = Type.IsRecord;\n  isTuple = Type.IsTuple;\n  isVoid = Type.IsVoid;\n  isLiteral = Type.IsLiteral;\n  isSchema = Type.IsSchema;\n  isScalar = (schema: TSchema): boolean =>\n    this.isString(schema) ||\n    this.isNumber(schema) ||\n    this.isInteger(schema) ||\n    this.isBoolean(schema);\n  // -------------------------------------------------------------------------------------------------------------------\n  isFile = isTypeFile;\n  isDateTime = (schema: unknown) => {\n    return t.schema.isString(schema) && schema.format === \"date-time\";\n  };\n  isDate = (schema: unknown) => {\n    return t.schema.isString(schema) && schema.format === \"date\";\n  };\n  isTime = (schema: unknown) => {\n    return t.schema.isString(schema) && schema.format === \"time\";\n  };\n  isDuration = (schema: unknown) => {\n    return t.schema.isString(schema) && schema.format === \"duration\";\n  };\n}\n\ndeclare module \"typebox\" {\n  interface TString {\n    format?: string;\n    minLength?: number;\n    maxLength?: number;\n  }\n\n  interface TNumber {\n    format?: \"int64\";\n  }\n}\n\nexport class TypeProvider {\n  static format = Format;\n\n  static {\n    Format.Set(\"bigint\", (value: string | number) =>\n      TypeProvider.isValidBigInt(value),\n    );\n  }\n\n  static translateError(error: TypeBoxError, _locale?: string): string {\n    return error.cause.message;\n  }\n\n  static setLocale(_locale: string) {}\n\n  static isValidBigInt(value: string | number) {\n    if (typeof value === \"number\") {\n      return Number.isInteger(value);\n    }\n\n    // Reject empty or whitespace-only strings\n    if (!value.trim()) return false;\n    // Regex: optional minus, then digits only\n    if (!/^-?\\d+$/.test(value)) return false;\n\n    try {\n      BigInt(value); // Will throw if invalid\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Default maximum length for strings.\n   *\n   * It can be set to a larger value:\n   * ```ts\n   * TypeProvider.DEFAULT_STRING_MAX_LENGTH = 1000000;\n   * TypeProvider.DEFAULT_STRING_MAX_LENGTH = undefined; // no limit (not recommended)\n   * ```\n   */\n  static DEFAULT_STRING_MAX_LENGTH: number | undefined = 255;\n\n  /**\n   * Maximum length for short strings, such as names or titles.\n   */\n  static DEFAULT_SHORT_STRING_MAX_LENGTH: number | undefined = 64;\n\n  /**\n   * Maximum length for long strings, such as descriptions or comments.\n   * It can be overridden in the string options.\n   *\n   * It can be set to a larger value:\n   * ```ts\n   * TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH = 2048;\n   * ```\n   */\n  static DEFAULT_LONG_STRING_MAX_LENGTH: number | undefined = 1024;\n\n  /**\n   * Maximum length for rich strings, such as HTML or Markdown.\n   * This is a large value to accommodate rich text content.\n   * > It's also the maximum length of PG's TEXT type.\n   *\n   * It can be overridden in the string options.\n   *\n   * It can be set to a larger value:\n   * ```ts\n   * TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH = 1000000;\n   * ```\n   */\n  static DEFAULT_RICH_STRING_MAX_LENGTH: number | undefined = 65535;\n\n  /**\n   * Maximum number of items in an array.\n   * This is a default value to prevent excessive memory usage.\n   * It can be overridden in the array options.\n   */\n  static DEFAULT_ARRAY_MAX_ITEMS = 1000;\n\n  // -------------------------------------------------------------------------------------------------------------------\n  public raw = Type; // typebox reference\n  public any = Type.Any;\n  public void = Type.Void;\n  public undefined = Type.Undefined;\n  public record = Type.Record;\n  public union = Type.Union;\n  public tuple = Type.Tuple;\n  public null = Type.Null;\n  public const = Type.Literal;\n  public options = Type.Options;\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Type guards to check the type of schema.\n   * This is not a runtime type check, but a compile-time type guard.\n   *\n   * @example\n   * ```ts\n   * if (t.schema.isString(schema)) {\n   *   // schema is TString\n   * }\n   * ```\n   */\n  public readonly schema = new TypeGuard();\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  public extend<T extends TSchema[], U extends TProperties>(\n    schema: [...T],\n    properties: U,\n    options?: TSchemaOptions,\n  ): TInterface<T, U>;\n  public extend<T extends TObject, U extends TProperties>(\n    schema: T,\n    properties: U,\n    options?: TSchemaOptions,\n  ): TInterface<[T], U>;\n  public extend(\n    schema: TSchema | TSchema[],\n    properties: Record<string, any>,\n    options?: TSchemaOptions,\n  ): any {\n    return Type.Interface(\n      Array.isArray(schema) ? schema : [schema],\n      properties,\n      {\n        additionalProperties: false,\n        ...options,\n      },\n    );\n  }\n\n  public pick<T extends TObject, Indexer extends PropertyKey[]>(\n    schema: T,\n    keys: [...Indexer],\n    options?: TObjectOptions,\n  ): TPick<T, TKeysToIndexer<Indexer>> {\n    return Type.Pick(schema, keys, {\n      additionalProperties: false,\n      ...options,\n    });\n  }\n\n  public omit<T extends TObject, Indexer extends PropertyKey[]>(\n    schema: T,\n    keys: [...Indexer],\n    options?: TObjectOptions,\n  ): TOmit<T, TKeysToIndexer<Indexer>> {\n    return Type.Omit(schema, keys, {\n      additionalProperties: false,\n      ...options,\n    });\n  }\n\n  public partial<T extends TSchema>(\n    schema: T,\n    options?: TSchemaOptions,\n  ): TPartial<T> {\n    return Type.Partial(schema, {\n      additionalProperties: false,\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for an object.\n   * By default, additional properties are not allowed.\n   *\n   * @example\n   * ```ts\n   * const userSchema = t.object({\n   *   id: t.integer(),\n   *   name: t.string(),\n   * });\n   * ```\n   */\n  public object<T extends TProperties>(\n    properties: T,\n    options?: TObjectOptions,\n  ): TObject<T> {\n    return Type.Object(properties, {\n      additionalProperties: false,\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for an array.\n   * By default, the maximum number of items is limited to prevent excessive memory usage.\n   *\n   * @see TypeProvider.DEFAULT_ARRAY_MAX_ITEMS\n   */\n  public array<T extends TSchema>(\n    schema: T,\n    options?: TArrayOptions,\n  ): TArray<T> {\n    return Type.Array(schema, {\n      maxItems: TypeProvider.DEFAULT_ARRAY_MAX_ITEMS,\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for a string.\n   * For db or input fields, consider using `t.text()` instead, which has length limits.\n   *\n   * If you need a string with specific format (e.g. email, uuid), consider using the corresponding method (e.g. `t.email()`, `t.uuid()`).\n   */\n  public string(options: TStringOptions = {}): TString {\n    return Type.String({\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for a string with length limits.\n   * For internal strings without length limits, consider using `t.string()` instead.\n   *\n   * Default size is \"regular\", which has a max length of 255 characters.\n   */\n  public text(options: TTextOptions = {}): TString {\n    const { size, ...rest } = options;\n    const maxLength =\n      size === \"short\"\n        ? TypeProvider.DEFAULT_SHORT_STRING_MAX_LENGTH\n        : size === \"long\"\n          ? TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH\n          : size === \"rich\"\n            ? TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH\n            : TypeProvider.DEFAULT_STRING_MAX_LENGTH;\n\n    return Type.String({\n      maxLength,\n      \"~options\": {\n        trim: options.trim ?? true,\n        lowercase: options.lowercase ?? false,\n      },\n      ...rest,\n    });\n  }\n\n  /**\n   * Create a schema for a JSON object.\n   * This is a record with string keys and any values.\n   */\n  public json<T = any>(options?: TSchemaOptions): TRecord<string, TAny> {\n    return t.record(t.text(), t.any(), options);\n  }\n\n  /**\n   * Create a schema for a boolean.\n   */\n  public boolean(options?: TSchemaOptions): TBoolean {\n    return Type.Boolean({\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for a number.\n   */\n  public number(options?: TNumberOptions): TNumber {\n    return Type.Number({\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for an integer.\n   */\n  public integer(options?: TNumberOptions): TInteger {\n    return Type.Integer({\n      ...options,\n    });\n  }\n\n  public int32(options?: TNumberOptions): TInteger {\n    return Type.Integer({\n      minimum: -2147483647,\n      maximum: 2147483647,\n      ...options,\n    });\n  }\n\n  /**\n   * Mimic a signed 64-bit integer.\n   *\n   * This is NOT a true int64, as JavaScript cannot represent all int64 values.\n   * It is a number that is an integer and between -9007199254740991 and 9007199254740991.\n   * Use `t.bigint()` for true int64 values represented as strings.\n   */\n  public int64(options?: TNumberOptions): TNumber {\n    return Type.Number({\n      format: \"int64\",\n      multipleOf: 1,\n      minimum: -9007199254740991,\n      maximum: 9007199254740991,\n      ...options,\n    });\n  }\n\n  /**\n   * Make a schema optional.\n   */\n  public optional<T extends TSchema>(schema: T): TOptionalAdd<T> {\n    return Type.Optional(schema);\n  }\n\n  /**\n   * Make a schema nullable.\n   */\n  public nullable<T extends TSchema>(\n    schema: T,\n    options?: TObjectOptions,\n  ): TUnion<[TNull, T]> {\n    return Type.Union([Type.Null(), schema], options);\n  }\n\n  /**\n   * Create a schema that maps all properties of an object schema to nullable.\n   */\n  public nullify = <T extends TSchema>(schema: T, options?: TObjectOptions) =>\n    Type.Mapped(\n      Type.Identifier(\"K\"),\n      Type.KeyOf(schema),\n      Type.Ref(\"K\"),\n      Type.Union([Type.Index(schema, Type.Ref(\"K\")), Type.Null()]),\n      options,\n    );\n\n  /**\n   * Create a schema for a string enum.\n   */\n  public enum<T extends string[]>(\n    values: [...T],\n    options?: TTextOptions,\n  ): TUnsafe<T[number]> {\n    return Type.Unsafe<T[number]>(\n      t.text({\n        enum: values,\n        pattern: values.map((v) => `^${v}$`).join(\"|\"),\n        ...options,\n      }),\n    );\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  // Codec types\n\n  /**\n   * Create a schema for a bigint represented as a string.\n   * This is a string that validates bigint format (e.g. \"123456789\").\n   */\n  public bigint(options?: TStringOptions) {\n    return t.string({\n      ...options,\n      format: \"bigint\",\n    });\n  }\n\n  /**\n   * Create a schema for a URL represented as a string.\n   */\n  public url(options?: TStringOptions) {\n    return this.string({\n      ...options,\n      format: \"url\",\n    });\n  }\n\n  /**\n   * Create a schema for binary data represented as a base64 string.\n   */\n  public binary(options: TStringOptions = {}) {\n    return this.string({\n      ...options,\n      format: \"binary\",\n    });\n  }\n\n  /**\n   * Create a schema for uuid.\n   */\n  public uuid(options?: TStringOptions): TString {\n    return this.string({\n      ...options,\n      format: \"uuid\",\n    });\n  }\n\n  /**\n   * Create a schema for a file-like object.\n   *\n   * File like mimics the File API in browsers, but is adapted to work in Node.js as well.\n   *\n   * Implementation of file-like objects is handled by \"alepha/file\" package.\n   */\n  public file(options?: { maxSize?: number }): TFile {\n    return Type.Unsafe(\n      Type.Any({\n        [OPTIONS]: options,\n        format: \"binary\",\n      }),\n    );\n  }\n\n  /**\n   * @experimental\n   */\n  public stream(): TStream {\n    return Type.Unsafe(\n      Type.Any({\n        format: \"stream\",\n        type: \"string\",\n      }),\n    );\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n  // Exotic types\n\n  public email(options?: TStringOptions): TString {\n    return this.text({\n      ...options,\n      format: \"email\",\n      trim: true,\n      lowercase: true,\n    });\n  }\n\n  public e164(options?: TStringOptions): TString {\n    return this.text({\n      ...options,\n      description: \"Phone number in E.164 format, e.g. +1234567890.\",\n      pattern: \"^\\\\+[1-9]\\\\d{1,14}$\",\n    });\n  }\n\n  public bcp47(options?: TStringOptions): TString {\n    return this.text({\n      ...options,\n      description: \"BCP 47 language tag, e.g. en, en-US, fr, fr-CA.\",\n      pattern: \"^[a-z]{2,3}(?:-[A-Z]{2})?$\",\n    });\n  }\n\n  /**\n   * Create a schema for short text, such as names or titles.\n   * Default max length is 64 characters.\n   */\n  public shortText(options?: TStringOptions): TString {\n    return this.text({\n      size: \"short\",\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for long text, such as descriptions or comments.\n   * Default max length is 1024 characters.\n   */\n  public longText(options?: TStringOptions): TString {\n    return this.text({\n      size: \"long\",\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for rich text, such as HTML or Markdown.\n   * Default max length is 65535 characters.\n   */\n  public richText(options?: TStringOptions): TString {\n    return this.text({\n      size: \"rich\",\n      ...options,\n    });\n  }\n\n  /**\n   * Create a schema for a constant case string e.g. LIKE_THIS.\n   */\n  public constantCase = (options?: TStringOptions) =>\n    this.text({\n      pattern: \"^[A-Z_-]+$\",\n      ...options,\n    });\n\n  /**\n   * Create a schema for an object with a value and label.\n   */\n  public valueLabel = (options?: TObjectOptions) =>\n    this.object(\n      {\n        value: this.constantCase({\n          description: \"Machine-readable value.\",\n        }),\n        label: this.text({\n          description: \"Human-readable label.\",\n        }),\n        description: this.optional(\n          this.text({\n            description: \"Description of the value.\",\n            size: \"long\",\n          }),\n        ),\n      },\n      options,\n    );\n\n  public datetime = (options?: TStringOptions) =>\n    t.text({\n      ...options,\n      format: \"date-time\",\n    });\n\n  public date = (options?: TStringOptions) =>\n    t.text({\n      ...options,\n      format: \"date\",\n    });\n\n  public time = (options?: TStringOptions) =>\n    t.text({\n      ...options,\n      format: \"time\",\n    });\n\n  public duration = (options?: TStringOptions) =>\n    t.text({\n      ...options,\n      format: \"duration\",\n    });\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type TextLength = \"short\" | \"regular\" | \"long\" | \"rich\";\n\nexport interface TTextOptions extends TStringOptions {\n  /**\n   * Predefined size of the text.\n   *\n   * - `short` - short text, such as names or titles. Default max length is 64 characters.\n   * - `regular` - regular text, such as single-line input. Default max length is 255 characters.\n   * - `long` - long text, such as descriptions or comments. Default max length is 1024 characters.\n   * - `rich` - rich text, such as HTML or Markdown. Default max length is 65535 characters.\n   *\n   * You can override the default max length by specifying `maxLength` in the options.\n   *\n   * @default \"regular\"\n   */\n  size?: TextLength;\n\n  /**\n   * Trim whitespace from both ends of the string.\n   *\n   * @default true\n   */\n  trim?: boolean;\n\n  /**\n   * Convert the string to lowercase.\n   *\n   * @default false\n   */\n  lowercase?: boolean;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const t: TypeProvider = new TypeProvider();\n","import type { TArray, TObject, TSchema, TUnion } from \"typebox\";\nimport { AlephaError } from \"../errors/AlephaError.ts\";\nimport { $hook } from \"../primitives/$hook.ts\";\nimport { SchemaCodec } from \"./SchemaCodec.ts\";\nimport { type Static, t } from \"./TypeProvider.ts\";\n\n// =============================================================================\n// Keyless JSON Codec\n// =============================================================================\n// Schema-driven JSON encoding without keys:\n// - Schema defines field order → no keys needed in output\n// - Uses native JSON.stringify on arrays (fast!)\n// - Uses native JSON.parse for decoding (blazing fast)\n// - 50-56% smaller than JSON, decode 1.7-2x faster\n//\n// Example:\n//   JSON:    {\"name\":\"Alice\",\"age\":30,\"active\":true}  (39 bytes)\n//   Keyless: [\"Alice\",30,true]                        (17 bytes)\n// =============================================================================\n\n// Security: Keys that could enable prototype pollution attacks\nconst UNSAFE_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport interface KeylessCodec<T = any> {\n  encode: (value: T) => string;\n  decode: (str: string) => T;\n}\n\nexport interface KeylessCodecOptions {\n  /**\n   * Whether to use `new Function()` for code compilation.\n   * When false, uses an interpreter-based approach (safer but slower).\n   *\n   * @default Auto-detected: false in browser (CSP compatibility), true on server\n   */\n  useFunctionCompilation?: boolean;\n\n  /**\n   * Maximum allowed array length during encoding/decoding.\n   * Prevents DoS attacks via large arrays.\n   *\n   * @default 10000\n   */\n  maxArrayLength?: number;\n\n  /**\n   * Maximum allowed string length during encoding/decoding.\n   * Prevents DoS attacks via large strings.\n   *\n   * @default 1000000 (1MB)\n   */\n  maxStringLength?: number;\n\n  /**\n   * Maximum recursion depth for nested objects.\n   * Prevents stack overflow attacks.\n   *\n   * @default 50\n   */\n  maxDepth?: number;\n}\n\n/**\n * KeylessJsonSchemaCodec provides schema-driven JSON encoding without keys.\n *\n * It uses the schema to determine field order, allowing the encoded output\n * to be a simple JSON array instead of an object with keys.\n */\nexport class KeylessJsonSchemaCodec extends SchemaCodec {\n  protected readonly cache = new Map<TSchema, KeylessCodec>();\n  protected readonly textEncoder = new TextEncoder();\n  protected readonly textDecoder = new TextDecoder();\n  protected varCounter = 0;\n\n  // Options with defaults\n  protected useFunctionCompilation = true;\n  protected maxArrayLength = 10000;\n  protected maxStringLength = 1000000;\n  protected maxDepth = 50;\n\n  /**\n   * Configure codec options.\n   */\n  public configure(options: KeylessCodecOptions): this {\n    if (options.useFunctionCompilation !== undefined) {\n      this.useFunctionCompilation = options.useFunctionCompilation;\n      this.cache.clear(); // Clear cache when compilation mode changes\n    }\n    if (options.maxArrayLength !== undefined) {\n      this.maxArrayLength = options.maxArrayLength;\n    }\n    if (options.maxStringLength !== undefined) {\n      this.maxStringLength = options.maxStringLength;\n    }\n    if (options.maxDepth !== undefined) {\n      this.maxDepth = options.maxDepth;\n    }\n    return this;\n  }\n\n  /**\n   * Hook to auto-detect safe mode on configure.\n   * Disables function compilation in browser by default.\n   */\n  protected onConfigure = $hook({\n    on: \"configure\",\n    handler: () => {\n      // Auto-detect: disable function compilation in browser (CSP compatibility)\n      // and test if eval/Function is available\n      this.useFunctionCompilation = this.canUseFunction();\n    },\n  });\n\n  /**\n   * Encode value to a keyless JSON string.\n   */\n  public encodeToString<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): string {\n    return this.getCodec(schema).encode(value);\n  }\n\n  /**\n   * Encode value to binary (UTF-8 encoded keyless JSON).\n   */\n  public encodeToBinary<T extends TSchema>(\n    schema: T,\n    value: Static<T>,\n  ): Uint8Array {\n    return this.textEncoder.encode(this.encodeToString(schema, value));\n  }\n\n  /**\n   * Decode keyless JSON string or binary to value.\n   */\n  public decode<T>(schema: TSchema, value: unknown): T {\n    if (value instanceof Uint8Array) {\n      const text = this.textDecoder.decode(value);\n      return this.getCodec(schema).decode(text) as T;\n    }\n\n    if (typeof value === \"string\") {\n      return this.getCodec(schema).decode(value) as T;\n    }\n\n    // If already an array (parsed JSON), reconstruct object\n    if (Array.isArray(value)) {\n      return this.reconstructObject(schema, value) as T;\n    }\n\n    return value as T;\n  }\n\n  // ===========================================================================\n  // Security Validation\n  // ===========================================================================\n\n  /**\n   * Test if `new Function()` is available (not blocked by CSP).\n   */\n  protected canUseFunction(): boolean {\n    try {\n      const fn = new Function(\"return true\");\n      return fn() === true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Validate schema keys for prototype pollution.\n   * Uses a visited set to avoid infinite recursion on recursive schemas.\n   */\n  protected validateSchemaKeys(\n    schema: TSchema,\n    depth = 0,\n    visited = new Set<TSchema>(),\n  ): void {\n    // Avoid infinite recursion on recursive schemas\n    if (visited.has(schema)) {\n      return;\n    }\n    visited.add(schema);\n\n    if (depth > this.maxDepth) {\n      throw new AlephaError(\n        `Schema depth exceeds maximum allowed (${this.maxDepth})`,\n      );\n    }\n\n    if (t.schema.isObject(schema)) {\n      const objSchema = schema as TObject;\n      const props = objSchema.properties as Record<string, TSchema>;\n\n      for (const key of Object.keys(props)) {\n        if (UNSAFE_KEYS.has(key)) {\n          throw new AlephaError(\n            `Unsafe schema key \"${key}\" detected. This key is blocked to prevent prototype pollution.`,\n          );\n        }\n        // Depth increases for object properties\n        this.validateSchemaKeys(props[key], depth + 1, visited);\n      }\n    } else if (t.schema.isArray(schema)) {\n      const arrSchema = schema as TArray;\n      // Depth increases for array items\n      this.validateSchemaKeys(arrSchema.items, depth + 1, visited);\n    } else if (t.schema.isUnion(schema) || t.schema.isOptional(schema)) {\n      // Optional/union wrappers don't increase depth - they're type modifiers\n      this.validateSchemaKeys(this.unwrap(schema), depth, visited);\n    }\n  }\n\n  /**\n   * Validate array length.\n   */\n  protected validateArrayLength(arr: unknown[]): void {\n    if (arr.length > this.maxArrayLength) {\n      throw new AlephaError(\n        `Array length (${arr.length}) exceeds maximum allowed (${this.maxArrayLength})`,\n      );\n    }\n  }\n\n  /**\n   * Validate string length.\n   */\n  protected validateStringLength(str: string): void {\n    if (str.length > this.maxStringLength) {\n      throw new AlephaError(\n        `String length (${str.length}) exceeds maximum allowed (${this.maxStringLength})`,\n      );\n    }\n  }\n\n  // ===========================================================================\n  // Codec Compilation\n  // ===========================================================================\n\n  /**\n   * Get a compiled codec for the given schema.\n   * Codecs are cached for reuse.\n   */\n  protected getCodec<T>(schema: TSchema): KeylessCodec<T> {\n    let c = this.cache.get(schema);\n    if (!c) {\n      c = this.useFunctionCompilation\n        ? this.compileWithFunction(schema)\n        : this.compileInterpreted(schema);\n      this.cache.set(schema, c);\n    }\n    return c as KeylessCodec<T>;\n  }\n\n  protected nextVar(): string {\n    return `_${this.varCounter++}`;\n  }\n\n  /**\n   * Compile codec using `new Function()` for maximum performance.\n   * Only used when CSP allows and useFunctionCompilation is true.\n   */\n  protected compileWithFunction(schema: TSchema): KeylessCodec {\n    this.varCounter = 0;\n    const encBody = this.genEnc(schema, \"v\");\n\n    this.varCounter = 0;\n    const decBody = this.genDec(schema);\n\n    const encoder = new Function(\"v\", `return JSON.stringify(${encBody});`) as (\n      value: any,\n    ) => string;\n\n    const decoder = new Function(\n      \"s\",\n      `const a=JSON.parse(s);let i=0;${decBody.code}return ${decBody.result};`,\n    ) as (str: string) => any;\n\n    return { encode: encoder, decode: decoder };\n  }\n\n  /**\n   * Compile codec using interpreter-based approach.\n   * Safer (no eval/Function) but slower. Used in browser by default.\n   */\n  protected compileInterpreted(schema: TSchema): KeylessCodec {\n    const self = this;\n\n    return {\n      encode(value: any): string {\n        return JSON.stringify(self.interpretEncode(schema, value));\n      },\n      decode(str: string): any {\n        const ctx = { arr: JSON.parse(str), i: 0 };\n        return self.interpretDecode(schema, ctx);\n      },\n    };\n  }\n\n  // ===========================================================================\n  // Interpreter-based Encoding (Safe Mode)\n  // ===========================================================================\n\n  protected interpretEncode(schema: TSchema, value: any): any {\n    if (this.isLeaf(schema)) {\n      return value;\n    }\n\n    if (t.schema.isBigInt(schema)) {\n      return `${value}n`;\n    }\n\n    if (t.schema.isArray(schema)) {\n      const arrSchema = schema as TArray;\n      if (!Array.isArray(value)) return value;\n\n      if (t.schema.isScalar(arrSchema.items)) {\n        return value;\n      }\n      return value.map((e) => this.interpretEncode(arrSchema.items, e));\n    }\n\n    if (t.schema.isObject(schema)) {\n      const result: any[] = [];\n      for (const { key, isOpt, isNullable, inner } of this.getObjectFields(\n        schema as TObject,\n      )) {\n        const v = value[key];\n\n        if (isOpt) {\n          result.push(v !== undefined ? this.interpretEncode(inner, v) : null);\n        } else if (isNullable) {\n          result.push(v !== null ? this.interpretEncode(inner, v) : null);\n        } else {\n          result.push(this.interpretEncode(inner, v));\n        }\n      }\n      return result;\n    }\n\n    if (t.schema.isOptional(schema) || t.schema.isUnion(schema)) {\n      const inner = this.unwrap(schema);\n      if (this.isNullable(schema)) {\n        return value !== null ? this.interpretEncode(inner, value) : null;\n      }\n      return value !== undefined ? this.interpretEncode(inner, value) : null;\n    }\n\n    return value;\n  }\n\n  // ===========================================================================\n  // Interpreter-based Decoding (Safe Mode)\n  // ===========================================================================\n\n  protected interpretDecode(\n    schema: TSchema,\n    ctx: { arr: any[]; i: number },\n  ): any {\n    if (this.isLeaf(schema)) {\n      return ctx.arr[ctx.i++];\n    }\n\n    if (t.schema.isBigInt(schema)) {\n      return BigInt(ctx.arr[ctx.i++].slice(0, -1));\n    }\n\n    if (t.schema.isArray(schema)) {\n      const arrSchema = schema as TArray;\n      const arr = ctx.arr[ctx.i++];\n      if (!Array.isArray(arr)) return arr;\n\n      if (t.schema.isObject(arrSchema.items)) {\n        return arr.map((e) =>\n          this.interpretDecodeFromValue(arrSchema.items, e),\n        );\n      }\n      return arr;\n    }\n\n    if (t.schema.isObject(schema)) {\n      const result: Record<string, any> = {};\n\n      for (const { key, isOpt, isNullable, inner } of this.getObjectFields(\n        schema as TObject,\n      )) {\n        const val = ctx.arr[ctx.i++];\n\n        if (isOpt) {\n          if (val !== null) {\n            result[key] = this.interpretDecodeFromValue(inner, val);\n          }\n        } else if (isNullable) {\n          result[key] =\n            val === null ? null : this.interpretDecodeFromValue(inner, val);\n        } else {\n          result[key] = this.interpretDecodeFromValue(inner, val);\n        }\n      }\n\n      return result;\n    }\n\n    if (t.schema.isOptional(schema) || t.schema.isUnion(schema)) {\n      const inner = this.unwrap(schema);\n      const val = ctx.arr[ctx.i++];\n\n      if (val === null) {\n        return this.isNullable(schema) ? null : undefined;\n      }\n\n      if (t.schema.isObject(inner) || t.schema.isArray(inner)) {\n        return this.interpretDecodeFromValue(inner, val);\n      }\n\n      return val;\n    }\n\n    return ctx.arr[ctx.i++];\n  }\n\n  protected interpretDecodeFromValue(schema: TSchema, value: any): any {\n    if (this.isLeaf(schema)) {\n      return value;\n    }\n\n    if (t.schema.isBigInt(schema)) {\n      return BigInt(value.slice(0, -1));\n    }\n\n    if (t.schema.isArray(schema)) {\n      if (!Array.isArray(value)) return value;\n      const arrSchema = schema as TArray;\n      if (t.schema.isObject(arrSchema.items)) {\n        return value.map((e) =>\n          this.interpretDecodeFromValue(arrSchema.items, e),\n        );\n      }\n      return value;\n    }\n\n    if (t.schema.isObject(schema)) {\n      const objSchema = schema as TObject;\n      const props = objSchema.properties as Record<string, TSchema>;\n      const keys = Object.keys(props);\n      const result: Record<string, any> = {};\n\n      for (let idx = 0; idx < keys.length; idx++) {\n        const k = keys[idx];\n        const inner = this.unwrap(props[k]);\n        const v = value[idx];\n\n        if (t.schema.isObject(inner)) {\n          result[k] = this.interpretDecodeFromValue(inner, v);\n        } else if (t.schema.isBigInt(inner)) {\n          result[k] = BigInt(v.slice(0, -1));\n        } else {\n          result[k] = v;\n        }\n      }\n\n      return result;\n    }\n\n    return value;\n  }\n\n  // ===========================================================================\n  // Encoder - generates code that returns an array representation\n  // ===========================================================================\n\n  protected genEnc(schema: TSchema, ve: string): string {\n    if (this.isLeaf(schema)) {\n      return ve;\n    }\n\n    if (t.schema.isBigInt(schema)) {\n      return `${ve}+'n'`;\n    }\n\n    if (t.schema.isArray(schema)) {\n      const arrSchema = schema as TArray;\n      const itemEnc = this.genEnc(arrSchema.items, \"e\");\n      if (t.schema.isScalar(arrSchema.items)) {\n        return ve;\n      }\n      return `${ve}.map(e=>${itemEnc})`;\n    }\n\n    if (t.schema.isObject(schema)) {\n      const parts: string[] = [];\n      for (const { key, isOpt, isNullable, inner } of this.getObjectFields(\n        schema as TObject,\n      )) {\n        const innerEnc = this.genEnc(inner, `${ve}.${key}`);\n\n        if (isOpt) {\n          parts.push(`${ve}.${key}!==undefined?${innerEnc}:null`);\n        } else if (isNullable) {\n          parts.push(`${ve}.${key}!==null?${innerEnc}:null`);\n        } else {\n          parts.push(innerEnc);\n        }\n      }\n\n      return `[${parts.join(\",\")}]`;\n    }\n\n    if (t.schema.isOptional(schema) || t.schema.isUnion(schema)) {\n      const inner = this.unwrap(schema);\n      const innerEnc = this.genEnc(inner, ve);\n      if (this.isNullable(schema)) {\n        return `${ve}!==null?${innerEnc}:null`;\n      }\n      return `${ve}!==undefined?${innerEnc}:null`;\n    }\n\n    return ve;\n  }\n\n  // ===========================================================================\n  // Decoder - generates code to reconstruct object from parsed array\n  // ===========================================================================\n\n  protected genDec(schema: TSchema): { code: string; result: string } {\n    const v = this.nextVar();\n\n    if (this.isLeaf(schema)) {\n      return { code: \"\", result: \"a[i++]\" };\n    }\n\n    if (t.schema.isBigInt(schema)) {\n      return { code: \"\", result: \"BigInt(a[i++].slice(0,-1))\" };\n    }\n\n    if (t.schema.isArray(schema)) {\n      const arrSchema = schema as TArray;\n      // Check if array items need transformation (objects)\n      if (t.schema.isObject(arrSchema.items)) {\n        const itemTransform = this.genDecFromValue(arrSchema.items, \"e\");\n        return { code: \"\", result: `a[i++].map(e=>${itemTransform})` };\n      }\n      return { code: \"\", result: \"a[i++]\" };\n    }\n\n    if (t.schema.isObject(schema)) {\n      const fields = this.getObjectFields(schema as TObject);\n\n      // Check if simple (all required primitives)\n      const simple = fields.every(\n        ({ isOpt, isNullable, inner }) =>\n          !isOpt &&\n          !isNullable &&\n          !t.schema.isObject(inner) &&\n          !t.schema.isArray(inner),\n      );\n\n      if (simple) {\n        const fieldExprs = fields.map(({ key }) => `${key}:a[i++]`);\n        return { code: \"\", result: `{${fieldExprs.join(\",\")}}` };\n      }\n\n      let code = `const ${v}={};`;\n      for (const { key, isOpt, isNullable, inner } of fields) {\n        if (isOpt) {\n          const nested = this.genDecFromValue(inner, \"t\");\n          code += `{const t=a[i++];if(t!==null){${v}.${key}=${nested};}}`;\n        } else if (isNullable) {\n          const nested = this.genDecFromValue(inner, \"t\");\n          code += `{const t=a[i++];if(t===null){${v}.${key}=null;}else{${v}.${key}=${nested};}}`;\n        } else if (t.schema.isObject(inner)) {\n          const nested = this.genDecFromValue(inner, \"a[i++]\");\n          code += `${v}.${key}=${nested};`;\n        } else if (t.schema.isArray(inner)) {\n          // Handle arrays - check if items need transformation\n          const arrSchema = inner as TArray;\n          if (t.schema.isObject(arrSchema.items)) {\n            const itemTransform = this.genDecFromValue(arrSchema.items, \"e\");\n            code += `${v}.${key}=a[i++].map(e=>${itemTransform});`;\n          } else {\n            code += `${v}.${key}=a[i++];`;\n          }\n        } else {\n          code += `${v}.${key}=a[i++];`;\n        }\n      }\n\n      return { code, result: v };\n    }\n\n    if (t.schema.isOptional(schema) || t.schema.isUnion(schema)) {\n      const inner = this.unwrap(schema);\n      const innerDec = this.genDec(inner);\n      const nullVal = this.isNullable(schema) ? \"null\" : \"undefined\";\n      return {\n        code: `const ${v}t=a[i++];let ${v};if(${v}t===null){${v}=${nullVal};}else{${innerDec.code.replace(/a\\[i\\+\\+\\]/g, `${v}t`)}${v}=${innerDec.result.replace(/a\\[i\\+\\+\\]/g, `${v}t`)};}`,\n        result: v,\n      };\n    }\n\n    return { code: \"\", result: \"a[i++]\" };\n  }\n\n  protected genDecFromValue(schema: TSchema, expr: string): string {\n    if (this.isLeaf(schema)) {\n      return expr;\n    }\n    if (t.schema.isBigInt(schema)) {\n      return `BigInt(${expr}.slice(0,-1))`;\n    }\n    if (t.schema.isArray(schema)) {\n      return expr;\n    }\n    if (t.schema.isObject(schema)) {\n      const objSchema = schema as TObject;\n      const props = objSchema.properties as Record<string, TSchema>;\n      const keys = Object.keys(props);\n      const v = this.nextVar();\n      const fields = keys.map((k, idx) => {\n        const inner = this.unwrap(props[k]);\n        const innerExpr = `${v}[${idx}]`;\n        if (t.schema.isObject(inner)) {\n          return `${k}:${this.genDecFromValue(inner, innerExpr)}`;\n        }\n        if (t.schema.isBigInt(inner)) {\n          return `${k}:BigInt(${innerExpr}.slice(0,-1))`;\n        }\n        return `${k}:${innerExpr}`;\n      });\n      return `((${v}=${expr})=>({${fields.join(\",\")}}))()`;\n    }\n    return expr;\n  }\n\n  // ===========================================================================\n  // Helpers\n  // ===========================================================================\n\n  protected isLeaf(schema: TSchema): boolean {\n    return t.schema.isScalar(schema) || this.isEnum(schema);\n  }\n\n  protected getObjectFields(schema: TObject): Array<{\n    key: string;\n    isOpt: boolean;\n    isNullable: boolean;\n    inner: TSchema;\n  }> {\n    const props = schema.properties as Record<string, TSchema>;\n    const req = new Set((schema.required as string[]) || []);\n    return Object.keys(props).map((key) => {\n      const ps = props[key];\n      return {\n        key,\n        isOpt: !req.has(key) || t.schema.isOptional(ps),\n        isNullable: this.isNullable(ps),\n        inner: this.unwrap(ps),\n      };\n    });\n  }\n\n  protected isEnum(schema: TSchema): boolean {\n    return (\n      \"enum\" in schema &&\n      Array.isArray((schema as { enum?: unknown[] }).enum) &&\n      ((schema as { enum?: unknown[] }).enum?.length ?? 0) > 0\n    );\n  }\n\n  protected isNullable(schema: TSchema): boolean {\n    if (!t.schema.isUnion(schema)) return false;\n    const unionSchema = schema as TUnion;\n    return unionSchema.anyOf?.some((s: TSchema) => t.schema.isNull(s)) ?? false;\n  }\n\n  protected unwrap(schema: TSchema): TSchema {\n    if (\"anyOf\" in schema && Array.isArray((schema as TUnion).anyOf)) {\n      const unionSchema = schema as TUnion;\n      return (\n        unionSchema.anyOf.find((s: TSchema) => !t.schema.isNull(s)) || schema\n      );\n    }\n    return schema;\n  }\n\n  /**\n   * Reconstruct an object from a parsed array (for when input is already parsed).\n   */\n  protected reconstructObject(schema: TSchema, arr: any[]): any {\n    if (!t.schema.isObject(schema)) return arr;\n\n    const result: Record<string, any> = {};\n    let i = 0;\n\n    for (const { key, isOpt, isNullable, inner } of this.getObjectFields(\n      schema as TObject,\n    )) {\n      const val = arr[i++];\n\n      if (isOpt) {\n        if (val !== null) {\n          result[key] = t.schema.isObject(inner)\n            ? this.reconstructObject(inner, val)\n            : val;\n        }\n      } else if (isNullable) {\n        result[key] =\n          val === null\n            ? null\n            : t.schema.isObject(inner)\n              ? this.reconstructObject(inner, val)\n              : val;\n      } else {\n        result[key] = t.schema.isObject(inner)\n          ? this.reconstructObject(inner, val)\n          : val;\n      }\n    }\n\n    return result;\n  }\n}\n","import type { TLocalizedValidationError } from \"typebox/error\";\nimport { AlephaError } from \"./AlephaError.ts\";\n\nexport class TypeBoxError extends AlephaError {\n  name = \"TypeBoxError\";\n\n  public readonly cause: TLocalizedValidationError;\n  public readonly value: {\n    path: string;\n    message: string;\n  };\n\n  constructor(error: TLocalizedValidationError) {\n    super(\n      `Invalid input: ${error.message}${error.instancePath ? ` at ${error.instancePath}` : \"\"}`,\n      {\n        cause: error,\n      },\n    );\n    const params = error.params as TypeBoxErrorParams;\n    if (params?.requiredProperties) {\n      this.value = {\n        path: `/${params.requiredProperties[0]}`,\n        message: \"must be defined\",\n      };\n    } else {\n      this.value = {\n        path: error.instancePath,\n        message: error.message,\n      };\n    }\n\n    this.cause = error;\n  }\n}\n\nexport interface TypeBoxErrorParams {\n  requiredProperties?: string[];\n}\n","import type { TSchema } from \"typebox\";\nimport { Compile, type Validator } from \"typebox/compile\";\nimport { TypeBoxError } from \"../errors/TypeBoxError.ts\";\nimport { $hook } from \"../primitives/$hook.ts\";\nimport { type Static, t, Value } from \"./TypeProvider.ts\";\n\nexport class SchemaValidator {\n  protected cache = new Map<TSchema, Validator>();\n  protected useEval: boolean = true;\n\n  /**\n   * Validate the value against the provided schema.\n   *\n   * Validation create a new value by applying some preprocessing. (e.g., trimming text)\n   */\n  public validate<T extends TSchema>(\n    schema: T,\n    value: unknown,\n    options: ValidateOptions = {},\n  ): Static<T> {\n    const newValue = this.beforeParse(schema, value, {\n      trim: options.trim ?? true,\n      nullToUndefined: options.nullToUndefined ?? true,\n      deleteUndefined: options.deleteUndefined ?? true,\n    });\n\n    try {\n      //\n      if (!this.useEval) {\n        return Value.Parse(schema, newValue);\n      }\n      return this.getValidator(schema).Parse(newValue) as Static<T>;\n    } catch (error: any) {\n      if (error.cause?.errors?.[0]) {\n        throw new TypeBoxError(error.cause.errors[0]);\n      }\n      throw error;\n    }\n  }\n\n  protected getValidator<T extends TSchema>(schema: T): Validator<{}, T> {\n    if (this.cache.has(schema)) {\n      return this.cache.get(schema) as Validator<{}, T>;\n    }\n\n    const validator = Compile(schema);\n    this.cache.set(schema, validator);\n    return validator as Validator<{}, T>;\n  }\n\n  /**\n   * Preprocess the value based on the schema before validation.\n   *\n   * - If the value is `null` and the schema does not allow `null`, it converts it to `undefined`.\n   * - If the value is a string and the schema has a `~options.trim` flag, it trims whitespace from the string.\n   */\n  public beforeParse(schema: any, value: any, options: ValidateOptions): any {\n    if (!schema) {\n      return value;\n    }\n\n    if (\n      value === null &&\n      !this.isSchemaNullable(schema) &&\n      options.nullToUndefined\n    ) {\n      return undefined;\n    }\n\n    if (Array.isArray(value)) {\n      return value.map((it) => this.beforeParse(schema.items, it, options));\n    }\n\n    if (typeof value === \"string\" && schema.type === \"string\") {\n      let str = value;\n\n      if (options.trim && schema[\"~options\"]?.trim) {\n        str = str.trim();\n      }\n\n      if (schema[\"~options\"]?.lowercase) {\n        str = str.toLowerCase();\n      }\n\n      return str;\n    }\n\n    if (\n      typeof value === \"object\" &&\n      value !== null &&\n      schema.type === \"object\"\n    ) {\n      const obj: any = {};\n\n      for (const key in value) {\n        const newValue = this.beforeParse(\n          schema.properties?.[key],\n          value[key],\n          options,\n        );\n\n        if (newValue === undefined && options.deleteUndefined) {\n          continue;\n        }\n\n        obj[key] = newValue;\n      }\n\n      return obj;\n    }\n\n    return value;\n  }\n\n  /**\n   * Used by `beforeParse` to determine if a schema allows null values.\n   */\n  protected isSchemaNullable = (schema: any): boolean => {\n    if (!schema) {\n      return false;\n    }\n    if (schema.type === \"null\") {\n      return true;\n    }\n    if (Array.isArray(schema.type) && schema.type.includes(\"null\")) {\n      return true;\n    }\n    if (schema.anyOf) {\n      return schema.anyOf.some((it: any) => this.isSchemaNullable(it));\n    }\n    if (schema.oneOf) {\n      return schema.oneOf.some((it: any) => this.isSchemaNullable(it));\n    }\n    if (schema.allOf) {\n      return schema.allOf.some((it: any) => this.isSchemaNullable(it));\n    }\n    return false;\n  };\n\n  protected onConfigure = $hook({\n    on: \"configure\",\n    handler: () => {\n      this.useEval = this.canEval();\n    },\n  });\n\n  protected canEval(): boolean {\n    try {\n      Compile(t.object({ test: t.string() })).Parse({ test: \"value\" });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n}\n\nexport interface ValidateOptions {\n  trim?: boolean;\n  nullToUndefined?: boolean;\n  deleteUndefined?: boolean;\n}\n","import type { StaticEncode, TSchema } from \"typebox\";\nimport { AlephaError } from \"../errors/AlephaError.ts\";\nimport { $inject } from \"../primitives/$inject.ts\";\nimport { JsonSchemaCodec } from \"./JsonSchemaCodec.ts\";\nimport { KeylessJsonSchemaCodec } from \"./KeylessJsonSchemaCodec.ts\";\nimport type { SchemaCodec } from \"./SchemaCodec.ts\";\nimport { SchemaValidator, type ValidateOptions } from \"./SchemaValidator.ts\";\nimport type { Static } from \"./TypeProvider.ts\";\n\nexport type Encoding = \"object\" | \"string\" | \"binary\";\n\nexport interface EncodeOptions<T extends Encoding = Encoding> {\n  /**\n   * The output encoding format:\n   * - 'string': Returns JSON string\n   * - 'binary': Returns Uint8Array (for protobuf, msgpack, etc.)\n   *\n   * @default \"string\"\n   */\n  as?: T;\n\n  /**\n   * The encoder to use (e.g., 'json', 'protobuf', 'msgpack')\n   *\n   * @default \"json\"\n   */\n  encoder?: string;\n\n  /**\n   * Validation options to apply before encoding.\n   */\n  validation?: ValidateOptions | false;\n}\n\nexport type EncodeResult<\n  T extends TSchema,\n  E extends Encoding,\n> = E extends \"string\"\n  ? string\n  : E extends \"binary\"\n    ? Uint8Array\n    : StaticEncode<T>;\n\nexport interface DecodeOptions {\n  /**\n   * The encoder to use (e.g., 'json', 'protobuf', 'msgpack')\n   *\n   * @default \"json\"\n   */\n  encoder?: string;\n\n  /**\n   * Validation options to apply before encoding.\n   */\n  validation?: ValidateOptions | false;\n}\n\n/**\n * CodecManager manages multiple codec formats and provides a unified interface\n * for encoding and decoding data with different formats.\n */\nexport class CodecManager {\n  protected readonly codecs: Map<string, SchemaCodec> = new Map();\n  protected readonly jsonCodec = $inject(JsonSchemaCodec);\n  protected readonly keylessCodec = $inject(KeylessJsonSchemaCodec);\n  protected readonly schemaValidator = $inject(SchemaValidator);\n\n  public default = \"json\";\n\n  constructor() {\n    // Register default JSON codec\n    this.register({\n      name: \"json\",\n      codec: this.jsonCodec,\n      default: true,\n    });\n\n    // Register keyless JSON codec (smaller, faster decoding)\n    this.register({\n      name: \"keyless\",\n      codec: this.keylessCodec,\n    });\n  }\n\n  /**\n   * Register a new codec format.\n   */\n  public register(opts: CodecRegisterOptions): void {\n    this.codecs.set(opts.name, opts.codec);\n    if (opts.default) {\n      this.default = opts.name;\n    }\n  }\n\n  /**\n   * Get a specific codec by name.\n   *\n   * @param name - The name of the codec\n   * @returns The codec instance\n   * @throws {AlephaError} If the codec is not found\n   */\n  public getCodec(name: string): SchemaCodec {\n    const codec = this.codecs.get(name);\n    if (!codec) {\n      throw new AlephaError(\n        `Codec \"${name}\" not found. Available codecs: ${Array.from(this.codecs.keys()).join(\", \")}`,\n      );\n    }\n    return codec;\n  }\n\n  /**\n   * Encode data using the specified codec and output format.\n   */\n  public encode<T extends TSchema, E extends Encoding = \"object\">(\n    schema: T,\n    value: unknown,\n    options?: EncodeOptions<E>,\n  ): EncodeResult<T, E> {\n    const codec = this.getCodec(options?.encoder ?? this.default);\n    const as = options?.as ?? \"object\";\n\n    if (options?.validation !== false) {\n      value = this.schemaValidator.validate(schema, value, options?.validation);\n    }\n\n    if (as === \"object\") {\n      // Return the validated object as-is\n      return value as EncodeResult<T, E>;\n    }\n\n    if (as === \"binary\") {\n      // not used by JSON, but for other codecs like Protobuf, MsgPack, etc.\n      return codec.encodeToBinary(schema, value as Static<T>) as EncodeResult<\n        T,\n        E\n      >;\n    }\n\n    // encode directly to string\n    return codec.encodeToString(schema, value as Static<T>) as EncodeResult<\n      T,\n      E\n    >;\n  }\n\n  /**\n   * Decode data using the specified codec.\n   */\n  public decode<T extends TSchema>(\n    schema: T,\n    data: any,\n    options?: DecodeOptions,\n  ): Static<T> {\n    const encoderName = options?.encoder ?? this.default;\n    const codec = this.getCodec(encoderName);\n    let value = codec.decode(schema, data);\n\n    if (options?.validation !== false) {\n      value = this.schemaValidator.validate(schema, value, options?.validation);\n    }\n\n    return value as Static<T>;\n  }\n\n  /**\n   * Validate decoded data against the schema.\n   *\n   * This is automatically called before encoding or after decoding.\n   */\n  public validate<T extends TSchema>(\n    schema: T,\n    value: unknown,\n    options?: ValidateOptions,\n  ): Static<T> {\n    return this.schemaValidator.validate(schema, value, options);\n  }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface CodecRegisterOptions {\n  name: string;\n  codec: SchemaCodec;\n  default?: boolean;\n}\n","import type { Hook, Hooks } from \"../Alepha.ts\";\nimport { AlephaError } from \"../errors/AlephaError.ts\";\nimport type { Async } from \"../interfaces/Async.ts\";\nimport type { LoggerInterface } from \"../interfaces/LoggerInterface.ts\";\nimport type { Service } from \"../interfaces/Service.ts\";\n\n/**\n * Compiled event executor - optimized for hot paths.\n * Returns void for sync-only chains, Promise<void> for chains with async hooks.\n */\nexport type CompiledEventExecutor<T extends keyof Hooks> = (\n  payload: Hooks[T],\n) => void | Promise<void>;\n\n/**\n * Options for compiled event executors.\n */\nexport interface CompileOptions {\n  /**\n   * If true, errors will be caught and logged instead of throwing.\n   * @default false\n   */\n  catch?: boolean;\n}\n\nexport class EventManager {\n  public logFn?: () => LoggerInterface | undefined;\n\n  /**\n   * Three-list storage for hooks, split by priority tier.\n   */\n  protected events: Record<\n    string,\n    { first: Array<Hook>; normal: Array<Hook>; last: Array<Hook> }\n  > = {};\n\n  /**\n   * Cache of compiled executors, auto-built on first emit per event.\n   */\n  protected cache = new Map<string, CompiledEventExecutor<any>>();\n\n  /**\n   * Cache of resolved (topo-sorted) hook arrays per event.\n   */\n  protected sortedCache = new Map<string, Array<Hook>>();\n\n  constructor(logFn?: () => LoggerInterface | undefined) {\n    this.logFn = logFn;\n  }\n\n  protected get log(): LoggerInterface | undefined {\n    return this.logFn?.();\n  }\n\n  public clear(): void {\n    this.events = {};\n    this.cache.clear();\n    this.sortedCache.clear();\n  }\n\n  /**\n   * Registers a hook for the specified event.\n   */\n  public on<T extends keyof Hooks>(\n    event: T,\n    hookOrFunc: Hook<T> | ((payload: Hooks[T]) => Async<void>),\n  ): () => void {\n    if (!this.events[event]) {\n      this.events[event] = { first: [], normal: [], last: [] };\n    }\n\n    const hook =\n      typeof hookOrFunc === \"function\" ? { callback: hookOrFunc } : hookOrFunc;\n\n    const lists = this.events[event];\n\n    if (hook.priority === \"first\") {\n      lists.first.push(hook);\n    } else if (hook.priority === \"last\") {\n      lists.last.push(hook);\n    } else {\n      lists.normal.push(hook);\n    }\n\n    this.invalidateCache(event as string);\n\n    return () => {\n      const lists = this.events[event];\n      if (!lists) return;\n      for (const key of [\"first\", \"normal\", \"last\"] as const) {\n        lists[key] = lists[key].filter((it) => it.callback !== hook.callback);\n      }\n      this.invalidateCache(event as string);\n    };\n  }\n\n  protected invalidateCache(event: string): void {\n    this.cache.delete(event);\n    this.cache.delete(`${event}:catch`);\n    this.sortedCache.delete(event);\n  }\n\n  /**\n   * Resolves the final ordered hook list for an event.\n   * Applies topological sort (Kahn's algorithm) within each priority tier\n   * based on before/after constraints.\n   */\n  protected resolve(event: string): Array<Hook> {\n    const cached = this.sortedCache.get(event);\n    if (cached) return cached;\n\n    const lists = this.events[event];\n    if (!lists) return [];\n\n    const sorted = [\n      ...this.topoSort(lists.first),\n      ...this.topoSort(lists.normal),\n      ...this.topoSort(lists.last),\n    ];\n\n    this.sortedCache.set(event, sorted);\n    return sorted;\n  }\n\n  /**\n   * Topological sort using Kahn's algorithm.\n   * Hooks with no constraints maintain registration order (stable).\n   */\n  protected topoSort(hooks: Array<Hook>): Array<Hook> {\n    if (hooks.length <= 1) return hooks;\n\n    // Check if any hook has constraints — skip sort if none\n    const hasConstraints = hooks.some(\n      (h) =>\n        (h.before && h.before.length > 0) || (h.after && h.after.length > 0),\n    );\n    if (!hasConstraints) return hooks;\n\n    // Build adjacency: edge from A → B means A must run before B\n    const inDegree = new Map<Hook, number>();\n    const adjacency = new Map<Hook, Set<Hook>>();\n\n    for (const hook of hooks) {\n      inDegree.set(hook, 0);\n      adjacency.set(hook, new Set());\n    }\n\n    // Build a map from service class → hooks in this list owned by that service\n    const serviceToHooks = new Map<Service, Array<Hook>>();\n    for (const hook of hooks) {\n      if (hook.caller) {\n        let arr = serviceToHooks.get(hook.caller);\n        if (!arr) {\n          arr = [];\n          serviceToHooks.set(hook.caller, arr);\n        }\n        arr.push(hook);\n      }\n    }\n\n    // \"after: [ServiceA]\" means this hook runs after ServiceA's hooks → edge from ServiceA's hooks → this hook\n    for (const hook of hooks) {\n      if (hook.after) {\n        for (const dep of hook.after) {\n          const depHooks = serviceToHooks.get(dep);\n          if (depHooks) {\n            for (const depHook of depHooks) {\n              if (depHook !== hook && !adjacency.get(depHook)!.has(hook)) {\n                adjacency.get(depHook)!.add(hook);\n                inDegree.set(hook, inDegree.get(hook)! + 1);\n              }\n            }\n          }\n        }\n      }\n\n      // \"before: [ServiceB]\" means this hook runs before ServiceB's hooks → edge from this hook → ServiceB's hooks\n      if (hook.before) {\n        for (const dep of hook.before) {\n          const depHooks = serviceToHooks.get(dep);\n          if (depHooks) {\n            for (const depHook of depHooks) {\n              if (depHook !== hook && !adjacency.get(hook)!.has(depHook)) {\n                adjacency.get(hook)!.add(depHook);\n                inDegree.set(depHook, inDegree.get(depHook)! + 1);\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Kahn's algorithm with stable ordering (registration order as tiebreaker)\n    const queue: Array<Hook> = [];\n    for (const hook of hooks) {\n      if (inDegree.get(hook)! === 0) {\n        queue.push(hook);\n      }\n    }\n\n    const result: Array<Hook> = [];\n    while (queue.length > 0) {\n      const hook = queue.shift()!;\n      result.push(hook);\n\n      for (const neighbor of adjacency.get(hook)!) {\n        const deg = inDegree.get(neighbor)! - 1;\n        inDegree.set(neighbor, deg);\n        if (deg === 0) {\n          queue.push(neighbor);\n        }\n      }\n    }\n\n    if (result.length !== hooks.length) {\n      throw new AlephaError(\n        \"Circular dependency detected in hook before/after constraints\",\n      );\n    }\n\n    return result;\n  }\n\n  /**\n   * Compiles an event into an optimized executor function.\n   *\n   * Called automatically by emit() on first use. Can also be called\n   * manually for direct access to the executor.\n   */\n  public compile<T extends keyof Hooks>(\n    event: T,\n    options: CompileOptions = {},\n  ): CompiledEventExecutor<T> {\n    const hooks = this.resolve(event as string);\n\n    if (hooks.length === 0) {\n      return () => {};\n    }\n\n    const catchErrors = options.catch ?? false;\n    const log = this.log;\n\n    // Once the first async hook is encountered, all remaining hooks\n    // must run in this async continuation to preserve sequential ordering\n    const runRemainingAsync = async (\n      startIndex: number,\n      payload: Hooks[T],\n    ): Promise<void> => {\n      for (let i = startIndex; i < hooks.length; i++) {\n        const hook = hooks[i];\n        try {\n          const result = hook.callback(payload);\n          if (result && typeof result === \"object\" && \"then\" in result) {\n            if (catchErrors) {\n              await (result as Promise<void>).catch((error) => {\n                log?.error(\n                  `${String(event)}(${hook.caller?.name ?? \"unknown\"}) ERROR`,\n                  error,\n                );\n              });\n            } else {\n              await result;\n            }\n          }\n        } catch (error) {\n          if (catchErrors) {\n            log?.error(\n              `${String(event)}(${hook.caller?.name ?? \"unknown\"}) ERROR`,\n              error,\n            );\n          } else {\n            throw error;\n          }\n        }\n      }\n    };\n\n    // Run sync hooks synchronously. On first async hook, switch to\n    // runRemainingAsync and return the Promise. If all hooks are sync,\n    // returns void (no Promise allocation).\n    return (payload: Hooks[T]): void | Promise<void> => {\n      for (let i = 0; i < hooks.length; i++) {\n        const hook = hooks[i];\n        try {\n          const result = hook.callback(payload);\n          if (result && typeof result === \"object\" && \"then\" in result) {\n            if (catchErrors) {\n              return (result as Promise<void>)\n                .catch((error) => {\n                  log?.error(\n                    `${String(event)}(${hook.caller?.name ?? \"unknown\"}) ERROR`,\n                    error,\n                  );\n                })\n                .then(() => runRemainingAsync(i + 1, payload));\n            }\n            return (result as Promise<void>).then(() =>\n              runRemainingAsync(i + 1, payload),\n            );\n          }\n        } catch (error) {\n          if (catchErrors) {\n            log?.error(\n              `${String(event)}(${hook.caller?.name ?? \"unknown\"}) ERROR`,\n              error,\n            );\n          } else {\n            throw error;\n          }\n        }\n      }\n    };\n  }\n\n  /**\n   * Emits the specified event with the given payload.\n   *\n   * Auto-compiles and caches an optimized executor on first call per event.\n   * Use `{ log: true }` for startup events that need timing information.\n   */\n  public async emit<T extends keyof Hooks>(\n    event: T,\n    payload: Hooks[T],\n    options: {\n      /**\n       * If true, the hooks will be logged with their execution time.\n       *\n       * @default false\n       */\n      log?: boolean;\n      /**\n       * If true, errors will be caught and logged instead of throwing.\n       *\n       * @default false\n       */\n      catch?: boolean;\n    } = {},\n  ): Promise<void> {\n    // Fast path: auto-compiled executor\n    if (!options.log) {\n      const cacheKey = options.catch\n        ? `${event as string}:catch`\n        : (event as string);\n      let executor = this.cache.get(cacheKey);\n      if (!executor) {\n        executor = this.compile(event, { catch: options.catch });\n        this.cache.set(cacheKey, executor);\n      }\n      await executor(payload);\n      return;\n    }\n\n    // Slow path with logging (startup only)\n    const events = this.resolve(event as string);\n    if (events.length === 0) return;\n\n    const now = performance.now();\n    this.log?.trace(`${String(event)} ...`);\n\n    for (const hook of events) {\n      const name = hook.caller?.name ?? \"unknown\";\n      const hookStart = performance.now();\n      this.log?.trace(`${String(event)}(${name}) ...`);\n\n      try {\n        const result = hook.callback(payload);\n        if (result && typeof result === \"object\" && \"then\" in result) {\n          await result;\n        }\n      } catch (error) {\n        if (options.catch) {\n          this.log?.error(`${String(event)}(${name}) ERROR`, error);\n          continue;\n        }\n        throw new AlephaError(\n          `Failed during '${String(event)}()' hook for service: ${name}`,\n          { cause: error },\n        );\n      }\n\n      this.log?.debug(\n        `${String(event)}(${name}) OK [${(performance.now() - hookStart).toFixed(1)}ms]`,\n      );\n    }\n\n    this.log?.debug(\n      `${String(event)} OK [${(performance.now() - now).toFixed(1)}ms]`,\n    );\n  }\n}\n","import type { TArray } from \"typebox\";\nimport { KIND } from \"../constants/KIND.ts\";\nimport type {\n  Static,\n  TObject,\n  TOptionalAdd,\n} from \"../providers/TypeProvider.ts\";\n\n/**\n * Define an atom for state management.\n *\n * Atom lets you define a piece of state with a name, schema, and default value.\n *\n * By default, Alepha state is just a simple key-value store.\n * Using atoms allows you to have type safety, validation, and default values for your state.\n *\n * You control how state is structured and validated.\n *\n * Features:\n * - Set a schema for validation\n * - Set a default value for initial state\n * - Rules, like read-only, custom validation, etc.\n * - Automatic getter access in services with {@link $use}\n * - SSR support (server state automatically serialized and hydrated on client)\n * - React integration (useAtom hook for automatic component re-renders)\n * - Middleware\n * - Persistence adapters (localStorage, Redis, database, file system, cookie, etc.)\n * - State migrations (version upgrades when schema changes)\n * - Documentation generation & devtools integration\n *\n * Common use cases:\n * - user preferences\n * - feature flags\n * - configuration options\n * - session data\n *\n * Atom must contain only serializable data.\n * Avoid storing complex objects like class instances, functions, or DOM elements.\n * If you need to store complex data, consider using identifiers or references instead.\n */\nexport const $atom = <\n  T extends TObject<TProperties> | TArray,\n  N extends string,\n>(\n  options: AtomOptions<T, N>,\n): Atom<T, N> => {\n  return new Atom<T, N>(options);\n};\n\nexport type AtomOptions<T extends TAtomObject, N extends string> = {\n  name: N;\n  schema: T;\n  description?: string;\n} & (T extends TOptionalAdd<T>\n  ? {\n      default?: Static<T>;\n    }\n  : {\n      default: Static<T>;\n    });\n\nexport class Atom<T extends TAtomObject = TObject, N extends string = string> {\n  public readonly options: AtomOptions<T, N>;\n\n  public get schema(): T {\n    return this.options.schema;\n  }\n\n  public get key(): N {\n    return this.options.name;\n  }\n\n  constructor(options: AtomOptions<T, N>) {\n    this.options = options;\n  }\n}\n\n$atom[KIND] = \"atom\";\n\ntype TProperties = any; // it's required to avoid required [ string ] error, ...\n\nexport type TAtomObject = TObject<any> | TArray;\nexport type AtomStatic<T extends TAtomObject> =\n  T extends TOptionalAdd<T> ? Static<T> | undefined : Static<T>;\n","import type { TObject } from \"typebox\";\nimport type { State as AlephaState } from \"../Alepha.ts\";\nimport {\n  Atom,\n  type AtomStatic,\n  type TAtomObject,\n} from \"../primitives/$atom.ts\";\nimport { $inject } from \"../primitives/$inject.ts\";\nimport { AlsProvider, type StateScope } from \"./AlsProvider.ts\";\nimport { EventManager } from \"./EventManager.ts\";\nimport { JsonSchemaCodec } from \"./JsonSchemaCodec.ts\";\nimport type { Static } from \"./TypeProvider.ts\";\n\nexport interface AtomWithValue {\n  atom: Atom;\n  value: unknown;\n}\n\nexport class StateManager<State extends object = AlephaState> {\n  protected readonly als = $inject(AlsProvider);\n  protected readonly events = $inject(EventManager);\n  protected readonly codec = $inject(JsonSchemaCodec);\n  protected readonly atoms = new Map<keyof State, Atom>();\n\n  protected store: Partial<State> = {};\n\n  constructor(store: Partial<State> = {}) {\n    this.store = store;\n  }\n\n  /**\n   * Export all registered atoms as a plain object.\n   *\n   * @param scope - Controls which store layer to read from:\n   *   - `undefined` (default): Resolved value (walks fork tree then app store).\n   *   - `\"current\"`: Only the current ALS layer — intentionally does NOT walk\n   *     the parent chain so that SSR serialisation captures exactly what the\n   *     current request set, without leaking parent-fork state.\n   *   - `\"app\"`: Only the root (app-level) store.\n   */\n  public exportAtoms(scope?: \"current\" | \"app\"): Record<string, unknown> {\n    const exported: Record<string, unknown> = {};\n\n    if (scope === \"current\") {\n      if (this.als?.exists()) {\n        for (const atom of this.atoms.values()) {\n          const value = this.als.get(atom.key, \"current\");\n          if (value !== undefined) {\n            exported[atom.key as string] = value;\n          }\n        }\n      }\n      return exported;\n    }\n\n    for (const [key, atom] of this.atoms.entries()) {\n      const value = this.get(atom, scope);\n      if (value !== undefined) {\n        exported[key as string] = value;\n      }\n    }\n\n    return exported;\n  }\n\n  public getAtoms(context = true): Array<AtomWithValue> {\n    const atoms: Array<AtomWithValue> = [];\n\n    if (context && this.als?.exists()) {\n      // for each this.atoms, check if key is present in als, if yes, add to new map\n      for (const atom of this.atoms.values()) {\n        const value = this.als.get(atom.key);\n        if (value !== undefined) {\n          atoms.push({ atom, value });\n        }\n      }\n    } else {\n      for (const [key, atom] of this.atoms.entries()) {\n        atoms.push({ atom, value: this.store[key] as unknown });\n      }\n    }\n\n    return atoms;\n  }\n\n  public register(atom: Atom<any>): this {\n    const key = atom.key as keyof State;\n\n    if (!this.atoms.has(key)) {\n      this.atoms.set(key, atom);\n      if (!(key in this.store)) {\n        this.set(key, atom.options.default as State[keyof State], {\n          skipContext: true,\n        });\n      }\n    }\n\n    return this;\n  }\n\n  /**\n   * Get a value from the state with proper typing.\n   *\n   * @param scope - Optional scope to control resolution:\n   *   - `undefined` (default): Walk up the fork tree from current layer to root, then fall back to the app store.\n   *   - `\"current\"`: Read only from the current fork layer (no tree walking).\n   *   - `\"parent\"`: Read only from the immediate parent fork layer.\n   *   - `\"app\"`: Read only from the root (app-level) store.\n   */\n  public get<T extends TAtomObject>(\n    target: Atom<T>,\n    scope?: StateScope,\n  ): Static<T>;\n  public get<Key extends keyof State>(\n    target: Key,\n    scope?: StateScope,\n  ): State[Key] | undefined;\n  public get(target: string | object, scope?: StateScope): any {\n    if (target instanceof Atom) {\n      this.register(target);\n    }\n\n    const key = target instanceof Atom ? target.key : target;\n    const store = this.store as Record<string, any>;\n\n    if (scope === \"app\") {\n      return store[key];\n    }\n\n    return this.als?.exists()\n      ? (this.als.get(key as string, scope) ?? (scope ? undefined : store[key]))\n      : store[key];\n  }\n\n  /**\n   * Set a value in the state\n   */\n  public set<T extends TAtomObject>(\n    target: Atom<T>,\n    value: AtomStatic<T>,\n    options?: SetStateOptions,\n  ): this;\n  public set<Key extends keyof State>(\n    target: Key,\n    value: State[Key] | undefined,\n    options?: SetStateOptions,\n  ): this;\n  public set(target: any, value: any, options?: SetStateOptions): this {\n    if (target instanceof Atom) {\n      this.register(target);\n    }\n\n    const key = target instanceof Atom ? target.key : target;\n    const store = this.store as Record<string, any>;\n\n    const prevValue = this.get(key);\n    if (prevValue === value) {\n      return this;\n    }\n\n    if (options?.skipContext !== true && this.als?.exists()) {\n      this.als.set(key as string, value);\n    } else {\n      store[key] = value;\n    }\n\n    if (options?.skipEvents !== true) {\n      this.events\n        ?.emit(\n          \"state:mutate\",\n          { key: key as keyof AlephaState, value, prevValue },\n          { catch: true },\n        )\n        .catch(() => null);\n    }\n\n    return this;\n  }\n\n  /**\n   * Mutate a value in the state.\n   */\n  public mut<T extends TObject>(\n    target: Atom<T>,\n    mutator: (current: Static<T>) => Static<T>,\n  ): this;\n  public mut<Key extends keyof State>(\n    target: Key,\n    mutator: (current: State[Key] | undefined) => State[Key] | undefined,\n  ): this;\n  public mut(target: any, mutator: (current: any) => any): this {\n    const current = this.get(target);\n    const updated = mutator(current);\n    return this.set(target, updated);\n  }\n\n  /**\n   * Check if a key exists in the state.\n   * Walks the ALS fork tree when inside a fork context.\n   */\n  public has<Key extends keyof State>(key: Key): boolean {\n    if (this.als?.has(key as string)) {\n      return true;\n    }\n    return key in this.store;\n  }\n\n  /**\n   * Delete a key from the state (set to undefined)\n   */\n  public del<Key extends keyof State>(key: Key): this {\n    return this.set(key, undefined);\n  }\n\n  /**\n   * Push a value to an array in the state\n   */\n  public push<Key extends keyof OnlyArray<State>>(\n    key: Key,\n    ...value: Array<NonNullable<State[Key]> extends Array<infer U> ? U : never>\n  ): this {\n    const current = (this.get(key) ?? []) as Array<any>; // default to empty array\n    if (Array.isArray(current)) {\n      this.set(key, [...current, ...value] as State[Key]);\n    }\n    return this;\n  }\n\n  /**\n   * Clear all state\n   */\n  public clear(): this {\n    this.store = {};\n    return this;\n  }\n\n  /**\n   * Get all keys that exist in the state\n   */\n  public keys(): (keyof State)[] {\n    return Object.keys(this.store) as (keyof State)[];\n  }\n}\n\ntype OnlyArray<T extends object> = {\n  [K in keyof T]: NonNullable<T[K]> extends Array<any> ? K : never;\n};\n\nexport interface SetStateOptions {\n  skipContext?: boolean;\n  skipEvents?: boolean;\n}\n","import type { Record, Static, TObject } from \"typebox\";\nimport { KIND } from \"./constants/KIND.ts\";\nimport { MODULE } from \"./constants/MODULE.ts\";\nimport { OPTIONS } from \"./constants/OPTIONS.ts\";\nimport { AlephaError } from \"./errors/AlephaError.ts\";\nimport { CircularDependencyError } from \"./errors/CircularDependencyError.ts\";\nimport { ContainerLockedError } from \"./errors/ContainerLockedError.ts\";\nimport { TooLateSubstitutionError } from \"./errors/TooLateSubstitutionError.ts\";\nimport { Primitive } from \"./helpers/primitive.ts\";\nimport { __alephaRef } from \"./helpers/ref.ts\";\nimport type { Async } from \"./interfaces/Async.ts\";\nimport type { LoggerInterface } from \"./interfaces/LoggerInterface.ts\";\nimport {\n  type InstantiableClass,\n  isClass,\n  type RunFunction,\n  type Service,\n  type ServiceEntry,\n} from \"./interfaces/Service.ts\";\nimport type { Atom, AtomStatic, TAtomObject } from \"./primitives/$atom.ts\";\nimport type { InjectOptions } from \"./primitives/$inject.ts\";\nimport { Module, type WithModule } from \"./primitives/$module.ts\";\nimport { AlsProvider, type StateScope } from \"./providers/AlsProvider.ts\";\nimport { CodecManager } from \"./providers/CodecManager.ts\";\nimport { EventManager } from \"./providers/EventManager.ts\";\nimport { StateManager } from \"./providers/StateManager.ts\";\nimport type { TSchema } from \"./providers/TypeProvider.ts\";\n\n/**\n * Core container of the Alepha framework.\n *\n * It is responsible for managing the lifecycle of services,\n * handling dependency injection,\n * and providing a unified interface for the application.\n *\n * @example\n * ```ts\n * import { Alepha, run } from \"alepha\";\n *\n * class MyService {\n *   // business logic here\n * }\n *\n * const alepha = Alepha.create({\n *   // state, env, and other properties\n * })\n *\n * alepha.with(MyService);\n *\n * run(alepha); // trigger .start (and .stop) automatically\n * ```\n *\n * ### Alepha Factory\n *\n * Alepha.create() is an enhanced version of new Alepha().\n * - It merges `process.env` with the provided state.env when available.\n * - It populates the test hooks for Vitest or Jest environments when available.\n *\n * new Alepha() is fine if you don't need these helpers.\n *\n * ### Platforms & Environments\n *\n * Alepha is designed to work in various environments:\n * - **Browser**: Runs in the browser, using the global `window` object.\n * - **Serverless**: Runs in serverless environments like Vercel or Vite.\n * - **Test**: Runs in test environments like Jest or Vitest.\n * - **Production**: Runs in production environments, typically with NODE_ENV set to \"production\".\n * * You can check the current environment using the following methods:\n *\n * - `isBrowser()`: Returns true if the App is running in a browser environment.\n * - `isServerless()`: Returns true if the App is running in a serverless environment.\n * - `isTest()`: Returns true if the App is running in a test environment.\n * - `isProduction()`: Returns true if the App is running in a production environment.\n *\n * ### State & Environment\n *\n * The state of the Alepha container is stored in the `store` property.\n * Most important property is `store.env`, which contains the environment variables.\n *\n * ```ts\n * const alepha = Alepha.create({ env: { MY_VAR: \"value\" } });\n *\n * // You can access the environment variables using alepha.env\n * console.log(alepha.env.MY_VAR); // \"value\"\n *\n * // But you should use $env() primitive to get typed values from the environment.\n * class App {\n *   env = $env(\n *     t.object({\n *  \t   MY_VAR: t.text(),\n *     })\n *   );\n * }\n * ```\n *\n * ### Modules\n *\n * Modules are a way to group services together.\n * You can register a module using the `$module` primitive.\n *\n * ```ts\n * import { $module } from \"alepha\";\n *\n * class MyLib {}\n *\n * const myModule = $module({\n *   name: \"my.project.module\",\n *   services: [MyLib],\n * });\n * ```\n *\n * Do not use modules for small applications.\n *\n * ### Hooks\n *\n * Hooks are a way to run async functions from all registered providers/services.\n * You can register a hook using the `$hook` primitive.\n *\n * ```ts\n * import { $hook } from \"alepha\";\n *\n * class App {\n * \t log = $logger();\n * \t onCustomerHook = $hook({\n * \t\t\ton: \"my:custom:hook\",\n * \t\t\thandler: () => {\n * \t\t \t  this.log?.info(\"App is being configured\");\n * \t \t\t},\n * \t  });\n * \t}\n *\n * Alepha.create()\n * \t .with(App)\n * \t .start()\n * \t .then(alepha => alepha.events.emit(\"my:custom:hook\"));\n * ```\n *\n * \tHooks are fully typed. You can create your own hooks by using module augmentation:\n *\n * \t```ts\n * \tdeclare module \"alepha\" {\n * \t\tinterface Hooks {\n * \t\t  \"my:custom:hook\": {\n * \t\t\t\targ1: string;\n * \t\t  }\n * \t\t}\n * \t}\n * \t```\n *\n * \t@module alepha\n */\nexport class Alepha {\n  /**\n   * Creates a new instance of the Alepha container with some helpers:\n   *\n   * - merges `process.env` with the provided state.env when available.\n   * - populates the test hooks for Vitest or Jest environments when available.\n   *\n   * If you are not interested about these helpers, you can use the constructor directly.\n   */\n  public static create(state: Partial<State> = {}): Alepha {\n    // merge process.env with the state.env\n    if (typeof process === \"object\" && typeof process.env === \"object\") {\n      state.env = {\n        ...process.env,\n        ...state.env,\n      };\n    }\n\n    // force production mode when building with vite\n    if (typeof process === \"object\" && process.env?.NODE_ENV === \"production\") {\n      state.env ??= {};\n      Object.assign(state.env, {\n        NODE_ENV: \"production\",\n      });\n    }\n\n    const alepha = new Alepha(state);\n\n    if (alepha.isTest()) {\n      // inject global hooks for testing purposes\n      // > for vitest, { globals: true } is required in the config\n      const g = globalThis as any;\n      const beforeAll = state[\"alepha.test.beforeAll\"] ?? g.beforeAll;\n      const afterAll = state[\"alepha.test.afterAll\"] ?? g.afterAll;\n      const afterEach = state[\"alepha.test.afterEach\"] ?? g.afterEach;\n      const onTestFinished =\n        state[\"alepha.test.onTestFinished\"] ?? g.onTestFinished;\n\n      beforeAll?.(() => alepha.start());\n      afterAll?.(() => alepha.stop());\n\n      try {\n        onTestFinished?.(() => alepha.stop());\n      } catch (_error) {\n        // ignore\n      }\n\n      alepha.store\n        .set(\"alepha.test.beforeAll\", beforeAll)\n        .set(\"alepha.test.afterAll\", afterAll)\n        .set(\"alepha.test.afterEach\", afterEach)\n        .set(\"alepha.test.onTestFinished\", onTestFinished);\n    } else {\n      state[\"alepha.logger\"] ??= {\n        trace: console.log,\n        debug: console.debug,\n        info: console.log,\n        warn: console.warn,\n        error: console.error,\n      };\n    }\n\n    return alepha;\n  }\n\n  /**\n   * Flag indicating whether the App won't accept any further changes.\n   * Pass to true when #start() is called.\n   */\n  protected locked = false;\n\n  /**\n   * True if the App has been configured.\n   */\n  protected configured = false;\n\n  /**\n   * True if the App has started.\n   */\n  protected started = false;\n\n  /**\n   * True if the App is ready.\n   */\n  protected ready = false;\n\n  /**\n   * A promise that resolves when the App has started.\n   */\n  protected starting?: PromiseWithResolvers<this>;\n\n  /**\n   * During the instantiation process, we keep a list of pending instantiations.\n   * > It allows us to detect circular dependencies.\n   */\n  protected pendingInstantiations: Service[] = [];\n\n  /**\n   * Cache for environment variables.\n   * > It allows us to avoid parsing the same schema multiple times.\n   */\n  protected cacheEnv: Map<TSchema, any> = new Map();\n\n  /**\n   * List of modules that are registered in the container.\n   *\n   * Modules are used to group services and provide a way to register them in the container.\n   */\n  protected modules: Array<Module> = [];\n\n  /**\n   * List of service substitutions.\n   *\n   * Services registered here will be replaced by the specified service when injected.\n   */\n  protected substitutions = new Map<Service, { use: Service }>();\n\n  /**\n   * Registry of primitives.\n   */\n  protected primitiveRegistry = new Map<Service<Primitive>, Array<Primitive>>();\n\n  /**\n   *  List of all services + how they are provided.\n   */\n  protected registry: Map<Service, ServiceDefinition> = new Map();\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Node.js feature that allows to store context across asynchronous calls.\n   *\n   * This is used for logging, tracing, and other context-related features.\n   *\n   * Mocked for browser environments.\n   */\n  public context: AlsProvider;\n\n  /**\n   * Event manager to handle lifecycle events and custom events.\n   */\n  public events: EventManager;\n\n  /**\n   * State manager to store arbitrary values.\n   */\n  public store: StateManager<State>;\n\n  /**\n   * Codec manager for encoding and decoding data with different formats.\n   *\n   * Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface.\n   */\n  public codec: CodecManager;\n\n  /**\n   * Get logger instance.\n   */\n  public get log(): LoggerInterface | undefined {\n    return this.store.get(\"alepha.logger\");\n  }\n\n  /**\n   * The environment variables for the App.\n   */\n  public get env(): Readonly<Env> {\n    return this.store.get(\"env\") ?? {};\n  }\n\n  constructor(state: Partial<State> = {}) {\n    this.store = this.inject(StateManager, {\n      args: [state],\n    });\n    this.events = this.inject(EventManager);\n    this.events.logFn = () => this.log;\n    this.context = this.inject(AlsProvider);\n    this.codec = this.inject(CodecManager);\n  }\n\n  public fork<R>(callback: () => R, data: Record<string, any> = {}): R {\n    return this.context.run(callback, data);\n  }\n\n  public get<T extends TAtomObject>(\n    target: Atom<T>,\n    scope?: StateScope,\n  ): Static<T>;\n  public get<Key extends keyof State>(\n    target: Key,\n    scope?: StateScope,\n  ): State[Key] | undefined;\n  public get(target: any, scope?: StateScope): any {\n    return this.store.get(target, scope);\n  }\n\n  public set<T extends TAtomObject>(\n    target: Atom<T>,\n    value: AtomStatic<T>,\n  ): this;\n  public set<Key extends keyof State>(\n    target: Key,\n    value: State[Key] | undefined,\n  ): this;\n  public set(target: any, value: any): this {\n    this.store.set(target, value);\n    return this;\n  }\n\n  /**\n   * True when start() is called.\n   *\n   * -> No more services can be added, it's over, bye!\n   */\n  public isLocked(): boolean {\n    return this.locked;\n  }\n\n  /**\n   * Returns whether the App is configured.\n   *\n   * It means that Alepha#configure() has been called.\n   *\n   * > By default, configure() is called automatically when start() is called, but you can also call it manually.\n   */\n  public isConfigured(): boolean {\n    return this.configured;\n  }\n\n  /**\n   * Returns whether the App has started.\n   *\n   * It means that #start() has been called but maybe not all services are ready.\n   */\n  public isStarted(): boolean {\n    return this.started;\n  }\n\n  /**\n   * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.\n   */\n  public isReady(): boolean {\n    return this.ready;\n  }\n\n  /**\n   * True if the App is running in a Continuous Integration environment.\n   */\n  public isCI(): boolean {\n    if (this.env.GITHUB_ACTIONS) {\n      return true;\n    }\n\n    return !!this.env.CI;\n  }\n\n  /**\n   * True if the App is running in a browser environment.\n   */\n  public isBrowser(): boolean {\n    return typeof window !== \"undefined\"; // pretty cheap check\n  }\n\n  /**\n   * Returns whether the App is running in Vite dev mode.\n   */\n  public isViteDev(): boolean {\n    if (this.isBrowser()) {\n      return false;\n    }\n\n    return !!this.env.VITE_ALEPHA_DEV;\n  }\n\n  /**\n   * Returns whether the App is running in Bun.js environment.\n   */\n  public isBun(): boolean {\n    return \"Bun\" in globalThis;\n  }\n\n  /**\n   * Returns whether the App is running in a serverless environment.\n   */\n  public isServerless(): boolean {\n    if (this.isBrowser()) {\n      return false;\n    }\n\n    if (this.env.ALEPHA_SERVERLESS) {\n      return true;\n    }\n\n    // Vercel support\n    if (this.env.VERCEL_REGION) {\n      return true;\n    }\n\n    // Cloudflare Workers support\n    if (\n      typeof global === \"object\" &&\n      typeof (global as any).Cloudflare === \"object\"\n    ) {\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Returns whether the App is in test mode. (Running in a test environment)\n   *\n   * > This is automatically set when running tests with Jest or Vitest.\n   */\n  public isTest(): boolean {\n    const env = this.env.NODE_ENV;\n    return env === \"test\";\n  }\n\n  /**\n   * Returns whether the App is in production mode. (Running in a production environment)\n   *\n   * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.\n   */\n  public isProduction(): boolean {\n    const env = this.env.NODE_ENV;\n    return env === \"production\";\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Starts the App.\n   *\n   * - Lock any further changes to the container.\n   * - Run \"configure\" hook for all services. Primitives will be processed.\n   * - Run \"start\" hook for all services. Providers will connect/listen/...\n   * - Run \"ready\" hook for all services. This is the point where the App is ready to serve requests.\n   *\n   * @return A promise that resolves when the App has started.\n   */\n  public async start(): Promise<this> {\n    if (this.ready) {\n      this.log?.debug(\"App is already started, skipping...\");\n      return this;\n    }\n\n    // make sure that start is called only once\n    if (this.starting) {\n      this.log?.warn(\"App is already starting, waiting for it to finish...\");\n      return this.starting.promise;\n    }\n\n    this.starting = Promise.withResolvers();\n\n    try {\n      const now = performance.now();\n\n      this.log?.info(\"Starting App...\");\n\n      for (const [key] of this.substitutions.entries()) {\n        this.inject(key);\n      }\n\n      const target = this.store.get(\"alepha.target\");\n      if (target) {\n        this.store.set(\"alepha.target\", undefined);\n        this.modules = [];\n        this.registry = new Map();\n        this.primitiveRegistry = new Map();\n        this.pendingInstantiations = [];\n        this.events.clear();\n        delete (target as any)[MODULE];\n        this.with(target);\n        for (const [key] of this.substitutions.entries()) {\n          this.inject(key);\n        }\n      }\n\n      this.locked = true;\n\n      await this.events.emit(\"configure\", this, { log: true });\n\n      this.configured = true;\n\n      await this.events.emit(\"start\", this, { log: true });\n\n      this.started = true;\n\n      await this.events.emit(\"ready\", this, { log: true });\n\n      this.log?.info(\n        `App is now ready [${Math.round(performance.now() - now)}ms]`,\n      );\n\n      this.ready = true;\n    } catch (error) {\n      this.starting.reject(error);\n      const promise = this.starting.promise;\n      this.starting = undefined;\n      return promise;\n    }\n\n    this.starting.resolve(this);\n    this.starting = undefined;\n\n    return this;\n  }\n\n  /**\n   * Stops the App.\n   *\n   * - Run \"stop\" hook for all services.\n   *\n   * Stop will NOT reset the container.\n   * Stop will NOT unlock the container.\n   *\n   * > Stop is used to gracefully shut down the application, nothing more. There is no \"restart\".\n   *\n   * @return A promise that resolves when the App has stopped.\n   */\n  public async stop(): Promise<void> {\n    if (!this.started) {\n      return;\n    }\n\n    this.log?.info(\"Stopping App...\");\n    await this.events.emit(\"stop\", this, { log: true });\n    this.log?.info(\"App is now off\");\n\n    this.started = false;\n    this.ready = false;\n  }\n\n  /**\n   * Destroys the App and clears all internal state.\n   *\n   * Use this for HMR in development mode to prevent duplicate class registrations.\n   * Unlike stop(), this method fully resets the container state.\n   *\n   * @return A promise that resolves when the App has been destroyed.\n   */\n  public async destroy(): Promise<void> {\n    await this.stop();\n\n    // Clear all internal state to prevent duplicate classes on HMR reload\n    this.modules = [];\n    this.registry = new Map();\n    this.primitiveRegistry = new Map();\n    this.pendingInstantiations = [];\n    this.substitutions = new Map();\n    this.cacheEnv = new Map();\n    this.events.clear();\n\n    // Reset flags\n    this.locked = false;\n    this.configured = false;\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Check if entry is registered in the container.\n   */\n  public has(\n    entry: ServiceEntry,\n    opts: {\n      /**\n       * Check if the entry is registered in the pending instantiation stack.\n       *\n       * @default true\n       */\n      inStack?: boolean;\n      /**\n       * Check if the entry is registered in the container registry.\n       *\n       * @default true\n       */\n      inRegistry?: boolean;\n      /**\n       * Check if the entry is registered in the substitutions.\n       *\n       * @default true\n       */\n      inSubstitutions?: boolean;\n      /**\n       * Where to look for registered services.\n       *\n       * @default this.registry\n       */\n      registry?: Map<Service, ServiceDefinition>;\n    } = {},\n  ): boolean {\n    if (entry === Alepha) {\n      return true;\n    }\n\n    const {\n      inStack = true,\n      inRegistry = true,\n      inSubstitutions = true,\n      registry = this.registry,\n    } = opts;\n\n    const { provide } =\n      typeof entry === \"object\" && \"provide\" in entry\n        ? entry\n        : { provide: entry };\n\n    if (inSubstitutions) {\n      const substitute = this.substitutions.get(provide);\n      if (substitute) {\n        return true;\n      }\n    }\n\n    if (inRegistry) {\n      const match = registry.get(provide);\n      if (match) {\n        return true;\n      }\n    }\n\n    if (inStack) {\n      const substitute = this.substitutions.get(provide)?.use;\n      if (substitute && this.pendingInstantiations.includes(substitute)) {\n        return true;\n      }\n\n      return this.pendingInstantiations.includes(provide);\n    }\n\n    return false;\n  }\n\n  /**\n   * Registers the specified service in the container.\n   *\n   * - If the service is ALREADY registered, the method does nothing.\n   * - If the service is NOT registered, a new instance is created and registered.\n   *\n   * Method is chainable, so you can register multiple services in a single call.\n   *\n   * > ServiceEntry allows to provide a service **substitution** feature.\n   *\n   * @example\n   * ```ts\n   * class A { value = \"a\"; }\n   * class B { value = \"b\"; }\n   * class M { a = $inject(A); }\n   *\n   * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // \"b\"\n   * ```\n   *\n   * > **Substitution** is an advanced feature that allows you to replace a service with another service.\n   * > It's useful for testing or for providing different implementations of a service.\n   * > If you are interested in configuring a service, use Alepha#configure() instead.\n   *\n   * @param serviceEntry - The service to register in the container.\n   * @return Current instance of Alepha.\n   */\n  public with<T extends object>(\n    serviceEntry: ServiceEntry<T> | { default: ServiceEntry<T> },\n  ): this {\n    // Early cutoff: if a $mode already claimed the target, skip further registrations.\n    // The target's own dependencies are resolved via $inject during its constructor.\n    if (this.store?.get(\"alepha.target\")) {\n      return this;\n    }\n\n    const entry: ServiceEntry<T> =\n      \"default\" in serviceEntry ? serviceEntry.default : serviceEntry;\n\n    // just check if the entry is not present in the pending instantiation stack\n    // Alepha#get will handle the rest\n    if (\n      this.has(entry, {\n        inSubstitutions: false,\n        inRegistry: false,\n      })\n    ) {\n      return this;\n    }\n\n    const isSubstitution = typeof entry === \"object\";\n    if (isSubstitution) {\n      if (entry.provide === entry.use) {\n        this.inject(entry.provide);\n        return this;\n      }\n\n      if (!this.substitutions.has(entry.provide) && !this.has(entry.provide)) {\n        if (this.started) {\n          throw new ContainerLockedError();\n        }\n\n        // inherit of module, if service has no module\n        if (\n          MODULE in entry.provide &&\n          typeof entry.provide[MODULE] === \"function\"\n        ) {\n          (entry.use as WithModule)[MODULE] ??= entry.provide[MODULE];\n        }\n\n        this.substitutions.set(entry.provide, {\n          use: entry.use,\n        });\n      } else if (!entry.optional) {\n        throw new TooLateSubstitutionError(entry.provide.name, entry.use.name);\n      }\n\n      return this;\n    }\n\n    this.inject(entry);\n\n    return this;\n  }\n\n  /**\n   * Get an instance of the specified service from the container.\n   *\n   * @see {@link InjectOptions} for the available options.\n   */\n  public inject<T extends object>(\n    service: Service<T> | string,\n    opts: InjectOptions<T> = {},\n  ): T {\n    const lifetime = opts.lifetime ?? \"singleton\";\n    const parent =\n      opts.parent !== undefined ? opts.parent : (__alephaRef?.parent ?? Alepha);\n\n    const transient = lifetime === \"transient\";\n    const registry =\n      lifetime === \"scoped\"\n        ? (this.context.get<Map<Service, ServiceDefinition>>(\"registry\") ??\n          this.registry)\n        : this.registry;\n\n    // If the requested type is the container, the current instance is returned.\n    if ((service as any) === Alepha) {\n      return this as any;\n    }\n\n    if (typeof service === \"string\") {\n      for (const [key, value] of registry.entries()) {\n        if (key.name === service) {\n          return value.instance as T;\n        }\n      }\n      throw new AlephaError(`Service not found: ${service}`);\n    }\n\n    const substitute = this.substitutions.get(service);\n    if (substitute) {\n      return this.inject(substitute.use, {\n        parent,\n        lifetime,\n      });\n    }\n\n    const index = this.pendingInstantiations.indexOf(service);\n    if (index !== -1 && !transient) {\n      throw new CircularDependencyError(\n        service.name,\n        this.pendingInstantiations.slice(0, index).map((it) => it.name),\n      );\n    }\n\n    if (!transient) {\n      // the requested type is searched in the container\n      const match = registry.get(service);\n      if (match) {\n        if (!match.parents.includes(parent) && parent !== service) {\n          match.parents.push(parent);\n        }\n\n        return match.instance;\n      }\n\n      if (this.started) {\n        const mod = (service as WithModule)[MODULE]?.name;\n        throw new ContainerLockedError(\n          `Container is locked. No more services can be added. Attempted to inject '${service.name}' from '${parent?.name}'. ${mod ? `Module '${mod}' is not registered ?` : \"\"}`,\n        );\n      }\n    }\n\n    const module = (service as WithModule)[MODULE];\n    if (module && typeof module === \"function\") {\n      this.with(module);\n    }\n\n    // check if service has been registered by a module\n    if (this.has(service, { registry }) && !transient) {\n      // if the service is already registered, we just return the instance\n      return this.inject(service, { parent, lifetime });\n    }\n\n    const instance: T = this.new(service, opts.args);\n\n    const definition: ServiceDefinition<T> = {\n      parents: [parent],\n      instance,\n    };\n\n    if (!transient) {\n      registry.set(service, definition);\n    }\n\n    // [feature]: modules - it's just a way to group services together\n    if (instance instanceof Module) {\n      this.modules.push(instance);\n\n      const parent = __alephaRef.parent;\n\n      // propagate the current module\n      __alephaRef.parent = instance.constructor as Service;\n\n      instance.register(this);\n\n      // restore the previous $get context\n      __alephaRef.parent = parent;\n    }\n\n    return instance;\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Applies environment variables to the provided schema and state object.\n   *\n   * It replaces also all templated $ENV inside string values.\n   *\n   * @param schema - The schema object to apply environment variables to.\n   * @return The schema object with environment variables applied.\n   */\n  public parseEnv<T extends TObject>(schema: T): Static<T> {\n    if (this.cacheEnv.has(schema)) {\n      return this.cacheEnv.get(schema) as Static<T>;\n    }\n\n    const config = this.codec.validate(schema, this.env) as Record<string, any>;\n\n    for (const key in config) {\n      if (typeof config[key] === \"string\") {\n        for (const env in config) {\n          config[key] = (config[key] as string).replaceAll(\n            `$${env}`,\n            String(config[env] ?? \"\"),\n          );\n        }\n      }\n    }\n\n    this.cacheEnv.set(schema, config);\n\n    return config as Static<T>;\n  }\n\n  /**\n   * Get all environment variable schemas and their parsed values.\n   *\n   * This is useful for DevTools to display all expected environment variables.\n   */\n  public getEnvSchemas(): Array<{\n    schema: TSchema;\n    values: Record<string, any>;\n  }> {\n    const result: Array<{ schema: TSchema; values: Record<string, any> }> = [];\n    for (const [schema, values] of this.cacheEnv.entries()) {\n      result.push({ schema, values });\n    }\n    return result;\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * Dump the current dependency graph of the App.\n   *\n   * This method returns a record where the keys are the names of the services.\n   */\n  public graph(): Record<\n    string,\n    { from: string[]; as?: string[]; module?: string }\n  > {\n    for (const [key] of this.substitutions.entries()) {\n      if (!this.has(key)) {\n        this.inject(key);\n      }\n    }\n\n    const graph: Record<\n      string,\n      { from: string[]; as?: string[]; module?: string }\n    > = {};\n\n    for (const [provide, { parents }] of this.registry.entries()) {\n      if (provide.name === \"\") {\n        // ignore anonymous classes\n        continue;\n      }\n\n      if (Module.is(provide)) {\n        continue;\n      }\n\n      graph[provide.name] = {\n        from: parents.filter((it) => !!it).map((it) => it.name),\n      };\n\n      const aliases = this.substitutions\n        .entries()\n        .filter((it) => it[1].use === provide)\n        .map((it) => it[0].name)\n        .toArray();\n\n      if (aliases.length) {\n        graph[provide.name].as = aliases;\n      }\n\n      const module = Module.of(provide);\n      if (module) {\n        graph[provide.name].module = module.name;\n      }\n    }\n\n    return graph;\n  }\n\n  public dump(): AlephaDump {\n    const env: Record<string, AlephaDumpEnvVariable> = {};\n    for (const [schema] of this.cacheEnv.entries()) {\n      const ref = schema as any;\n      for (const [key, value] of Object.entries(ref.properties)) {\n        const prop = value as any;\n        env[key] = {\n          description: prop.description,\n          default: prop.default,\n          required: ref.required?.includes(key) ?? undefined,\n          enum: prop.enum ? ([...prop.enum] as Array<string>) : undefined,\n        };\n      }\n    }\n\n    return {\n      env,\n      providers: this.graph(),\n    };\n  }\n\n  public services<T extends object>(base: Service<T>): Array<T> {\n    const list: Array<T> = [];\n    for (const [key, value] of this.registry.entries()) {\n      if (value.instance instanceof base) {\n        list.push(value.instance as T);\n      }\n    }\n    return list;\n  }\n\n  /**\n   * Get all primitives of the specified type.\n   */\n  public primitives<TPrimitive extends Primitive>(\n    factory:\n      | {\n          [KIND]: InstantiableClass<TPrimitive>;\n        }\n      | string,\n  ): Array<TPrimitive> {\n    if (typeof factory === \"string\") {\n      const key1 = factory.toLowerCase().replace(\"$\", \"\");\n      const key2 = `${key1}primitive`;\n      for (const [key, value] of this.primitiveRegistry.entries()) {\n        const name = key.name.toLowerCase();\n        if (name === key1 || name === key2) {\n          return value as Array<TPrimitive>;\n        }\n      }\n      return [];\n    }\n    return (this.primitiveRegistry.get(factory[KIND]) ??\n      []) as Array<TPrimitive>;\n  }\n\n  // -------------------------------------------------------------------------------------------------------------------\n\n  protected new<T extends object>(service: Service<T>, args: any[] = []): T {\n    // we keep a tree of dependencies to detect circular dependencies\n    // it's also useful for cleaning are global cursor\n    this.pendingInstantiations.push(service);\n\n    //\n    // we use a global cursor to store the current context and definition\n    // as new() is synchronous, there is no worry to do that\n    //\n    __alephaRef.alepha = this;\n    __alephaRef.service = service;\n\n    const instance: T = isClass(service)\n      ? new service(...args)\n      : (((service as RunFunction)(...args) ?? {}) as T);\n\n    const obj = instance as unknown as Record<string, any>;\n    for (const [key, value] of Object.entries(obj)) {\n      if (value instanceof Primitive) {\n        this.processPrimitive(value, key);\n      }\n      if (\n        typeof value === \"object\" &&\n        value !== null &&\n        typeof value[OPTIONS] === \"object\" &&\n        \"getter\" in value[OPTIONS]\n      ) {\n        const getter = value[OPTIONS].getter as keyof State;\n        Object.defineProperty(obj, key, {\n          get: () => this.store.get(getter),\n        });\n      }\n    }\n\n    this.pendingInstantiations.pop();\n\n    // tree is empty, now we can clean the global cursor\n    if (this.pendingInstantiations.length === 0) {\n      __alephaRef.alepha = undefined;\n    }\n\n    __alephaRef.service =\n      this.pendingInstantiations[this.pendingInstantiations.length - 1];\n\n    return instance;\n  }\n\n  protected processPrimitive(value: Primitive, propertyKey = \"\") {\n    value.config.propertyKey = propertyKey;\n    (value as any).onInit();\n\n    const kind = value.constructor as Service;\n    const existing = this.primitiveRegistry.get(kind);\n    if (existing) {\n      existing.push(value);\n    } else {\n      this.primitiveRegistry.set(kind, [value]);\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface Hook<T extends keyof Hooks = any> {\n  caller?: Service;\n  priority?: \"first\" | \"last\";\n  before?: Service[];\n  after?: Service[];\n  callback: (payload: Hooks[T]) => Async<void>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface AlephaDump {\n  env: Record<string, AlephaDumpEnvVariable>;\n  providers: Record<string, { from: string[]; as?: string[]; module?: string }>;\n}\n\nexport interface AlephaDumpEnvVariable {\n  description: string;\n  default?: string;\n  required?: boolean;\n  enum?: Array<string>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * This is how we store services in the Alepha container.\n */\ninterface ServiceDefinition<T extends object = any> {\n  /**\n   * The instance of the class or type definition.\n   * Mostly used for caching / singleton but can be used for other purposes like forcing the instance.\n   */\n  instance: T;\n\n  /**\n   * List of classes which use this class.\n   */\n  parents: Array<Service | null>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface Env {\n  [key: string]: string | boolean | number | undefined;\n\n  /**\n   * Optional environment variable that indicates the current environment.\n   */\n  NODE_ENV?: string;\n\n  /**\n   * Optional name of the application.\n   */\n  APP_NAME?: string;\n\n  /**\n   * Optional root module name.\n   */\n  MODULE_NAME?: string;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface State {\n  [key: string]: unknown;\n\n  /**\n   * Environment variables for the application.\n   */\n  env?: Readonly<Env>;\n\n  /**\n   * Logger instance to be used by the Alepha container.\n   *\n   * @internal\n   */\n  \"alepha.logger\"?: LoggerInterface;\n\n  /**\n   * If defined, the Alepha container will only register this service and its dependencies.\n   *\n   * @example\n   * ```ts\n   * class MigrateCmd {\n   *   db = $inject(DatabaseProvider);\n   *   alepha = $inject(Alepha);\n   *   env = $env(\n   *     t.object({\n   *       MIGRATE: t.optional(t.boolean()),\n   *     }),\n   *   );\n   *\n   *   constructor() {\n   *     if (this.env.MIGRATE) {\n   *       this.alepha.set(\"alepha.target\", MigrateCmd);\n   *     }\n   *   }\n   *\n   *   ready = $hook({\n   *     on: \"ready\",\n   *     handler: async () => {\n   *       if (this.env.MIGRATE) {\n   *         await this.db.migrate();\n   *       }\n   *     },\n   *   });\n   * }\n   * ```\n   */\n  \"alepha.target\"?: Service;\n\n  // test hooks\n\n  /**\n   * Bind to Vitest 'beforeAll' hook.\n   * Used for testing purposes.\n   * This is automatically attached if Alepha#create() detects a test environment and global 'beforeAll' is available.\n   */\n  \"alepha.test.beforeAll\"?: (run: any) => any;\n\n  /**\n   * Bind to Vitest 'afterAll' hook.\n   * Used for testing purposes.\n   * This is automatically attached if Alepha#create() detects a test environment and global 'afterAll' is available.\n   */\n  \"alepha.test.afterAll\"?: (run: any) => any;\n\n  /**\n   * Bind to Vitest 'afterEach' hook.\n   * Used for testing purposes.\n   * This is automatically attached if Alepha#create() detects a test environment and global 'afterEach' is available.\n   */\n  \"alepha.test.afterEach\"?: (run: any) => any;\n\n  /**\n   * Bind to Vitest 'onTestFinished' hook.\n   * Used for testing purposes.\n   * This is automatically attached if Alepha#create() detects a test environment and global 'onTestFinished' is available.\n   */\n  \"alepha.test.onTestFinished\"?: (run: any) => any;\n\n  /**\n   * List of static assets to be copied to the output directory during the build process.\n   *\n   * Used for Alepha-based applications that require static assets.\n   *\n   * See cli/services/ViteUtils for more details.\n   */\n  \"alepha.build.assets\"?: Array<string>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface Hooks {\n  /**\n   * Used for testing purposes.\n   */\n  echo: unknown;\n\n  /**\n   * Triggered during the configuration phase. Before the start phase.\n   */\n  configure: Alepha;\n\n  /**\n   * Triggered during the start phase. When `Alepha#start()` is called.\n   */\n  start: Alepha;\n\n  /**\n   * Triggered during the ready phase. After the start phase.\n   */\n  ready: Alepha;\n\n  /**\n   * Triggered during the stop phase.\n   *\n   * - Stop should be called after a SIGINT or SIGTERM signal in order to gracefully shutdown the application. (@see `run()` method)\n   *\n   */\n  stop: Alepha;\n\n  /**\n   * Triggered when a state value is mutated.\n   */\n  \"state:mutate\": {\n    /**\n     * The key of the state that was mutated.\n     */\n    key: keyof State;\n\n    /**\n     * The new value of the state.\n     */\n    value: any;\n\n    /**\n     * The previous value of the state.\n     */\n    prevValue: any;\n  };\n}\n","import { AlephaError } from \"./AlephaError.ts\";\n\nexport class AppNotStartedError extends AlephaError {\n  readonly name = \"AppNotStartedError\";\n\n  constructor() {\n    super(\"App not started. Please start the app before.\");\n  }\n}\n","import type { Page } from \"../schemas/pageSchema.ts\";\n\n/**\n * Create a pagination object from an array of entities.\n *\n * This is a pure function that works with any data source (databases, APIs, caches, arrays, etc.).\n * It handles the core pagination logic including:\n * - Slicing the content to the requested page size\n * - Calculating pagination metadata (offset, page number, etc.)\n * - Determining navigation state (isFirst, isLast)\n * - Including sort metadata when provided\n *\n * @param entities - The entities to paginate (should include one extra item to detect if there's a next page)\n * @param limit - The limit of the pagination (page size)\n * @param offset - The offset of the pagination (starting position)\n * @param sort - Optional sort metadata to include in response\n * @returns A complete Page object with content and metadata\n *\n * @example Basic pagination\n * ```ts\n * const users = await fetchUsers({ limit: 11, offset: 0 }); // Fetch limit + 1\n * const page = createPagination(users, 10, 0);\n * // page.content has max 10 items\n * // page.page.isLast tells us if there are more pages\n * ```\n *\n * @example With sorting\n * ```ts\n * const page = createPagination(\n *   entities,\n *   10,\n *   0,\n *   [{ column: \"name\", direction: \"asc\" }]\n * );\n * ```\n *\n * @example In a custom service\n * ```ts\n * class MyService {\n *   async listItems(page: number, size: number) {\n *     const items = await this.fetchItems({ limit: size + 1, offset: page * size });\n *     return createPagination(items, size, page * size);\n *   }\n * }\n * ```\n */\nexport function createPagination<T>(\n  entities: T[],\n  limit = 10,\n  offset = 0,\n  sort?: Array<{ column: string; direction: \"asc\" | \"desc\" }>,\n): Page<T> {\n  const content = entities.slice(0, limit);\n  const hasNext = entities.length === limit + 1;\n  const pageNumber = Math.floor(offset / limit);\n\n  return {\n    content,\n    page: {\n      number: pageNumber,\n      size: limit,\n      offset,\n      numberOfElements: content.length,\n      isEmpty: content.length === 0,\n      isFirst: pageNumber === 0,\n      isLast: !hasNext,\n      ...(sort && sort.length > 0\n        ? {\n            sort: {\n              sorted: true,\n              fields: sort.map((s) => ({\n                field: s.column,\n                direction: s.direction,\n              })),\n            },\n          }\n        : {}),\n    },\n  };\n}\n","import type {\n  TArrayOptions,\n  TNumberOptions,\n  TObjectOptions,\n  TSchema,\n  TStringOptions,\n} from \"typebox\";\nimport { t } from \"../providers/TypeProvider.ts\";\n\n/**\n * JSON Schema representation for conversion to TypeBox.\n */\nexport interface JsonSchemaObject {\n  type?: string | string[];\n  properties?: Record<string, JsonSchemaObject>;\n  required?: string[];\n  items?: JsonSchemaObject;\n  enum?: (string | number | boolean)[];\n  const?: unknown;\n  format?: string;\n  title?: string;\n  description?: string;\n  default?: unknown;\n  minLength?: number;\n  maxLength?: number;\n  minimum?: number;\n  maximum?: number;\n  exclusiveMinimum?: number;\n  exclusiveMaximum?: number;\n  multipleOf?: number;\n  pattern?: string;\n  minItems?: number;\n  maxItems?: number;\n  uniqueItems?: boolean;\n  // Alepha text options (trim, lowercase)\n  \"~options\"?: {\n    trim?: boolean;\n    lowercase?: boolean;\n  };\n  // Not supported\n  oneOf?: JsonSchemaObject[];\n  anyOf?: JsonSchemaObject[];\n  allOf?: JsonSchemaObject[];\n  not?: JsonSchemaObject;\n  $ref?: string;\n}\n\n/**\n * Converts a JSON Schema object to a TypeBox schema using Alepha's type system.\n *\n * This is useful when receiving JSON Schema from an API (e.g., configuration schemas)\n * and needing to use them with TypeBox-based form rendering or validation.\n *\n * **Supports:**\n * - Basic types: string, number, integer, boolean, null, object, array\n * - String formats: email, uuid, date-time, date, time, url/uri, binary, bigint, duration, color\n * - Enums (string enums)\n * - Nested objects with required/optional properties\n * - Arrays with item schemas\n * - Common validation options: minLength, maxLength, minimum, maximum, pattern\n * - anyOf/oneOf/allOf with nullable patterns (e.g., `anyOf: [type, null]` → `t.nullable(type)`)\n * - Alepha ~options (trim, lowercase) pass-through\n *\n * **Not supported:**\n * - $ref (references)\n * - additionalProperties, patternProperties\n * - Complex composition schemas (multiple non-null types in anyOf/oneOf/allOf)\n *\n * @param schema - JSON Schema object to convert\n * @returns TypeBox TSchema\n *\n * @example\n * ```ts\n * const jsonSchema = {\n *   type: \"object\",\n *   properties: {\n *     email: { type: \"string\", format: \"email\" },\n *     age: { type: \"integer\", minimum: 0 },\n *     active: { type: \"boolean\" },\n *   },\n *   required: [\"email\"]\n * };\n *\n * const typeBoxSchema = jsonSchemaToTypeBox(jsonSchema);\n * // Equivalent to:\n * // t.object({\n * //   email: t.email(),\n * //   age: t.optional(t.integer({ minimum: 0 })),\n * //   active: t.optional(t.boolean()),\n * // })\n * ```\n */\nexport function jsonSchemaToTypeBox(schema: JsonSchemaObject): any {\n  // Handle const (literal)\n  if (schema.const !== undefined) {\n    return t.const(schema.const as string | number | boolean);\n  }\n\n  // Handle enum\n  if (schema.enum && Array.isArray(schema.enum)) {\n    // String enum\n    if (schema.enum.every((v) => typeof v === \"string\")) {\n      return t.enum(\n        schema.enum as string[],\n        filterUndefined({\n          title: schema.title,\n          description: schema.description,\n          default: schema.default as string,\n        }),\n      );\n    }\n    // For non-string enums, use union of literals\n    return t.union(\n      schema.enum.map((v) => t.const(v as string | number | boolean)),\n    );\n  }\n\n  // Handle anyOf (typically used for nullable types: anyOf: [type, null])\n  if (schema.anyOf && Array.isArray(schema.anyOf)) {\n    const nullSchema = schema.anyOf.find((s) => s.type === \"null\");\n    const nonNullSchemas = schema.anyOf.filter((s) => s.type !== \"null\");\n\n    // If anyOf is [someType, null], convert to t.nullable(someType)\n    if (nullSchema && nonNullSchemas.length === 1) {\n      const converted = jsonSchemaToTypeBox(nonNullSchemas[0]);\n      return t.nullable(converted);\n    }\n\n    // For other anyOf cases, create a union\n    return t.union(schema.anyOf.map((s) => jsonSchemaToTypeBox(s)));\n  }\n\n  // Handle allOf (merge schemas)\n  if (schema.allOf && Array.isArray(schema.allOf)) {\n    const nullSchema = schema.allOf.find((s) => s.type === \"null\");\n    const nonNullSchemas = schema.allOf.filter((s) => s.type !== \"null\");\n\n    // If allOf includes null, convert to nullable\n    if (nullSchema && nonNullSchemas.length === 1) {\n      const converted = jsonSchemaToTypeBox(nonNullSchemas[0]);\n      return t.nullable(converted);\n    }\n\n    // For other allOf cases, merge the first non-null schema (simplified)\n    if (nonNullSchemas.length > 0) {\n      return jsonSchemaToTypeBox(nonNullSchemas[0]);\n    }\n  }\n\n  // Handle oneOf (similar to anyOf)\n  if (schema.oneOf && Array.isArray(schema.oneOf)) {\n    const nullSchema = schema.oneOf.find((s) => s.type === \"null\");\n    const nonNullSchemas = schema.oneOf.filter((s) => s.type !== \"null\");\n\n    // If oneOf is [someType, null], convert to t.nullable(someType)\n    if (nullSchema && nonNullSchemas.length === 1) {\n      const converted = jsonSchemaToTypeBox(nonNullSchemas[0]);\n      return t.nullable(converted);\n    }\n\n    // For other oneOf cases, create a union\n    return t.union(schema.oneOf.map((s) => jsonSchemaToTypeBox(s)));\n  }\n\n  // Handle type\n  const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;\n\n  switch (type) {\n    case \"string\":\n      return convertString(schema);\n    case \"number\":\n      return convertNumber(schema);\n    case \"integer\":\n      return convertInteger(schema);\n    case \"boolean\":\n      return convertBoolean(schema);\n    case \"null\":\n      return t.null();\n    case \"object\":\n      return convertObject(schema);\n    case \"array\":\n      return convertArray(schema);\n    default:\n      // If no type specified but has properties, treat as object\n      if (schema.properties) {\n        return convertObject(schema);\n      }\n      // Fallback to any\n      return t.any();\n  }\n}\n\n/**\n * Remove undefined values from an object.\n */\nfunction filterUndefined<T extends Record<string, unknown>>(\n  obj: T,\n): Partial<T> {\n  return Object.fromEntries(\n    Object.entries(obj).filter(([_, v]) => v !== undefined),\n  ) as Partial<T>;\n}\n\n/**\n * Convert JSON Schema string type to TypeBox.\n */\nfunction convertString(schema: JsonSchemaObject): TSchema {\n  const baseOptions: TStringOptions = filterUndefined({\n    title: schema.title,\n    description: schema.description,\n    default: schema.default as string,\n    minLength: schema.minLength,\n    maxLength: schema.maxLength,\n    pattern: schema.pattern,\n  });\n\n  // Preserve ~options if present (for t.text() compatibility)\n  const options: TStringOptions = schema[\"~options\"]\n    ? { ...baseOptions, \"~options\": schema[\"~options\"] }\n    : baseOptions;\n\n  switch (schema.format) {\n    case \"email\":\n      return t.email(options);\n    case \"uuid\":\n      return t.uuid(options);\n    case \"date-time\":\n      return t.datetime(options);\n    case \"date\":\n      return t.date(options);\n    case \"time\":\n      return t.time(options);\n    case \"url\":\n    case \"uri\":\n      return t.url(options);\n    case \"binary\":\n      return t.binary(options);\n    case \"bigint\":\n      return t.bigint(options);\n    case \"duration\":\n      return t.duration(options);\n    case \"color\":\n      return t.text({ ...options, format: \"color\" });\n    case \"e164\":\n      return t.e164(options);\n    case \"bcp47\":\n      return t.bcp47(options);\n    default:\n      // For unknown formats, preserve the format in text\n      if (schema.format) {\n        return t.string({ ...options, format: schema.format });\n      }\n      return t.string(options);\n  }\n}\n\n/**\n * Convert JSON Schema number type to TypeBox.\n */\nfunction convertNumber(schema: JsonSchemaObject): TSchema {\n  return t.number(\n    filterUndefined({\n      title: schema.title,\n      description: schema.description,\n      default: schema.default as number,\n      minimum: schema.minimum,\n      maximum: schema.maximum,\n      exclusiveMinimum: schema.exclusiveMinimum,\n      exclusiveMaximum: schema.exclusiveMaximum,\n      multipleOf: schema.multipleOf,\n    }) as TNumberOptions,\n  );\n}\n\n/**\n * Convert JSON Schema integer type to TypeBox.\n */\nfunction convertInteger(schema: JsonSchemaObject): TSchema {\n  return t.integer(\n    filterUndefined({\n      title: schema.title,\n      description: schema.description,\n      default: schema.default as number,\n      minimum: schema.minimum,\n      maximum: schema.maximum,\n      exclusiveMinimum: schema.exclusiveMinimum,\n      exclusiveMaximum: schema.exclusiveMaximum,\n      multipleOf: schema.multipleOf,\n    }) as TNumberOptions,\n  );\n}\n\n/**\n * Convert JSON Schema boolean type to TypeBox.\n */\nfunction convertBoolean(schema: JsonSchemaObject): TSchema {\n  return t.boolean(\n    filterUndefined({\n      title: schema.title,\n      description: schema.description,\n      default: schema.default as boolean,\n    }),\n  );\n}\n\n/**\n * Convert JSON Schema object type to TypeBox.\n */\nfunction convertObject(schema: JsonSchemaObject): TSchema {\n  // No properties means it's a generic object/record\n  if (!schema.properties) {\n    return t.json(\n      filterUndefined({\n        title: schema.title,\n        description: schema.description,\n      }),\n    );\n  }\n\n  const required = new Set(schema.required ?? []);\n  const properties: Record<string, TSchema> = {};\n\n  for (const [key, propSchema] of Object.entries(schema.properties)) {\n    let converted = jsonSchemaToTypeBox(propSchema);\n\n    // Wrap in optional if not required\n    if (!required.has(key)) {\n      converted = t.optional(converted);\n    }\n\n    properties[key] = converted;\n  }\n\n  return t.object(\n    properties,\n    filterUndefined({\n      title: schema.title,\n      description: schema.description,\n    }) as TObjectOptions,\n  );\n}\n\n/**\n * Convert JSON Schema array type to TypeBox.\n */\nfunction convertArray(schema: JsonSchemaObject): TSchema {\n  const itemSchema = schema.items ? jsonSchemaToTypeBox(schema.items) : t.any();\n\n  return t.array(\n    itemSchema,\n    filterUndefined({\n      title: schema.title,\n      description: schema.description,\n      minItems: schema.minItems,\n      maxItems: schema.maxItems,\n      uniqueItems: schema.uniqueItems,\n    }) as TArrayOptions,\n  );\n}\n","import type { Static, TObject } from \"typebox\";\nimport { AlephaError } from \"../errors/AlephaError.ts\";\nimport { t } from \"../providers/TypeProvider.ts\";\nimport { $context } from \"./$context.ts\";\n\n/**\n * Get typed values from environment variables.\n *\n * @example\n * ```ts\n * const alepha = Alepha.create({\n *   env: {\n *     // Alepha.create() will also use process.env when running on Node.js\n *     HELLO: \"world\",\n *   }\n * });\n *\n * class App {\n *   log = $logger();\n *\n *   // program expect a var env \"HELLO\" as string to works\n *   env = $env(t.object({\n *     HELLO: t.text()\n *   }));\n *\n *   sayHello = () => this.log.info(\"Hello ${this.env.HELLO}\")\n * }\n *\n * run(alepha.with(App));\n * ```\n */\nexport const $env = <T extends TObject>(type: T): Static<T> => {\n  const { alepha } = $context();\n\n  // allow to inject TypeBox schemas\n  if (!t.schema.isObject(type)) {\n    throw new AlephaError(\"Type must be an TObject\");\n  }\n\n  return alepha.parseEnv(type) as Static<T>;\n};\n","import { createMiddleware, type Middleware } from \"alepha\";\n\nexport interface MemoizeOptions {\n  /**\n   * Maximum number of entries to keep in the cache.\n   * When exceeded, the oldest entry is evicted (FIFO).\n   *\n   * @default 1000\n   */\n  max?: number;\n\n  /**\n   * Custom key function. Receives the handler's arguments.\n   * By default, `JSON.stringify(args)` is used.\n   */\n  key?: (...args: any[]) => string;\n}\n\n/**\n * Lightweight in-process memoization middleware.\n *\n * Caches handler results in a plain `Map` — no external store, no serialization,\n * no provider dependency. Process-local only. Entries live until eviction by capacity.\n *\n * ```typescript\n * class Api {\n *   getStats = $action({\n *     use: [$memoize({ max: 100 })],\n *     handler: async () => this.repo.aggregate(),\n *   });\n * }\n * ```\n *\n * > For more advanced caching, use `$cache` from \"alepha/cache\" instead — it supports TTL, invalidation, external stores (Redis).\n */\nexport const $memoize = (options?: MemoizeOptions): Middleware => {\n  return createMiddleware({\n    name: \"$memoize\",\n    options: options as unknown as Record<string, unknown>,\n    handler: ({ next }) => {\n      const store = new Map<string, any>();\n      const maxSize = options?.max ?? 1000;\n      const keyFn = options?.key ?? ((...args: any[]) => JSON.stringify(args));\n\n      return async (...args) => {\n        const key = keyFn(...args);\n        if (store.has(key)) {\n          return store.get(key);\n        }\n\n        const result = await next(...args);\n\n        // Evict oldest if at capacity\n        if (store.size >= maxSize) {\n          const firstKey = store.keys().next().value;\n          if (firstKey !== undefined) {\n            store.delete(firstKey);\n          }\n        }\n\n        store.set(key, result);\n\n        return result;\n      };\n    },\n  });\n};\n","import type { Alepha } from \"../Alepha.ts\";\nimport { $context } from \"./$context.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ModeOptions {\n  /**\n   * Environment variable to check for.\n   *\n   * The mode activates when:\n   * - The env variable is truthy (e.g. `MIGRATE=true`), OR\n   * - The `MODE` env equals this value (e.g. `MODE=MIGRATE`)\n   *\n   * @example \"MIGRATE\"\n   * @example \"SEED\"\n   * @example \"CONSOLE\"\n   */\n  env: string;\n\n  /**\n   * Callback to execute when the mode is activated and the app is ready.\n   *\n   * After the callback completes (or throws), `alepha.stop()` is called automatically\n   * to ensure graceful shutdown (close DB connections, etc.).\n   *\n   * If omitted, the mode activates (graph is pruned) but the process stays alive.\n   * Useful for long-running modes like queue workers or cron.\n   */\n  ready?: (alepha: Alepha) => void | Promise<void>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Activate a selective bootstrap mode.\n *\n * When the environment condition matches, the owning class becomes `alepha.target`:\n * the DI graph is pruned to only this class and its transitive dependencies.\n * Everything else (HTTP server, job scheduler, etc.) is discarded.\n *\n * Returns `true` if the mode is active, `false` otherwise.\n *\n * @example\n * ```ts\n * import { $mode, $inject } from \"alepha\";\n * import { DatabaseProvider } from \"alepha/orm\";\n *\n * class DbMigrationMode {\n *   db = $inject(DatabaseProvider);\n *\n *   mode = $mode({\n *     env: \"MIGRATE\",\n *     ready: async () => {\n *       await this.db.migrate();\n *     },\n *   });\n * }\n * ```\n *\n * ```bash\n * MIGRATE=true node app.js    # runs migrations, then exits\n * MODE=MIGRATE node app.js    # same effect\n * ```\n */\nexport const $mode = (args: ModeOptions): boolean => {\n  const { alepha, service } = $context();\n\n  // Accept MIGRATE=true or MODE=MIGRATE\n  if (alepha.env[args.env] || alepha.env.MODE === args.env) {\n    alepha.set(\"alepha.target\", service);\n\n    if (args.ready) {\n      alepha.events.on(\"ready\", async () => {\n        try {\n          await args.ready!(alepha);\n        } finally {\n          await alepha.stop();\n        }\n      });\n    }\n\n    return true;\n  }\n\n  return false;\n};\n","import type { Alepha } from \"../Alepha.ts\";\nimport { KIND } from \"../constants/KIND.ts\";\nimport { OPTIONS } from \"../constants/OPTIONS.ts\";\nimport { createPrimitive, Primitive } from \"../helpers/primitive.ts\";\nimport { $context } from \"./$context.ts\";\n\n/**\n * Creates a pipeline primitive that composes middleware with a handler.\n *\n * It makes a big function which runs all functions (middleware) inside `use` array before and after the `handler` function.\n * The middleware functions are applied in the order they are defined in the `use` array.\n *\n * So PipelinePrimitive is also a base for primitives with `handler` which need some sort of plugins.\n *\n * Use `$pipeline` for standalone composition outside host primitives (`$action`, `$job`, `$page`).\n * Host primitives extend `PipelinePrimitive` directly to get middleware support.\n *\n * ```ts\n * class OrderService {\n *   processOrder = $pipeline({\n *     use: [$lock({ name: \"process-order\" }), $retry({ max: 3 })],\n *     handler: async (orderId: string) => {\n *       return await this.orders.updateById(orderId, { status: \"paid\" });\n *     },\n *   });\n * }\n * ```\n */\nexport function $pipeline<T extends (...args: any[]) => any>(\n  options: PipelineOptions<T>,\n): PipelinePrimitiveFn<T> {\n  const instance = createPrimitive(PipelinePrimitive, options);\n  const fn = (...args: Parameters<T>): any => instance.run(...args);\n  return Object.setPrototypeOf(fn, instance) as PipelinePrimitiveFn<T>;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport class PipelinePrimitive<\n  TOptions extends PipelinePrimitiveOptions = PipelinePrimitiveOptions,\n> extends Primitive<TOptions> {\n  public readonly handler = new PipelineHandler(\n    this.options.handler,\n    this.options.use,\n  );\n\n  public get middlewares(): MiddlewareMetadata[] {\n    return (this.options.use ?? []).map(\n      (it) => it[OPTIONS] as MiddlewareMetadata,\n    );\n  }\n\n  /**\n   * Execute the wrapped handler.\n   */\n  public run(...args: any[]): any {\n    return this.handler.run(...args);\n  }\n}\n\nexport interface MiddlewareMetadata {\n  name: string;\n  options?: Record<string, unknown>;\n}\n\nexport type Middleware = (<T extends (...args: any[]) => any>(\n  handler: T,\n) => T) & {\n  [OPTIONS]?: MiddlewareMetadata;\n};\n\nexport interface PipelinePrimitiveOptions<\n  THandler extends (...args: any[]) => any = (...args: any[]) => any,\n> {\n  use?: Middleware[];\n  handler: THandler;\n}\n\nexport interface PipelineOptions<\n  T extends (...args: any[]) => any = (...args: any[]) => any,\n> {\n  use: Middleware[];\n  handler: T;\n}\n\nexport interface CreateMiddlewareOptions {\n  name: string;\n  options?: any;\n  handler: (context: {\n    alepha: Alepha;\n    next: (...args: any[]) => any;\n  }) => (...args: any[]) => any;\n}\n\n/**\n * Internal class that composes middleware and the handler function.\n * This is required when adding more middleware dynamically. See `$middleware()`.\n */\nexport class PipelineHandler {\n  protected fn: (...args: any[]) => any;\n  protected middlewares: Middleware[];\n\n  constructor(fn: (...args: any[]) => any, middlewares?: Middleware[]) {\n    this.fn = fn;\n    this.middlewares = middlewares ?? [];\n  }\n\n  protected wrapped?: (...args: any[]) => any;\n\n  public use(...middleware: Middleware[]): void {\n    this.middlewares.unshift(...middleware);\n    this.wrapped = undefined; // reset wrapped function to apply new middleware\n  }\n\n  public run(...args: any[]): any {\n    if (!this.wrapped) {\n      this.wrapped = this.fn;\n      for (let i = this.middlewares.length - 1; i >= 0; i--) {\n        this.wrapped = this.middlewares[i](this.wrapped);\n      }\n    }\n\n    return this.wrapped(...args);\n  }\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport interface PipelinePrimitiveFn<\n  T extends (...args: any[]) => any = (...args: any[]) => any,\n> extends PipelinePrimitive<PipelineOptions<T>> {\n  (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n$pipeline[KIND] = PipelinePrimitive;\n\n// -----------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates a middleware with automatic `$context()` resolution, type handling, and metadata.\n *\n * Eliminates the boilerplate of calling `$context()`, casting types, and attaching\n * `MiddlewareMetadata`. The handler receives `{ alepha, next }` and returns the\n * wrapped function directly.\n *\n * ```typescript\n * export const $logElastic = (options?: LogOptions): Middleware => {\n *   return createMiddleware({\n *     name: \"$logElastic\",\n *     options,\n *     handler: ({ alepha, next }) => {\n *       const elastic = alepha.inject(ElasticProvider);\n *       return async (...args) => {\n *         const result = await next(...args);\n *         elastic.push({ ... }).catch(() => {});\n *         return result;\n *       };\n *     },\n *   });\n * };\n * ```\n */\nexport const createMiddleware = (\n  config: CreateMiddlewareOptions,\n): Middleware => {\n  const { alepha } = $context();\n\n  const mw: Middleware = <T extends (...args: any[]) => any>(handler: T): T =>\n    config.handler({ alepha, next: handler }) as T;\n\n  mw[OPTIONS] =\n    config.options != null\n      ? { name: config.name, options: config.options }\n      : { name: config.name };\n\n  return mw;\n};\n","import { AlephaError } from \"../errors/AlephaError.ts\";\nimport type { Middleware } from \"./$pipeline.ts\";\nimport { createMiddleware } from \"./$pipeline.ts\";\n\n/**\n * Middleware that wraps the handler in an ALS (AsyncLocalStorage) context.\n *\n * Gives the handler its own isolated scope — `alepha.context.get()` / `.set()` are scoped\n * to this execution. Useful for `$pipeline` where no host primitive provides a scope.\n *\n * Host primitives (`$action`, `$job`, `$page`) include `$scope` by default.\n * Adding `$scope()` to their `use` array will throw — you're already in a scope.\n *\n * ```typescript\n * class OrderService {\n *   processOrder = $pipeline({\n *     use: [$scope(), $retry({ max: 3 })],\n *     handler: async (orderId: string) => {\n *       // alepha.context.set/get are scoped here\n *       return await this.orders.updateById(orderId, { status: \"paid\" });\n *     },\n *   });\n * }\n * ```\n */\nexport const $scope = (): Middleware => {\n  return createMiddleware({\n    name: \"$scope\",\n    handler:\n      ({ alepha, next }) =>\n      async (...args) => {\n        if (alepha.context.exists()) {\n          throw new AlephaError(\n            \"$scope: already inside a scope — host primitives ($action, $job, $page) include $scope by default\",\n          );\n        }\n\n        return alepha.context.run(() => next(...args));\n      },\n  });\n};\n","import type { State } from \"../Alepha.ts\";\nimport { OPTIONS } from \"../constants/OPTIONS.ts\";\nimport type { Static, TObject } from \"../providers/TypeProvider.ts\";\nimport type { Atom } from \"./$atom.ts\";\nimport { $context } from \"./$context.ts\";\n\n/**\n * Subscribes to an atom's state and returns its current value for use in components.\n *\n * Creates a reactive connection between an atom and a component, automatically registering\n * the atom in the application state if not already registered. The returned value is reactive\n * and will update when the atom's state changes.\n *\n * **Use Cases**: Accessing global state, sharing data between components, reactive UI updates\n *\n * @example\n * ```ts\n * const userState = $atom({ schema: t.object({ name: t.text(), role: t.text() }) });\n *\n * class UserComponent {\n *   user = $use(userState); // Reactive reference to atom state\n *\n *   render() {\n *     return <div>Hello {this.user.name}!</div>;\n *   }\n * }\n * ```\n */\nexport const $use = <T extends TObject, N extends string>(\n  atom: Atom<T, N>,\n): Readonly<Static<T>> => {\n  const { alepha } = $context();\n\n  // register atom in state if not already registered\n  alepha.store.register(atom);\n\n  const init = alepha.store.get(atom.key as keyof State) as object;\n\n  return {\n    [OPTIONS]: { getter: atom.key }, // alepha will replace this with by a real 'get prop()'\n    ...init,\n  } as Static<T>;\n};\n","import { type Static, t } from \"../providers/TypeProvider.ts\";\n\nexport const pageQuerySchema = t.object({\n  page: t.optional(\n    t.integer({\n      description: \"The page number to retrieve.\",\n      minimum: 0,\n      default: 0,\n    }),\n  ),\n  size: t.optional(\n    t.integer({\n      description: \"The number of items per page.\",\n      minimum: 1,\n      maximum: 100,\n      default: 10,\n    }),\n  ),\n  sort: t.optional(\n    t.text({\n      description:\n        \"Sort by field(s). Multiple columns separated by comma. Prefix with '-' for DESC. Examples: 'name' (ASC), '-createdAt' (DESC), 'role,-name' (role ASC, name DESC)\",\n    }),\n  ),\n});\n\nexport type PageQuery = Static<typeof pageQuerySchema>;\n","import {\n  type Static,\n  type TArray,\n  type TObject,\n  type TObjectOptions,\n  type TRecord,\n  TypeProvider,\n  t,\n} from \"../providers/TypeProvider.ts\";\n\nexport const pageMetadataSchema = t.object({\n  number: t.integer({ description: \"Page number, starting from 0\" }),\n  size: t.integer({\n    description: \"Number of items per page (requested page size)\",\n  }),\n  offset: t.integer({\n    description: \"Offset in the dataset (page × size)\",\n  }),\n  numberOfElements: t.integer({\n    description:\n      \"Number of elements in THIS page (content.length). Different from totalElements which is the total across all pages.\",\n  }),\n  totalElements: t.optional(\n    t.integer({\n      description:\n        \"Total number of elements across all pages. Only available when counting is enabled.\",\n    }),\n  ),\n  totalPages: t.optional(\n    t.integer({\n      description:\n        \"Total number of pages. Only available when `totalElements` is present.\",\n    }),\n  ),\n  isEmpty: t.boolean({\n    description:\n      \"Indicates if the current page has no items (numberOfElements === 0)\",\n  }),\n  isFirst: t.boolean({\n    description: \"Indicates if this is the first page (number === 0)\",\n  }),\n  isLast: t.boolean({\n    description:\n      \"Indicates if this is the last page (no more pages after this)\",\n  }),\n  sort: t.optional(\n    t.object({\n      sorted: t.boolean({\n        description: \"Whether the results are sorted\",\n      }),\n      fields: t.array(\n        t.object({\n          field: t.text({\n            description: \"The field used for sorting\",\n          }),\n          direction: t.enum([\"asc\", \"desc\"], {\n            description: \"The direction of the sort. Either 'asc' or 'desc'\",\n          }),\n        }),\n      ),\n    }),\n  ),\n});\n\n/**\n * Create a pagination schema for the given object schema.\n *\n * Provides a standardized pagination response format compatible with Spring Data's Page interface.\n * This schema can be used across any data source (databases, APIs, caches, etc.).\n *\n * @example\n * ```ts\n * const userSchema = t.object({ id: t.integer(), name: t.text() });\n * const userPageSchema = pageSchema(userSchema);\n * ```\n *\n * @example In an API endpoint\n * ```ts\n * $action({\n *   output: pageSchema(UserSchema),\n *   handler: async () => {\n *     return await userRepo.paginate();\n *   }\n * })\n * ```\n */\nexport const pageSchema = <T extends TObject | TRecord>(\n  objectSchema: T,\n  options?: TObjectOptions,\n): TPage<T> =>\n  t.object(\n    {\n      content: t.array(objectSchema),\n      page: pageMetadataSchema,\n    },\n    options,\n  );\n\nexport type TPage<T extends TObject | TRecord> = TObject<{\n  content: TArray<T>;\n  page: typeof pageMetadataSchema;\n}>;\n\n/**\n * Opinionated type definition for a paginated response.\n *\n * Inspired by Spring Data's Page interface with all essential pagination metadata.\n * This generic type can be used with any data source.\n *\n * @example\n * ```ts\n * const page: Page<User> = {\n *   content: [user1, user2, ...],\n *   page: {\n *     number: 0,\n *     size: 10,\n *     offset: 0,\n *     numberOfElements: 10,\n *     totalElements: 1200,\n *     totalPages: 120,\n *     isEmpty: false,\n *     isFirst: true,\n *     isLast: false,\n *     sort: {\n *       sorted: true,\n *       fields: [\n *         { field: \"name\", direction: \"asc\" }\n *       ]\n *     }\n *   }\n * }\n * ```\n */\nexport type Page<T> = {\n  /**\n   * Array of items on the current page.\n   */\n  content: T[];\n  page: Static<typeof pageMetadataSchema>;\n};\n\nexport type PageMetadata = Static<typeof pageMetadataSchema>;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n  interface TypeProvider {\n    /**\n     * Create a schema for a paginated response.\n     */\n    page<T extends TObject | TRecord>(itemSchema: T): TPage<T>;\n  }\n}\n\nTypeProvider.prototype.page = (itemSchema) => pageSchema(itemSchema);\n","/// <reference types=\"vite/client\" />\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport cluster from \"node:cluster\";\nimport { cpus } from \"node:os\";\nimport { Alepha } from \"./Alepha.ts\";\nimport type { RunOptions } from \"./interfaces/Run.ts\";\nimport type { Service } from \"./interfaces/Service.ts\";\nimport { $module } from \"./primitives/$module.ts\";\nimport { AlsProvider } from \"./providers/AlsProvider.ts\";\nimport { CodecManager } from \"./providers/CodecManager.ts\";\nimport { EventManager } from \"./providers/EventManager.ts\";\nimport { Json } from \"./providers/Json.ts\";\nimport { JsonSchemaCodec } from \"./providers/JsonSchemaCodec.ts\";\nimport { KeylessJsonSchemaCodec } from \"./providers/KeylessJsonSchemaCodec.ts\";\nimport { SchemaCodec } from \"./providers/SchemaCodec.ts\";\nimport { SchemaValidator } from \"./providers/SchemaValidator.ts\";\nimport { StateManager } from \"./providers/StateManager.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./index.shared.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Foundation of the entire framework with dependency injection and lifecycle management.\n *\n * **Features:**\n * - Dependency injection for services\n * - Service substitution/mocking\n * - Type-safe environment variable loading with TypeBox schemas\n * - Lifecycle hooks (start, stop, log, etc.)\n * - Module definitions and composition\n * - Request-scoped context access via Async Local Storage (ALS)\n * - Reactive state management with atoms\n * - Cluster mode with automatic worker forking\n * - Full TypeScript generics and type inference\n *\n * @module alepha.core\n */\nexport const AlephaCore = $module({\n  name: \"alepha.core\",\n  services: [\n    StateManager,\n    CodecManager,\n    EventManager,\n    AlsProvider,\n    Json,\n    JsonSchemaCodec,\n    KeylessJsonSchemaCodec,\n    SchemaCodec,\n    SchemaValidator,\n  ],\n  register: () => {\n    // skip registration, Alepha will handle it\n  },\n});\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Run Alepha application, trigger start lifecycle.\n *\n * ```ts\n * import { Alepha, run } from \"alepha\";\n * import { MyService } from \"./services/MyService.ts\";\n *\n * const alepha = new Alepha({ env: { APP_NAME: \"MyAlephaApp\" } });\n *\n * alepha.with(MyService);\n *\n * export default run(alepha);\n * ```\n */\nexport const run = (\n  entry: Alepha | Service | Array<Service>,\n  opts?: RunOptions,\n): Alepha => {\n  const env: Record<string, string | undefined> =\n    typeof process === \"object\" ? process.env : {};\n\n  const alepha =\n    entry instanceof Alepha\n      ? entry\n      : Alepha.create({ env: { ...env, ...opts?.env } });\n\n  if (!(entry instanceof Alepha)) {\n    const entries = Array.isArray(entry) ? entry : [entry];\n    for (const e of entries) {\n      alepha.with(e);\n    }\n  }\n\n  // make alepha globally accessible (for serverless functions, etc...)\n  // it's not recommended, we should force 'export default run(alepha)'\n  (globalThis as any).__alepha = alepha;\n\n  // when alepha instance is imported via CLI, use a different global variable\n  if (env.ALEPHA_CLI_IMPORT) {\n    (globalThis as any).__cli_alepha = alepha;\n  }\n\n  if (alepha.isServerless() || alepha.isViteDev() || env.ALEPHA_CLI_IMPORT) {\n    return alepha;\n  }\n\n  if (opts?.cluster) {\n    withCluster(entry, opts);\n    return alepha;\n  }\n\n  setTimeout(async () => {\n    try {\n      await opts?.configure?.(alepha);\n\n      await alepha.start();\n\n      if (opts?.ready) {\n        await opts.ready(alepha);\n      }\n\n      if (opts?.once) {\n        await alepha.stop();\n        return alepha;\n      }\n\n      if (typeof process === \"object\") {\n        const traps = [\"SIGTERM\", \"SIGINT\", \"SIGUSR2\", \"uncaughtException\"];\n\n        for (const trap of traps) {\n          process.once(trap, async (err) => {\n            if (trap === \"uncaughtException\") {\n              alepha.log?.error(\"Uncaught Exception\", err);\n            } else {\n              alepha.log?.info(\"Received signal\", { trap });\n            }\n            try {\n              await alepha.stop();\n              console.log(\" \");\n              process.exit(0);\n            } catch (error) {\n              alepha.log?.error(\"Alepha failed to stop\", error);\n              process.exit(1);\n            }\n          });\n        }\n      }\n    } catch (error) {\n      alepha.log?.error(\"Alepha failed to start\", error);\n      if (typeof process === \"object\") {\n        process.exit(1);\n      }\n    }\n  });\n\n  return alepha;\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n// only for node.js environment\nAlsProvider.create = () => new AsyncLocalStorage();\n\n/**\n * Run Alepha in cluster mode, forking workers based on the number of CPU cores.\n */\nconst withCluster = (\n  entry: Alepha | Service | Array<Service>,\n  opts?: RunOptions,\n) => {\n  const numCPUs = cpus().length;\n  if (cluster.isPrimary) {\n    for (let i = 0; i < numCPUs; i++) {\n      cluster.fork();\n    }\n  } else {\n    run(entry, {\n      ...opts,\n      env: {\n        ...opts?.env,\n        APP_NAME: `${opts?.env?.APP_NAME || \"P\"}-${cluster.worker?.id}`,\n      },\n      cluster: false,\n    });\n  }\n};\n"]}