@navios/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +145 -0
  3. package/dist/index.d.mts +425 -0
  4. package/dist/index.d.ts +425 -0
  5. package/dist/index.js +1744 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +1657 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +45 -0
  10. package/src/__tests__/controller.spec.mts +59 -0
  11. package/src/attribute.factory.mts +155 -0
  12. package/src/decorators/controller.decorator.mts +36 -0
  13. package/src/decorators/endpoint.decorator.mts +81 -0
  14. package/src/decorators/index.mts +4 -0
  15. package/src/decorators/module.decorator.mts +47 -0
  16. package/src/decorators/use-guards.decorator.mts +43 -0
  17. package/src/exceptions/bad-request.exception.mts +7 -0
  18. package/src/exceptions/conflict.exception.mts +7 -0
  19. package/src/exceptions/forbidden.exception.mts +7 -0
  20. package/src/exceptions/http.exception.mts +7 -0
  21. package/src/exceptions/index.mts +7 -0
  22. package/src/exceptions/internal-server-error.exception.mts +7 -0
  23. package/src/exceptions/not-found.exception.mts +10 -0
  24. package/src/exceptions/unauthorized.exception.mts +7 -0
  25. package/src/index.mts +10 -0
  26. package/src/interfaces/can-activate.mts +5 -0
  27. package/src/interfaces/index.mts +2 -0
  28. package/src/interfaces/navios-module.mts +3 -0
  29. package/src/metadata/controller.metadata.mts +71 -0
  30. package/src/metadata/endpoint.metadata.mts +69 -0
  31. package/src/metadata/index.mts +4 -0
  32. package/src/metadata/injectable.metadata.mts +11 -0
  33. package/src/metadata/module.metadata.mts +62 -0
  34. package/src/navios.application.mts +113 -0
  35. package/src/navios.factory.mts +17 -0
  36. package/src/service-locator/__tests__/injectable.spec.mts +170 -0
  37. package/src/service-locator/decorators/get-injectable-token.mts +23 -0
  38. package/src/service-locator/decorators/index.mts +2 -0
  39. package/src/service-locator/decorators/injectable.decorator.mts +103 -0
  40. package/src/service-locator/enums/index.mts +1 -0
  41. package/src/service-locator/enums/injectable-scope.enum.mts +10 -0
  42. package/src/service-locator/errors/errors.enum.mts +7 -0
  43. package/src/service-locator/errors/factory-not-found.mts +8 -0
  44. package/src/service-locator/errors/index.mts +6 -0
  45. package/src/service-locator/errors/instance-destroying.mts +8 -0
  46. package/src/service-locator/errors/instance-expired.mts +8 -0
  47. package/src/service-locator/errors/instance-not-found.mts +8 -0
  48. package/src/service-locator/errors/unknown-error.mts +15 -0
  49. package/src/service-locator/event-emitter.mts +107 -0
  50. package/src/service-locator/index.mts +14 -0
  51. package/src/service-locator/inject.mts +37 -0
  52. package/src/service-locator/injection-token.mts +36 -0
  53. package/src/service-locator/injector.mts +18 -0
  54. package/src/service-locator/interfaces/factory.interface.mts +3 -0
  55. package/src/service-locator/override.mts +22 -0
  56. package/src/service-locator/proxy-service-locator.mts +80 -0
  57. package/src/service-locator/service-locator-abstract-factory-context.mts +23 -0
  58. package/src/service-locator/service-locator-event-bus.mts +96 -0
  59. package/src/service-locator/service-locator-instance-holder.mts +63 -0
  60. package/src/service-locator/service-locator-manager.mts +89 -0
  61. package/src/service-locator/service-locator.mts +445 -0
  62. package/src/service-locator/sync-injector.mts +55 -0
  63. package/src/services/controller-adapter.service.mts +124 -0
  64. package/src/services/execution-context.mts +53 -0
  65. package/src/services/guard-runner.service.mts +93 -0
  66. package/src/services/index.mts +4 -0
  67. package/src/services/module-loader.service.mts +68 -0
  68. package/src/tokens/application.token.mts +9 -0
  69. package/src/tokens/execution-context.token.mts +8 -0
  70. package/src/tokens/index.mts +4 -0
  71. package/src/tokens/reply.token.mts +7 -0
  72. package/src/tokens/request.token.mts +9 -0
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Oleksandr Hanzha
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # Navios
2
+
3
+ Navios is a Type-Safe HTTP Server with Zod Validation.
4
+
5
+ It is a powerful tool for building robust and type-safe APIs using TypeScript. It leverages the power of Zod for validation and provides a simple and intuitive API for defining endpoints, request and response schemas, and handling errors.
6
+
7
+ It uses Fastify under the hood, which is a fast and low-overhead web framework for Node.js. This allows Navios to provide high performance and low latency for your APIs.
8
+
9
+ ## Features
10
+
11
+ - **Type Safety**: Navios provides a type-safe API for defining endpoints, request and response schemas. This ensures that your API is always type-safe and reduces the risk of runtime errors.
12
+ - **Validation**: Zod provides powerful validation capabilities, allowing you to define complex validation rules for your data. This ensures that the data you work with is always valid and meets your requirements.
13
+ - **Build with Navios Builder**: Navios Builder is a powerful HTTP client that simplifies API requests. By combining it with Navios, you can use the same API definition for both the client and server, ensuring consistency and reducing duplication.
14
+ - **Declarative API**: The API is designed to be declarative, allowing you to define your API endpoints and their schemas in a clear and concise manner. This makes it easy to understand and maintain your API client.
15
+ - **Customizable**: The package allows you to customize the behavior of the API client, such as using a custom client.
16
+ - **Error Handling**: The package provides built-in error handling capabilities, allowing you to handle API errors gracefully and provide meaningful feedback to users.
17
+
18
+ ## Main Concepts
19
+
20
+ - **Module**: A module is a collection of controllers, and other modules. It is used to group related functionality together and provide a clear structure for your API. It also can define some shared guards and attributes.
21
+ - **Controller**: A controller is a class that defines a set of endpoints for a specific resource. It is used to handle incoming requests and return responses. Controllers can also define guards and attributes that apply to all endpoints in the controller.
22
+ - **Endpoint**: An endpoint is a specific route in your API that handles a specific request. It used original endpoint definition from Navios Builder, and a set of request and response schemas. Endpoints can also define guards and attributes that apply to the endpoint.
23
+ - **Service**: A service is a class that defines the business logic for a specific resource. It is used to separate the business logic from the controller and provide a clear structure for your API.
24
+ - **Guard**: A guard is a class that is used to validate incoming requests and ensure that they meet certain criteria. Guards can be used to validate request parameters, headers, and body. They can also be used to check authentication and authorization.
25
+ - **Attribute**: An attribute is a decorator that is used to add metadata to a class or method. Attributes can be used in guards, controllers, modules, and endpoints to provide additional information about the class or method.
26
+
27
+
28
+ ## Getting Started
29
+
30
+ ### Define your API
31
+
32
+ Define your API in a shared location accessible to both the client and server. This allows you to use the same API definition for both the client and server, ensuring consistency and reducing duplication.
33
+
34
+ ```ts
35
+ import { builder } from '@navios/core'
36
+ import { z } from 'zod'
37
+
38
+ const api = builder({
39
+ useDiscriminatorResponse: true,
40
+ })
41
+
42
+ const login = api.declareEndpoint({
43
+ method: 'post',
44
+ url: '/login',
45
+ requestSchema: z.object({
46
+ email: z.string().email(),
47
+ password: z.string().min(6),
48
+ }),
49
+ responseSchema: z.discriminatedUnion('success', [
50
+ z.object({
51
+ success: z.literal(true),
52
+ user: z.object({
53
+ id: z.string(),
54
+ name: z.string(),
55
+ email: z.string().email(),
56
+ }),
57
+ }),
58
+ z.object({
59
+ success: z.literal(false),
60
+ error: z.string(),
61
+ }),
62
+ ]),
63
+ })
64
+ ```
65
+
66
+ ### Create your server
67
+
68
+ ```bash
69
+ yarn install --save @navios/core @navios/common zod
70
+ ```
71
+
72
+ Create AuthService:
73
+
74
+ ```ts
75
+ import { Injectable } from '@navios/core'
76
+
77
+ @Injectable()
78
+ export class LoginService {
79
+ async login(email: string, password: string) {
80
+ // Perform your login logic here
81
+ // For example, check the email and password against a database
82
+ }
83
+ }
84
+ ```
85
+
86
+ Create your first Controller:
87
+
88
+ ```ts
89
+ import { Controller, Endpoint, type EndpointParams, syncInject } from '@navios/core'
90
+
91
+ import { AuthService } from './auth.service.mjs'
92
+
93
+ @Controller()
94
+ export class AuthController {
95
+ // Inject the LoginService
96
+ loginService = syncInject(LoginService)
97
+
98
+ @Endpoint(login)
99
+ async login(request: EndpointParams<typeof login>) {
100
+ // Handle the login request
101
+ const { email, password } = request
102
+
103
+ // Perform your login logic here
104
+ const user = await this.loginService.login(email, password)
105
+
106
+ if (user) {
107
+ return { success: true, user }
108
+ } else {
109
+ return { success: false, error: 'Invalid credentials' }
110
+ }
111
+ }
112
+ }
113
+ ```
114
+ Create your AppModule:
115
+
116
+ ```ts
117
+ import { Module } from '@navios/core'
118
+
119
+ import { AuthController } from './auth.controller.mjs'
120
+
121
+ @Module({
122
+ controllers: [AuthController],
123
+ })
124
+ export class AppModule {}
125
+ ```
126
+
127
+ Create your server:
128
+
129
+ ```ts
130
+ import { NaviosFactory } from '@navios/core'
131
+ import { AppModule } from './src/app.module.mjs'
132
+
133
+ export async function boot() {
134
+ const app = await NaviosFactory.create(AppModule)
135
+ app.setGlobalPrefix('/api')
136
+ app.enableCors({
137
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
138
+ })
139
+ await app.init()
140
+ await app.listen({ port: 3000, host: '0.0.0.0' })
141
+ }
142
+ await boot()
143
+ ```
144
+
145
+ That's it! You have created your first Navios server. You can now run your server and test the `/api/login` endpoint.
@@ -0,0 +1,425 @@
1
+ import { AnyZodObject, z, ZodType } from 'zod';
2
+ import { BaseEndpointConfig, EndpointFunctionArgs, HttpMethod } from '@navios/common';
3
+ import * as fastify from 'fastify';
4
+ import { FastifyRequest, FastifyReply, FastifyInstance, FastifyServerOptions, FastifyListenOptions } from 'fastify';
5
+ import * as http from 'http';
6
+ import * as fastify_types_type_provider_js from 'fastify/types/type-provider.js';
7
+ import { FastifyCorsOptions } from '@fastify/cors';
8
+
9
+ type ClassType = new (...args: any[]) => any;
10
+ type ClassTypeWithInstance<T> = new (...args: any[]) => T;
11
+ declare class InjectionToken<T, S extends AnyZodObject | unknown = unknown> {
12
+ readonly name: string | symbol | ClassType;
13
+ readonly schema: AnyZodObject | undefined;
14
+ id: `${string}-${string}-${string}-${string}-${string}`;
15
+ constructor(name: string | symbol | ClassType, schema: AnyZodObject | undefined);
16
+ static create<T extends ClassType>(name: T): InjectionToken<InstanceType<T>, undefined>;
17
+ static create<T extends ClassType, Schema extends AnyZodObject>(name: T, schema: Schema): InjectionToken<InstanceType<T>, Schema>;
18
+ static create<T>(name: string): InjectionToken<T, undefined>;
19
+ static create<T, Schema extends AnyZodObject>(name: string, schema: Schema): InjectionToken<T, Schema>;
20
+ toString(): string | symbol | ClassType;
21
+ }
22
+
23
+ declare function getInjectableToken<R, T extends ClassTypeWithInstance<R>>(target: ClassType): R extends {
24
+ create(...args: any[]): infer V;
25
+ } ? InjectionToken<V> : InjectionToken<R>;
26
+
27
+ declare enum InjectableScope {
28
+ /**
29
+ * Singleton scope: The instance is created once and shared across the application.
30
+ */
31
+ Singleton = "Singleton",
32
+ /**
33
+ * Instance scope: A new instance is created for each injection.
34
+ */
35
+ Instance = "Instance"
36
+ }
37
+
38
+ declare enum InjectableType {
39
+ Class = "Class",
40
+ Factory = "Factory"
41
+ }
42
+ interface InjectableOptions {
43
+ scope?: InjectableScope;
44
+ type?: InjectableType;
45
+ token?: InjectionToken<any, any>;
46
+ }
47
+ declare const InjectableTokenMeta: unique symbol;
48
+ declare function Injectable({ scope, type, token, }?: InjectableOptions): (target: ClassType, context: ClassDecoratorContext) => ClassType;
49
+
50
+ declare enum ErrorsEnum {
51
+ InstanceExpired = "InstanceExpired",
52
+ InstanceNotFound = "InstanceNotFound",
53
+ InstanceDestroying = "InstanceDestroying",
54
+ UnknownError = "UnknownError",
55
+ FactoryNotFound = "FactoryNotFound"
56
+ }
57
+
58
+ declare class FactoryNotFound extends Error {
59
+ name: string;
60
+ code: ErrorsEnum;
61
+ constructor(name: string);
62
+ }
63
+
64
+ declare class InstanceDestroying extends Error {
65
+ name: string;
66
+ code: ErrorsEnum;
67
+ constructor(name: string);
68
+ }
69
+
70
+ declare class InstanceExpired extends Error {
71
+ name: string;
72
+ code: ErrorsEnum;
73
+ constructor(name: string);
74
+ }
75
+
76
+ declare class InstanceNotFound extends Error {
77
+ name: string;
78
+ code: ErrorsEnum;
79
+ constructor(name: string);
80
+ }
81
+
82
+ declare class UnknownError extends Error {
83
+ code: ErrorsEnum;
84
+ parent?: Error;
85
+ constructor(message: string | Error);
86
+ }
87
+
88
+ type EventsConfig = {
89
+ [event: string]: any[];
90
+ };
91
+ type EventsNames<Events extends EventsConfig> = Exclude<keyof Events, symbol | number>;
92
+ type EventsArgs<Events extends EventsConfig, Name extends EventsNames<Events>> = Events[Name] extends any[] ? Events[Name] : [];
93
+ type ChannelEmitter<Events extends EventsConfig, Ns extends string, E extends EventsNames<Events>> = {
94
+ emit<Args extends EventsArgs<Events, E>>(ns: Ns, event: E, ...args: Args): Promise<any>;
95
+ };
96
+ interface EventEmitterInterface<Events extends EventsConfig> {
97
+ on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void): () => void;
98
+ emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, ...args: Args): void;
99
+ addChannel<E extends EventsNames<Events>, Ns extends string, Emmiter extends ChannelEmitter<Events, Ns, E>>(ns: Ns, event: E, target: Emmiter): () => void;
100
+ }
101
+ declare class EventEmitter<Events extends EventsConfig = {}> implements EventEmitterInterface<Events> {
102
+ private listeners;
103
+ on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void): () => void;
104
+ off<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void): void;
105
+ once<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void): () => void;
106
+ emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, ...args: Args): Promise<any>;
107
+ addChannel<E extends EventsNames<Events>, Ns extends string, Emitter extends ChannelEmitter<Events, Ns, E>>(ns: Ns, event: E, target: Emitter): () => void;
108
+ }
109
+
110
+ declare function inject<T extends ClassType>(token: T): Promise<InstanceType<T>>;
111
+ declare function inject<T, S extends AnyZodObject>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
112
+ declare function inject<T>(token: InjectionToken<T, undefined>): Promise<T>;
113
+
114
+ declare class ServiceLocatorEventBus {
115
+ private readonly logger;
116
+ private listeners;
117
+ constructor(logger?: Console | null);
118
+ on<Event extends string | `pre:${string}` | `post:${string}`>(ns: string, event: Event, listener: (event: Event) => void): () => void;
119
+ emit(key: string, event: string): Promise<PromiseSettledResult<any>[] | undefined>;
120
+ }
121
+
122
+ interface ServiceLocatorAbstractFactoryContext {
123
+ inject: typeof inject;
124
+ addDependency: ((token: InjectionToken<any, undefined>) => void) | (<S extends AnyZodObject>(token: InjectionToken<any, S>, args: z.input<S>) => void);
125
+ on: ServiceLocatorEventBus['on'];
126
+ getDependencies: () => string[];
127
+ invalidate: () => void;
128
+ addEffect: (listener: () => void) => void;
129
+ getDestroyListeners: () => (() => void)[];
130
+ setTtl: (ttl: number) => void;
131
+ getTtl: () => number;
132
+ }
133
+
134
+ declare class ServiceLocator {
135
+ private readonly logger;
136
+ private abstractFactories;
137
+ private instanceFactories;
138
+ private readonly eventBus;
139
+ private readonly manager;
140
+ constructor(logger?: Console | null);
141
+ getEventBus(): ServiceLocatorEventBus;
142
+ registerInstance<Instance>(token: InjectionToken<Instance, undefined>, instance: Instance): void;
143
+ removeInstance<Instance>(token: InjectionToken<Instance, undefined>): Promise<any>;
144
+ registerAbstractFactory<Instance, Schema extends AnyZodObject | undefined>(token: InjectionToken<Instance, Schema>, factory: (ctx: ServiceLocatorAbstractFactoryContext, values: Schema extends AnyZodObject ? z.output<Schema> : undefined) => Promise<Instance>, type?: InjectableScope): void;
145
+ getInstanceIdentifier<Instance, Schema extends AnyZodObject | undefined>(token: InjectionToken<Instance, Schema>, args: Schema extends AnyZodObject ? z.input<Schema> : undefined): string;
146
+ getInstance<Instance, Schema extends AnyZodObject | undefined>(token: InjectionToken<Instance, Schema>, args: Schema extends AnyZodObject ? z.input<Schema> : undefined): Promise<[undefined, Instance] | [UnknownError | FactoryNotFound]>;
147
+ getOrThrowInstance<Instance, Schema extends AnyZodObject | undefined>(token: InjectionToken<Instance, Schema>, args: Schema extends AnyZodObject ? z.input<Schema> : undefined): Promise<Instance>;
148
+ private notifyListeners;
149
+ private createInstance;
150
+ private createInstanceFromAbstractFactory;
151
+ private createContextForAbstractFactory;
152
+ getSyncInstance<Instance, Schema extends AnyZodObject | undefined>(token: InjectionToken<Instance, Schema>, args: Schema extends AnyZodObject ? z.input<Schema> : undefined): Instance | null;
153
+ invalidate(service: string, round?: number): Promise<any>;
154
+ ready(): Promise<null>;
155
+ makeInstanceName(token: InjectionToken<any, any>, args: any): string;
156
+ }
157
+
158
+ declare function provideServiceLocator(locator: ServiceLocator): ServiceLocator;
159
+ declare function getServiceLocator(): ServiceLocator;
160
+
161
+ /**
162
+ * Useful for tests or when you want to override a service
163
+ * with a different implementation.
164
+ */
165
+ declare function override<T>(token: InjectionToken<T>, target: ClassType): () => void;
166
+
167
+ declare enum ServiceLocatorInstanceHolderKind {
168
+ Instance = "instance",
169
+ Factory = "factory",
170
+ AbstractFactory = "abstractFactory"
171
+ }
172
+ declare enum ServiceLocatorInstanceHolderStatus {
173
+ Created = "created",
174
+ Creating = "creating",
175
+ Destroying = "destroying"
176
+ }
177
+ type ServiceLocatorInstanceEffect = () => void;
178
+ type ServiceLocatorInstanceDestroyListener = () => void | Promise<void>;
179
+ interface ServiceLocatorInstanceHolderCreating<Instance> {
180
+ status: ServiceLocatorInstanceHolderStatus.Creating;
181
+ name: string;
182
+ instance: null;
183
+ creationPromise: Promise<[undefined, Instance]> | null;
184
+ destroyPromise: null;
185
+ kind: ServiceLocatorInstanceHolderKind;
186
+ effects: ServiceLocatorInstanceEffect[];
187
+ deps: string[];
188
+ destroyListeners: ServiceLocatorInstanceDestroyListener[];
189
+ createdAt: number;
190
+ ttl: number;
191
+ }
192
+ interface ServiceLocatorInstanceHolderCreated<Instance> {
193
+ status: ServiceLocatorInstanceHolderStatus.Created;
194
+ name: string;
195
+ instance: Instance;
196
+ creationPromise: null;
197
+ destroyPromise: null;
198
+ kind: ServiceLocatorInstanceHolderKind;
199
+ effects: ServiceLocatorInstanceEffect[];
200
+ deps: string[];
201
+ destroyListeners: ServiceLocatorInstanceDestroyListener[];
202
+ createdAt: number;
203
+ ttl: number;
204
+ }
205
+ interface ServiceLocatorInstanceHolderDestroying<Instance> {
206
+ status: ServiceLocatorInstanceHolderStatus.Destroying;
207
+ name: string;
208
+ instance: Instance | null;
209
+ creationPromise: null;
210
+ destroyPromise: Promise<void>;
211
+ kind: ServiceLocatorInstanceHolderKind;
212
+ effects: ServiceLocatorInstanceEffect[];
213
+ deps: string[];
214
+ destroyListeners: ServiceLocatorInstanceDestroyListener[];
215
+ createdAt: number;
216
+ ttl: number;
217
+ }
218
+ type ServiceLocatorInstanceHolder<Instance = unknown> = ServiceLocatorInstanceHolderCreating<Instance> | ServiceLocatorInstanceHolderCreated<Instance> | ServiceLocatorInstanceHolderDestroying<Instance>;
219
+
220
+ declare class ServiceLocatorManager {
221
+ private readonly logger;
222
+ private readonly instancesHolders;
223
+ constructor(logger?: Console | null);
224
+ get(name: string): [InstanceExpired | InstanceDestroying, ServiceLocatorInstanceHolder] | [InstanceNotFound] | [undefined, ServiceLocatorInstanceHolder];
225
+ set(name: string, holder: ServiceLocatorInstanceHolder): void;
226
+ has(name: string): [InstanceExpired | InstanceDestroying] | [undefined, boolean];
227
+ delete(name: string): boolean;
228
+ filter(predicate: (value: ServiceLocatorInstanceHolder<any>, key: string) => boolean): Map<string, ServiceLocatorInstanceHolder>;
229
+ }
230
+
231
+ declare let promiseCollector: null | ((promise: Promise<any>) => void);
232
+ declare function syncInject<T extends ClassType>(token: T): InstanceType<T>;
233
+ declare function syncInject<T, S extends AnyZodObject>(token: InjectionToken<T, S>, args: z.input<S>): T;
234
+ declare function syncInject<T>(token: InjectionToken<T, undefined>): T;
235
+ declare function setPromiseCollector(collector: null | ((promise: Promise<any>) => void)): typeof promiseCollector;
236
+
237
+ interface ControllerOptions {
238
+ guards?: ClassType[] | Set<ClassType>;
239
+ }
240
+ declare function Controller({ guards }?: ControllerOptions): (target: ClassType, context: ClassDecoratorContext) => ClassType;
241
+
242
+ type EndpointParams<EndpointDeclaration extends {
243
+ config: BaseEndpointConfig<any, any, any, any, any>;
244
+ }, Url extends string = EndpointDeclaration['config']['url'], QuerySchema = EndpointDeclaration['config']['querySchema']> = QuerySchema extends AnyZodObject ? EndpointDeclaration['config']['requestSchema'] extends ZodType ? EndpointFunctionArgs<Url, QuerySchema, EndpointDeclaration['config']['requestSchema']> : EndpointFunctionArgs<Url, QuerySchema, undefined> : EndpointDeclaration['config']['requestSchema'] extends ZodType ? EndpointFunctionArgs<Url, undefined, EndpointDeclaration['config']['requestSchema']> : EndpointFunctionArgs<Url, undefined, undefined>;
245
+ declare function Endpoint<Method extends HttpMethod = HttpMethod, Url extends string = string, QuerySchema = undefined, ResponseSchema extends ZodType = ZodType, RequestSchema = ZodType>(endpoint: {
246
+ config: BaseEndpointConfig<Method, Url, QuerySchema, ResponseSchema, RequestSchema>;
247
+ }): (target: (params: QuerySchema extends AnyZodObject ? RequestSchema extends ZodType ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema> : EndpointFunctionArgs<Url, QuerySchema, undefined> : RequestSchema extends ZodType ? EndpointFunctionArgs<Url, undefined, RequestSchema> : EndpointFunctionArgs<Url, undefined, undefined>) => z.input<ResponseSchema>, context: ClassMethodDecoratorContext) => (params: QuerySchema extends AnyZodObject ? RequestSchema extends ZodType ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema> : EndpointFunctionArgs<Url, QuerySchema, undefined> : RequestSchema extends ZodType ? EndpointFunctionArgs<Url, undefined, RequestSchema> : EndpointFunctionArgs<Url, undefined, undefined>) => z.input<ResponseSchema>;
248
+
249
+ interface ModuleOptions {
250
+ controllers?: ClassType[] | Set<ClassType>;
251
+ imports?: ClassType[] | Set<ClassType>;
252
+ guards?: ClassType[] | Set<ClassType>;
253
+ }
254
+ declare function Module(metadata: ModuleOptions): (target: ClassType, context: ClassDecoratorContext) => ClassType;
255
+
256
+ declare const EndpointMetadataKey: unique symbol;
257
+ interface EndpointMetadata {
258
+ classMethod: string;
259
+ url: string;
260
+ httpMethod: HttpMethod;
261
+ config: BaseEndpointConfig | null;
262
+ guards: Set<ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>>;
263
+ customAttributes: Map<string | symbol, any>;
264
+ }
265
+ declare function getAllEndpointMetadata(context: ClassMethodDecoratorContext | ClassDecoratorContext): Set<EndpointMetadata>;
266
+ declare function getEndpointMetadata(target: Function, context: ClassMethodDecoratorContext): EndpointMetadata;
267
+
268
+ declare const ControllerMetadataKey: unique symbol;
269
+ interface ControllerMetadata {
270
+ endpoints: Set<EndpointMetadata>;
271
+ guards: Set<ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>>;
272
+ customAttributes: Map<string | symbol, any>;
273
+ }
274
+ declare function getControllerMetadata(target: ClassType, context: ClassDecoratorContext): ControllerMetadata;
275
+ declare function extractControllerMetadata(target: ClassType): ControllerMetadata;
276
+ declare function hasControllerMetadata(target: ClassType): boolean;
277
+
278
+ interface InjectableMetadata<Instance = any, Schema = any> {
279
+ type: InjectableType;
280
+ scope: InjectableScope;
281
+ token: InjectionToken<Instance, Schema>;
282
+ }
283
+
284
+ declare const ModuleMetadataKey: unique symbol;
285
+ interface ModuleMetadata {
286
+ controllers: Set<ClassType>;
287
+ imports: Set<ClassType>;
288
+ guards: Set<ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>>;
289
+ customAttributes: Map<string | symbol, any>;
290
+ }
291
+ declare function getModuleMetadata(target: ClassType, context: ClassDecoratorContext): ModuleMetadata;
292
+ declare function extractModuleMetadata(target: ClassType): ModuleMetadata;
293
+ declare function hasModuleMetadata(target: ClassType): boolean;
294
+
295
+ declare class ExecutionContext {
296
+ private readonly module;
297
+ private readonly controller;
298
+ private readonly handler;
299
+ private request;
300
+ private reply;
301
+ constructor(module: ModuleMetadata, controller: ControllerMetadata, handler: EndpointMetadata);
302
+ getModule(): ModuleMetadata;
303
+ getController(): ControllerMetadata;
304
+ getHandler(): EndpointMetadata;
305
+ getRequest(): FastifyRequest;
306
+ getReply(): FastifyReply;
307
+ provideRequest(request: FastifyRequest): void;
308
+ provideReply(reply: FastifyReply): void;
309
+ }
310
+
311
+ declare class GuardRunnerService {
312
+ runGuards(allGuards: Set<ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>>, executionContext: ExecutionContext): Promise<boolean>;
313
+ makeContext(executionContext: ExecutionContext): Set<ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>>;
314
+ }
315
+
316
+ declare class ControllerAdapterService {
317
+ guardRunner: GuardRunnerService;
318
+ setupController(controller: ClassType, instance: FastifyInstance, moduleMetadata: ModuleMetadata): void;
319
+ }
320
+
321
+ declare class ModuleLoaderService {
322
+ private modulesMetadata;
323
+ private loadedModules;
324
+ private initialized;
325
+ loadModules(appModule: ClassTypeWithInstance<NaviosModule>): Promise<void>;
326
+ private traverseModules;
327
+ private mergeMetadata;
328
+ getAllModules(): Map<string, ModuleMetadata>;
329
+ }
330
+
331
+ interface CanActivate {
332
+ canActivate(executionContext: ExecutionContext): Promise<boolean> | boolean;
333
+ }
334
+
335
+ interface NaviosModule {
336
+ onModuleInit?: () => Promise<void> | void;
337
+ }
338
+
339
+ declare function UseGuards(...guards: (ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>)[]): <T extends Function>(target: T, context: ClassMethodDecoratorContext | ClassDecoratorContext) => T;
340
+
341
+ declare class HttpException {
342
+ readonly statusCode: number;
343
+ readonly response: string | object;
344
+ readonly error?: Error | undefined;
345
+ constructor(statusCode: number, response: string | object, error?: Error | undefined);
346
+ }
347
+
348
+ declare class BadRequestException extends HttpException {
349
+ constructor(message: string | object);
350
+ }
351
+
352
+ declare class ForbiddenException extends HttpException {
353
+ constructor(message: string);
354
+ }
355
+
356
+ declare class InternalServerErrorException extends HttpException {
357
+ constructor(message: string | object, error?: Error);
358
+ }
359
+
360
+ declare class NotFoundException extends HttpException {
361
+ readonly response: string | object;
362
+ readonly error?: Error | undefined;
363
+ constructor(response: string | object, error?: Error | undefined);
364
+ }
365
+
366
+ declare class UnauthorizedException extends HttpException {
367
+ constructor(message: string | object, error?: Error);
368
+ }
369
+
370
+ declare class ConflictException extends HttpException {
371
+ constructor(message: string | object, error?: Error);
372
+ }
373
+
374
+ declare const Application: InjectionToken<FastifyInstance<fastify.RawServerDefault, http.IncomingMessage, http.ServerResponse<http.IncomingMessage>, fastify.FastifyBaseLogger, fastify.FastifyTypeProviderDefault>, undefined>;
375
+
376
+ declare const ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
377
+ declare const ExecutionContextToken: InjectionToken<ExecutionContext, undefined>;
378
+
379
+ declare const Reply: InjectionToken<FastifyReply<fastify.RouteGenericInterface, fastify.RawServerDefault, http.IncomingMessage, http.ServerResponse<http.IncomingMessage>, unknown, fastify.FastifySchema, fastify.FastifyTypeProviderDefault, unknown>, undefined>;
380
+
381
+ declare const Request: InjectionToken<FastifyRequest<fastify.RouteGenericInterface, fastify.RawServerDefault, http.IncomingMessage, fastify.FastifySchema, fastify.FastifyTypeProviderDefault, unknown, fastify.FastifyBaseLogger, fastify_types_type_provider_js.ResolveFastifyRequestType<fastify.FastifyTypeProviderDefault, fastify.FastifySchema, fastify.RouteGenericInterface>>, undefined>;
382
+
383
+ type ClassAttribute = (() => <T>(target: T, context: ClassDecoratorContext | ClassMethodDecoratorContext) => T) & {
384
+ token: symbol;
385
+ };
386
+ type ClassSchemaAttribute<T extends ZodType> = ((value: z.input<T>) => <T extends ClassType>(target: T, context: ClassDecoratorContext | ClassMethodDecoratorContext) => T) & {
387
+ token: symbol;
388
+ schema: ZodType;
389
+ };
390
+ declare class AttributeFactory {
391
+ static createAttribute(token: symbol): ClassAttribute;
392
+ static createAttribute<T extends ZodType>(token: symbol, value: z.input<T>): ClassSchemaAttribute<T>;
393
+ static get(attribute: ClassAttribute, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): true | null;
394
+ static get<T extends ZodType>(attribute: ClassSchemaAttribute<T>, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): z.output<T> | null;
395
+ static getAll(attribute: ClassAttribute, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): Array<true> | null;
396
+ static getAll<T extends ZodType>(attribute: ClassSchemaAttribute<T>, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): Array<z.output<T>> | null;
397
+ static getLast(attribute: ClassAttribute, target: (ModuleMetadata | ControllerMetadata | EndpointMetadata)[]): true | null;
398
+ static getLast<T extends ZodType>(attribute: ClassSchemaAttribute<T>, target: (ModuleMetadata | ControllerMetadata | EndpointMetadata)[]): z.output<T> | null;
399
+ static has(attribute: ClassAttribute, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): boolean;
400
+ static has<T extends ZodType>(attribute: ClassSchemaAttribute<T>, target: ModuleMetadata | ControllerMetadata | EndpointMetadata): boolean;
401
+ }
402
+
403
+ interface NaviosApplicationOptions extends FastifyServerOptions {
404
+ }
405
+ declare class NaviosApplication {
406
+ private moduleLoader;
407
+ private controllerAdapter;
408
+ private server;
409
+ private corsOptions;
410
+ private globalPrefix;
411
+ private appModule;
412
+ private options;
413
+ setup(appModule: ClassTypeWithInstance<NaviosModule>, options?: NaviosApplicationOptions): void;
414
+ init(): Promise<void>;
415
+ enableCors(options: FastifyCorsOptions): void;
416
+ setGlobalPrefix(prefix: string): void;
417
+ getServer(): FastifyInstance;
418
+ listen(options: FastifyListenOptions): Promise<void>;
419
+ }
420
+
421
+ declare class NaviosFactory {
422
+ static create(appModule: ClassTypeWithInstance<NaviosModule>, options?: NaviosApplicationOptions): Promise<NaviosApplication>;
423
+ }
424
+
425
+ export { Application, AttributeFactory, BadRequestException, type CanActivate, type ChannelEmitter, type ClassAttribute, type ClassSchemaAttribute, type ClassType, type ClassTypeWithInstance, ConflictException, Controller, ControllerAdapterService, type ControllerMetadata, ControllerMetadataKey, type ControllerOptions, Endpoint, type EndpointMetadata, EndpointMetadataKey, type EndpointParams, ErrorsEnum, EventEmitter, type EventEmitterInterface, type EventsArgs, type EventsConfig, type EventsNames, ExecutionContext, ExecutionContextInjectionToken, ExecutionContextToken, FactoryNotFound, ForbiddenException, GuardRunnerService, HttpException, Injectable, type InjectableMetadata, type InjectableOptions, InjectableScope, InjectableTokenMeta, InjectableType, InjectionToken, InstanceDestroying, InstanceExpired, InstanceNotFound, InternalServerErrorException, Module, ModuleLoaderService, type ModuleMetadata, ModuleMetadataKey, type ModuleOptions, NaviosApplication, type NaviosApplicationOptions, NaviosFactory, type NaviosModule, NotFoundException, Reply, Request, ServiceLocator, type ServiceLocatorAbstractFactoryContext, ServiceLocatorEventBus, type ServiceLocatorInstanceDestroyListener, type ServiceLocatorInstanceEffect, type ServiceLocatorInstanceHolder, type ServiceLocatorInstanceHolderCreated, type ServiceLocatorInstanceHolderCreating, type ServiceLocatorInstanceHolderDestroying, ServiceLocatorInstanceHolderKind, ServiceLocatorInstanceHolderStatus, ServiceLocatorManager, UnauthorizedException, UnknownError, UseGuards, extractControllerMetadata, extractModuleMetadata, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getInjectableToken, getModuleMetadata, getServiceLocator, hasControllerMetadata, hasModuleMetadata, inject, override, provideServiceLocator, setPromiseCollector, syncInject };