zeti-framework-backend 0.2.4
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.
- package/dist/chunk-7D4SUZUM.js +38 -0
- package/dist/chunk-7D4SUZUM.js.map +1 -0
- package/dist/chunk-K2E6XKVB.js +18 -0
- package/dist/chunk-K2E6XKVB.js.map +1 -0
- package/dist/chunk-KIOZSPU2.js +690 -0
- package/dist/chunk-KIOZSPU2.js.map +1 -0
- package/dist/chunk-LCNZVWVO.js +581 -0
- package/dist/chunk-LCNZVWVO.js.map +1 -0
- package/dist/chunk-TTILJJ3O.js +324 -0
- package/dist/chunk-TTILJJ3O.js.map +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +418 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/config-VWgz0Iq_.d.ts +647 -0
- package/dist/generator-CK-ZmWQj.d.ts +197 -0
- package/dist/generator-KC24DE6M.js +8 -0
- package/dist/generator-KC24DE6M.js.map +1 -0
- package/dist/index.d.ts +333 -0
- package/dist/index.js +11675 -0
- package/dist/index.js.map +1 -0
- package/dist/scripts/index.d.ts +34 -0
- package/dist/scripts/index.js +12 -0
- package/dist/scripts/index.js.map +1 -0
- package/dist/swagger/index.d.ts +10 -0
- package/dist/swagger/index.js +14 -0
- package/dist/swagger/index.js.map +1 -0
- package/dist/tenants/index.d.ts +146 -0
- package/dist/tenants/index.js +10 -0
- package/dist/tenants/index.js.map +1 -0
- package/package.json +83 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { ZodRawShape, ZodTypeAny, ZodObject, z } from 'zod';
|
|
2
|
+
import { Context, Next } from 'hono';
|
|
3
|
+
import { Z as ZetiSwaggerConfig } from './config-VWgz0Iq_.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Handler de middleware com db injetado automaticamente.
|
|
7
|
+
*
|
|
8
|
+
* O `db` é obtido do contexto (setado pelo framework) e já vem com:
|
|
9
|
+
* - Filtro de tenant aplicado (se connectionStrategy = 'dynamic')
|
|
10
|
+
* - Cache por URL (reutiliza instância base)
|
|
11
|
+
*/
|
|
12
|
+
type MiddlewareHandler<TDb = any> = (c: Context, next: Next, db: TDb) => Promise<void | Response>;
|
|
13
|
+
/**
|
|
14
|
+
* Cria um middleware com o `db` injetado automaticamente.
|
|
15
|
+
*
|
|
16
|
+
* O `db` é obtido do contexto (setado pelo framework) e já vem com:
|
|
17
|
+
* - Filtro de tenant aplicado (se connectionStrategy = 'dynamic')
|
|
18
|
+
* - Cache por URL (reutiliza instância base)
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* import { PrismaClient } from '@prisma/client';
|
|
23
|
+
*
|
|
24
|
+
* const authMiddleware = createMiddleware<PrismaClient>(async (c, next, db) => {
|
|
25
|
+
* // db já vem tipado e com filtro de tenant
|
|
26
|
+
* const user = await db.user.findUnique({
|
|
27
|
+
* where: { id: c.req.header('x-user-id') }
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* if (!user) {
|
|
31
|
+
* return c.json({ error: 'Unauthorized' }, 401);
|
|
32
|
+
* }
|
|
33
|
+
*
|
|
34
|
+
* c.set('user', user);
|
|
35
|
+
* await next();
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
declare function createMiddleware<TDb = any>(handler: MiddlewareHandler<TDb>): (c: Context, next: Next) => Promise<void | Response>;
|
|
40
|
+
type MiddlewareFactory<T extends any[], TDb = any> = (...args: T) => (c: Context, next: Next) => Promise<void | Response>;
|
|
41
|
+
/**
|
|
42
|
+
* Cria uma factory de middleware com db injetado.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* const requirePermission = createMiddlewareFactory<[string[]], PrismaClient>(
|
|
47
|
+
* (permissions: string[]) => async (c, next, db) => {
|
|
48
|
+
* const user = c.get('user');
|
|
49
|
+
* const userPermissions = await db.permission.findMany({
|
|
50
|
+
* where: { userId: user.id }
|
|
51
|
+
* });
|
|
52
|
+
*
|
|
53
|
+
* const hasPermission = permissions.every(p =>
|
|
54
|
+
* userPermissions.some(up => up.name === p)
|
|
55
|
+
* );
|
|
56
|
+
*
|
|
57
|
+
* if (!hasPermission) {
|
|
58
|
+
* return c.json({ error: 'Forbidden' }, 403);
|
|
59
|
+
* }
|
|
60
|
+
*
|
|
61
|
+
* await next();
|
|
62
|
+
* }
|
|
63
|
+
* );
|
|
64
|
+
*
|
|
65
|
+
* // Uso:
|
|
66
|
+
* app.use('/admin/*', requirePermission(['admin:read']));
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
declare function createMiddlewareFactory<T extends any[], TDb = any>(factory: (...args: T) => MiddlewareHandler<TDb>): MiddlewareFactory<T, TDb>;
|
|
70
|
+
/**
|
|
71
|
+
* Helper para obter o db do contexto de forma tipada.
|
|
72
|
+
* Útil quando você precisa acessar o db fora do createMiddleware.
|
|
73
|
+
*
|
|
74
|
+
* @throws Error se o db não estiver disponível
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```typescript
|
|
78
|
+
* // Em um handler de rota Hono puro
|
|
79
|
+
* app.get('/users', async (c) => {
|
|
80
|
+
* const db = getDb<PrismaClient>(c);
|
|
81
|
+
* const users = await db.user.findMany();
|
|
82
|
+
* return c.json(users);
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
declare function getDb<TDb = any>(c: Context): TDb;
|
|
87
|
+
/**
|
|
88
|
+
* Helper para obter o db do contexto de forma segura (pode retornar undefined).
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```typescript
|
|
92
|
+
* // Em um handler de rota Hono puro
|
|
93
|
+
* app.get('/health', async (c) => {
|
|
94
|
+
* const db = getDbSafe<PrismaClient>(c);
|
|
95
|
+
* if (!db) {
|
|
96
|
+
* return c.json({ status: 'degraded', db: false });
|
|
97
|
+
* }
|
|
98
|
+
* return c.json({ status: 'ok', db: true });
|
|
99
|
+
* });
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
declare function getDbSafe<TDb = any>(c: Context): TDb | undefined;
|
|
103
|
+
|
|
104
|
+
type SchemaDefinition = {
|
|
105
|
+
body?: ZodRawShape | ZodTypeAny;
|
|
106
|
+
query?: ZodRawShape | ZodTypeAny;
|
|
107
|
+
response?: ZodRawShape | ZodTypeAny;
|
|
108
|
+
formData?: ZodRawShape | ZodTypeAny;
|
|
109
|
+
};
|
|
110
|
+
type NormalizeFormData<T> = T extends ZodTypeAny ? T : T extends ZodRawShape ? ZodObject<T> : never;
|
|
111
|
+
type InferFormData<S extends SchemaDefinition> = S['formData'] extends undefined ? unknown : NormalizeFormData<S['formData']> extends never ? unknown : z.infer<NormalizeFormData<S['formData']>>;
|
|
112
|
+
type NormalizeZod<T> = T extends ZodTypeAny ? T : T extends ZodRawShape ? ZodObject<T> : never;
|
|
113
|
+
type InferBody<S extends SchemaDefinition> = S['body'] extends undefined ? unknown : NormalizeZod<S['body']> extends never ? unknown : z.infer<NormalizeZod<S['body']>>;
|
|
114
|
+
type InferQuery<S extends SchemaDefinition> = S['query'] extends undefined ? unknown : NormalizeZod<S['query']> extends never ? unknown : z.infer<NormalizeZod<S['query']>>;
|
|
115
|
+
type ExtractParams<T extends string> = T extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
|
|
116
|
+
[K in Param]: string;
|
|
117
|
+
} & ExtractParams<Rest> : T extends `${infer _Start}:${infer Param}` ? {
|
|
118
|
+
[K in Param]: string;
|
|
119
|
+
} : {};
|
|
120
|
+
type ZetiZod = typeof z;
|
|
121
|
+
type ZetiContextExtensions = {
|
|
122
|
+
ipAddress?: string;
|
|
123
|
+
userAgent?: string;
|
|
124
|
+
timezone: string;
|
|
125
|
+
tenantId: string;
|
|
126
|
+
};
|
|
127
|
+
type ZetiContext<TContext extends Context = Context> = TContext & ZetiContextExtensions;
|
|
128
|
+
interface ZetiRouteProps<TParams extends Record<string, string>, TBody, TQuery, TFormData, TPrisma = any, TUser = any> {
|
|
129
|
+
context: ZetiContext;
|
|
130
|
+
next: Next;
|
|
131
|
+
params: TParams;
|
|
132
|
+
body: TBody;
|
|
133
|
+
query: TQuery;
|
|
134
|
+
formData: TFormData;
|
|
135
|
+
user?: TUser;
|
|
136
|
+
db: TPrisma;
|
|
137
|
+
res: ZetiResponseHelpers;
|
|
138
|
+
}
|
|
139
|
+
interface ZetiResponseHelpers {
|
|
140
|
+
goneError: (params: {
|
|
141
|
+
message: string;
|
|
142
|
+
code?: string;
|
|
143
|
+
}) => never;
|
|
144
|
+
unauthorizedError: (message: string) => never;
|
|
145
|
+
badRequestError: (message: string) => never;
|
|
146
|
+
}
|
|
147
|
+
interface ZetiMethodOptions<TPath extends string, TSchema extends SchemaDefinition, TPrisma = any, TUser = any> {
|
|
148
|
+
middleware?: {
|
|
149
|
+
use?: MiddlewareHandler[];
|
|
150
|
+
schema?: (z: ZetiZod) => TSchema;
|
|
151
|
+
database?: string;
|
|
152
|
+
tenant?: boolean;
|
|
153
|
+
/** Exige auth (injeta `auth` antes dos demais). */
|
|
154
|
+
auth?: boolean;
|
|
155
|
+
/** Claims exigidas (usa `requireClaim` de named). */
|
|
156
|
+
claims?: string[];
|
|
157
|
+
/** Roles exigidas (usa `requireRole` de named). */
|
|
158
|
+
roles?: string[];
|
|
159
|
+
};
|
|
160
|
+
route: (props: ZetiRouteProps<ExtractParams<TPath>, InferBody<TSchema>, InferQuery<TSchema>, InferFormData<TSchema>, TPrisma, TUser>) => Promise<any>;
|
|
161
|
+
}
|
|
162
|
+
interface RouteMetadata {
|
|
163
|
+
path: string;
|
|
164
|
+
method: 'get' | 'post' | 'put' | 'delete' | 'patch';
|
|
165
|
+
auth: boolean;
|
|
166
|
+
tenant?: boolean;
|
|
167
|
+
claims?: string[];
|
|
168
|
+
roles?: string[];
|
|
169
|
+
bodySchema?: ZodTypeAny;
|
|
170
|
+
querySchema?: ZodTypeAny;
|
|
171
|
+
responseSchema?: ZodTypeAny;
|
|
172
|
+
formDataSchema?: ZodTypeAny;
|
|
173
|
+
summary?: string;
|
|
174
|
+
description?: string;
|
|
175
|
+
tags?: string[];
|
|
176
|
+
}
|
|
177
|
+
type ZetiRouteMiddleware<TSchema extends SchemaDefinition> = ZetiMethodOptions<any, TSchema>['middleware'];
|
|
178
|
+
|
|
179
|
+
declare class SwaggerRegistry {
|
|
180
|
+
private routes;
|
|
181
|
+
register(metadata: RouteMetadata): void;
|
|
182
|
+
getAll(): RouteMetadata[];
|
|
183
|
+
clear(): void;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface SwaggerGeneratorOptions {
|
|
187
|
+
loadGeneratedSchemas?: () => Promise<{
|
|
188
|
+
routeResponseSchemas?: Record<string, Record<string, {
|
|
189
|
+
schema: ZodTypeAny;
|
|
190
|
+
ref: string | null;
|
|
191
|
+
}>>;
|
|
192
|
+
namedSchemas?: Record<string, ZodTypeAny>;
|
|
193
|
+
}>;
|
|
194
|
+
}
|
|
195
|
+
declare function generateSwagger(registry: SwaggerRegistry, config: ZetiSwaggerConfig, options?: SwaggerGeneratorOptions): Promise<object>;
|
|
196
|
+
|
|
197
|
+
export { type ExtractParams as E, type InferBody as I, type MiddlewareFactory as M, type RouteMetadata as R, type SwaggerGeneratorOptions as S, type ZetiMethodOptions as Z, SwaggerRegistry as a, type SchemaDefinition as b, type InferFormData as c, type InferQuery as d, type MiddlewareHandler as e, type ZetiContext as f, generateSwagger as g, type ZetiContextExtensions as h, type ZetiResponseHelpers as i, type ZetiRouteMiddleware as j, type ZetiRouteProps as k, type ZetiZod as l, createMiddleware as m, createMiddlewareFactory as n, getDb as o, getDbSafe as p };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import * as hono_types from 'hono/types';
|
|
2
|
+
import { Context, Next, Hono } from 'hono';
|
|
3
|
+
import { a as ZetiConfigInternal, W as WorkerConfig, b as ZetiPrismaConnectionConfig, R as RedisConfig } from './config-VWgz0Iq_.js';
|
|
4
|
+
export { C as ConnectionStrategy, E as ErrorResponse, c as ErrorTrace, M as Middleware, P as Prisma, d as PrismaClientBase, S as SecurityScope, T as TenantSelection, V as ValidationError, e as WorkersConfig, f as ZetiConfig, g as ZetiCorsConfig, h as ZetiDatabaseConfig, i as ZetiDevConfig, j as ZetiErrorHandlerConfig, k as ZetiHeadersConfig, l as ZetiMiddlewareConfig, m as ZetiPrismaConfig, Z as ZetiSwaggerConfig, n as ZetiSwaggerHeaderParam, o as ZetiTenantConfig, p as closeRedis, q as createErrorHandler, r as defineZetiConfig, s as getRedisClient, t as getRedisConfig, u as handleError, v as initRedis } from './config-VWgz0Iq_.js';
|
|
5
|
+
import { b as SchemaDefinition, Z as ZetiMethodOptions, a as SwaggerRegistry } from './generator-CK-ZmWQj.js';
|
|
6
|
+
export { E as ExtractParams, I as InferBody, c as InferFormData, d as InferQuery, M as MiddlewareFactory, e as MiddlewareHandler, R as RouteMetadata, S as SwaggerGeneratorOptions, f as ZetiContext, h as ZetiContextExtensions, i as ZetiResponseHelpers, j as ZetiRouteMiddleware, k as ZetiRouteProps, l as ZetiZod, m as createMiddleware, n as createMiddlewareFactory, g as generateSwagger, o as getDb, p as getDbSafe } from './generator-CK-ZmWQj.js';
|
|
7
|
+
import { TenantManager } from './tenants/index.js';
|
|
8
|
+
export { MetricsCollector, TenantMetrics } from './tenants/index.js';
|
|
9
|
+
import Redis from 'ioredis';
|
|
10
|
+
export { default as Redis } from 'ioredis';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
export { GenerateRegistryOptions, GenerateSwaggerTypesOptions, generateRegistry, generateSwaggerTypes, runPrebuild } from './scripts/index.js';
|
|
13
|
+
import 'hono/http-exception';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Handler de middleware tipado com o PrismaClient do projeto.
|
|
17
|
+
*/
|
|
18
|
+
type ZetiMiddlewareHandler<TPrisma = any> = (c: Context, next: Next, db: TPrisma) => Promise<void | Response>;
|
|
19
|
+
interface ZetiApp<TPrisma = any, TUser = any> {
|
|
20
|
+
get: <TPath extends string, TSchema extends SchemaDefinition = {}>(url: TPath, options: ZetiMethodOptions<TPath, TSchema, TPrisma, TUser>) => void;
|
|
21
|
+
post: <TPath extends string, TSchema extends SchemaDefinition = {}>(url: TPath, options: ZetiMethodOptions<TPath, TSchema, TPrisma, TUser>) => void;
|
|
22
|
+
put: <TPath extends string, TSchema extends SchemaDefinition = {}>(url: TPath, options: ZetiMethodOptions<TPath, TSchema, TPrisma, TUser>) => void;
|
|
23
|
+
del: <TPath extends string, TSchema extends SchemaDefinition = {}>(url: TPath, options: ZetiMethodOptions<TPath, TSchema, TPrisma, TUser>) => void;
|
|
24
|
+
patch: <TPath extends string, TSchema extends SchemaDefinition = {}>(url: TPath, options: ZetiMethodOptions<TPath, TSchema, TPrisma, TUser>) => void;
|
|
25
|
+
/**
|
|
26
|
+
* Cria um middleware com o db tipado automaticamente.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const authMiddleware = app.createMiddleware(async (c, next, db) => {
|
|
31
|
+
* const user = await db.user.findUnique({
|
|
32
|
+
* where: { id: c.req.header('x-user-id') }
|
|
33
|
+
* });
|
|
34
|
+
* if (!user) return c.json({ error: 'Unauthorized' }, 401);
|
|
35
|
+
* c.set('user', user);
|
|
36
|
+
* await next();
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
createMiddleware: (handler: ZetiMiddlewareHandler<TPrisma>) => (c: Context, next: Next) => Promise<void | Response>;
|
|
41
|
+
honoApp: Hono;
|
|
42
|
+
swaggerRegistry: SwaggerRegistry;
|
|
43
|
+
tenantManager: TenantManager;
|
|
44
|
+
shutdown: () => Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Cria uma instância do Zeti App
|
|
48
|
+
*
|
|
49
|
+
* @template TPrisma - Tipo do PrismaClient do projeto do usuário
|
|
50
|
+
* @template TUser - Tipo do usuário autenticado (opcional)
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* import { PrismaClient } from '@prisma/client';
|
|
55
|
+
*
|
|
56
|
+
* const app = createZetiApp<PrismaClient>({
|
|
57
|
+
* config,
|
|
58
|
+
* prismaClient: PrismaClient,
|
|
59
|
+
* });
|
|
60
|
+
*
|
|
61
|
+
* // Agora todas as rotas terão db tipado como PrismaClient do usuário
|
|
62
|
+
* app.get('/users', {
|
|
63
|
+
* route: async ({ db }) => {
|
|
64
|
+
* // db é tipado como PrismaClient do usuário
|
|
65
|
+
* // Com todos os modelos do schema.prisma
|
|
66
|
+
* const users = await db.user.findMany();
|
|
67
|
+
* return { data: users };
|
|
68
|
+
* },
|
|
69
|
+
* });
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
declare function createZetiApp<TPrisma = any, TUser = any>(options: {
|
|
73
|
+
config: ZetiConfigInternal;
|
|
74
|
+
prismaClient: new (...args: any[]) => TPrisma;
|
|
75
|
+
}): ZetiApp<TPrisma, TUser>;
|
|
76
|
+
declare function initializeZetiApp<TPrisma = any, TUser = any>(options: {
|
|
77
|
+
config: ZetiConfigInternal;
|
|
78
|
+
prismaClient: new (...args: any[]) => TPrisma;
|
|
79
|
+
}): ZetiApp<TPrisma, TUser>;
|
|
80
|
+
declare function getZetiApp(): ZetiApp<any, any> | null;
|
|
81
|
+
declare function getZetiAppTyped<TPrisma = any, TUser = any>(): ZetiApp<TPrisma, TUser>;
|
|
82
|
+
declare function autoInitializeZetiApp<TPrisma = any, TUser = any>(options?: {
|
|
83
|
+
configPath?: string;
|
|
84
|
+
prismaClient?: new (...args: any[]) => TPrisma;
|
|
85
|
+
}): Promise<ZetiApp<TPrisma, TUser> | null>;
|
|
86
|
+
declare const honoRoutesZeti: Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Função para obter conexão do banco
|
|
90
|
+
* Para multi-tenant, recebe o tenantId e retorna o banco do tenant
|
|
91
|
+
*/
|
|
92
|
+
type GetDbFn = (tenantId?: string) => any | Promise<any>;
|
|
93
|
+
/**
|
|
94
|
+
* Instância de um Worker em execução
|
|
95
|
+
*/
|
|
96
|
+
declare class WorkerInstance {
|
|
97
|
+
private name;
|
|
98
|
+
private config;
|
|
99
|
+
private intervalId;
|
|
100
|
+
private isRunning;
|
|
101
|
+
private isProcessing;
|
|
102
|
+
private isStopping;
|
|
103
|
+
private getDb;
|
|
104
|
+
private getTenants?;
|
|
105
|
+
private executionCount;
|
|
106
|
+
private startedAt;
|
|
107
|
+
constructor(name: string, config: WorkerConfig, getDb: GetDbFn, getTenants?: () => string[]);
|
|
108
|
+
start(): void;
|
|
109
|
+
/**
|
|
110
|
+
* Para o worker de forma graciosa, aguardando execução atual terminar
|
|
111
|
+
*/
|
|
112
|
+
stop(): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* Verifica se está processando
|
|
115
|
+
*/
|
|
116
|
+
getIsProcessing(): boolean;
|
|
117
|
+
private run;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Gerenciador de Workers com Graceful Shutdown
|
|
121
|
+
*/
|
|
122
|
+
declare class WorkerManager {
|
|
123
|
+
private workers;
|
|
124
|
+
private isShuttingDown;
|
|
125
|
+
constructor();
|
|
126
|
+
/**
|
|
127
|
+
* Configura listeners para sinais de shutdown
|
|
128
|
+
*/
|
|
129
|
+
private setupGracefulShutdown;
|
|
130
|
+
startAll(workersConfig: Record<string, WorkerConfig>, getDb: GetDbFn, getTenants?: () => string[]): void;
|
|
131
|
+
/**
|
|
132
|
+
* Para todos os workers de forma graciosa
|
|
133
|
+
*/
|
|
134
|
+
stopAll(): Promise<void>;
|
|
135
|
+
/**
|
|
136
|
+
* Para um worker específico
|
|
137
|
+
*/
|
|
138
|
+
stop(name: string): Promise<void>;
|
|
139
|
+
getActiveWorkers(): string[];
|
|
140
|
+
/**
|
|
141
|
+
* Verifica se algum worker está processando
|
|
142
|
+
*/
|
|
143
|
+
hasActiveProcessing(): boolean;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface StartZetiOptions<TPrisma = any, TUser = any> {
|
|
147
|
+
config: ZetiConfigInternal;
|
|
148
|
+
prisma?: ZetiPrismaConnectionConfig<TPrisma>;
|
|
149
|
+
redis?: RedisConfig;
|
|
150
|
+
port?: number;
|
|
151
|
+
registryPath?: string;
|
|
152
|
+
onReady?: (app: ZetiApp<TPrisma, TUser>) => void | Promise<void>;
|
|
153
|
+
}
|
|
154
|
+
declare function startZeti<TPrisma = any, TUser = any>(options: StartZetiOptions<TPrisma, TUser>): Promise<ZetiApp<TPrisma, TUser>>;
|
|
155
|
+
declare function getPrismaClient<TPrisma = any>(tenantId?: string): TPrisma;
|
|
156
|
+
declare function createAppProxy<TPrisma = any, TUser = any>(): ZetiApp<TPrisma, TUser>;
|
|
157
|
+
declare function getPrismaConnectionConfig(): ZetiPrismaConnectionConfig | null;
|
|
158
|
+
declare function getWorkerManager(): WorkerManager | null;
|
|
159
|
+
declare function stopAllWorkers(): void;
|
|
160
|
+
declare function getRedis(): Redis;
|
|
161
|
+
declare function hasRedis(): boolean;
|
|
162
|
+
declare function getRedisConfiguration(): RedisConfig | null;
|
|
163
|
+
declare function shutdownZeti(): Promise<void>;
|
|
164
|
+
|
|
165
|
+
interface PrismaConfigOptions {
|
|
166
|
+
/** Caminho do schema. Default: "prisma/schema.prisma" */
|
|
167
|
+
schema?: string;
|
|
168
|
+
/** Caminho das migrations. Default: "prisma/migrations" */
|
|
169
|
+
migrationsPath?: string;
|
|
170
|
+
}
|
|
171
|
+
interface PrismaDefineConfig {
|
|
172
|
+
schema: string;
|
|
173
|
+
migrations: {
|
|
174
|
+
path: string;
|
|
175
|
+
};
|
|
176
|
+
datasource: {
|
|
177
|
+
url: string;
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Gera a configuração do Prisma.
|
|
182
|
+
*
|
|
183
|
+
* Aceita opcionalmente um ZetiConfig, mas NÃO É NECESSÁRIO passá-lo.
|
|
184
|
+
* A função busca automaticamente a URL do banco no .env.
|
|
185
|
+
*
|
|
186
|
+
* @example Uso simples (recomendado para evitar importar zeti.config.ts)
|
|
187
|
+
* ```typescript
|
|
188
|
+
* // prisma.config.ts
|
|
189
|
+
* import { definePrismaConfig } from "zeti-framework";
|
|
190
|
+
*
|
|
191
|
+
* export default definePrismaConfig();
|
|
192
|
+
* ```
|
|
193
|
+
*
|
|
194
|
+
* @example Uso com config (opcional)
|
|
195
|
+
* ```typescript
|
|
196
|
+
* // prisma.config.ts
|
|
197
|
+
* import { zetiConfig } from "./zeti.config";
|
|
198
|
+
* import { definePrismaConfig } from "zeti-framework";
|
|
199
|
+
*
|
|
200
|
+
* export default definePrismaConfig(zetiConfig);
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
declare function definePrismaConfig(zetiConfigOrOptions?: ZetiConfigInternal | PrismaConfigOptions, options?: PrismaConfigOptions): PrismaDefineConfig;
|
|
204
|
+
/**
|
|
205
|
+
* Retorna todas as URLs de banco de dados configuradas (para multi-tenant migrations).
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```typescript
|
|
209
|
+
* const urls = getAllDatabaseUrls(zetiConfig);
|
|
210
|
+
* for (const [name, url] of Object.entries(urls)) {
|
|
211
|
+
* console.log(`Migrating ${name}...`);
|
|
212
|
+
* // executar migration para cada tenant
|
|
213
|
+
* }
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
declare function getAllDatabaseUrls(zetiConfig: ZetiConfigInternal): Record<string, string>;
|
|
217
|
+
|
|
218
|
+
declare function badRequestError(message: string, cause?: any): never;
|
|
219
|
+
declare function unauthorizedError(message: string, cause?: any): never;
|
|
220
|
+
declare function forbiddenError(message: string, cause?: any): never;
|
|
221
|
+
declare function notFoundError(message: string, cause?: any): never;
|
|
222
|
+
declare function conflictError(message: string, cause?: any): never;
|
|
223
|
+
declare function goneError(message: string, cause?: any): never;
|
|
224
|
+
declare function unprocessableEntityError(message: string, cause?: any): never;
|
|
225
|
+
declare function internalServerError(message: string, cause?: any): never;
|
|
226
|
+
|
|
227
|
+
declare function loadEnv(): void;
|
|
228
|
+
/**
|
|
229
|
+
* Retorna o valor de uma variável de ambiente.
|
|
230
|
+
*
|
|
231
|
+
* @param key - Nome da variável de ambiente
|
|
232
|
+
* @param fallback - Valor padrão se a variável não existir (padrão: undefined = obrigatório)
|
|
233
|
+
* @returns O valor da variável ou o fallback
|
|
234
|
+
* @throws Error se a variável não existir e não houver fallback
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* ```typescript
|
|
238
|
+
* // Obrigatório - lança erro se não existir
|
|
239
|
+
* const dbUrl = env("DATABASE_URL");
|
|
240
|
+
*
|
|
241
|
+
* // Opcional - retorna fallback
|
|
242
|
+
* const port = env("PORT", "3000");
|
|
243
|
+
* ```
|
|
244
|
+
*/
|
|
245
|
+
declare function env(key: string, fallback?: string): string;
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Symbol usado para identificar schemas de arquivo
|
|
249
|
+
*/
|
|
250
|
+
declare const FILE_SCHEMA_SYMBOL: unique symbol;
|
|
251
|
+
/**
|
|
252
|
+
* Cria um schema Zod para upload de arquivo
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```typescript
|
|
256
|
+
* app.post("/upload", {
|
|
257
|
+
* middleware: {
|
|
258
|
+
* schema: (zod) => ({
|
|
259
|
+
* formData: zod.object({
|
|
260
|
+
* file: zFile(),
|
|
261
|
+
* avatar: zFile("Foto de perfil"),
|
|
262
|
+
* documents: zFiles("Documentos PDF"),
|
|
263
|
+
* }),
|
|
264
|
+
* }),
|
|
265
|
+
* },
|
|
266
|
+
* route: async ({ formData }) => {
|
|
267
|
+
* const file = formData.file as File;
|
|
268
|
+
* // ...
|
|
269
|
+
* },
|
|
270
|
+
* });
|
|
271
|
+
* ```
|
|
272
|
+
*/
|
|
273
|
+
declare function zFile(description?: string): z.ZodAny;
|
|
274
|
+
/**
|
|
275
|
+
* Cria um schema Zod para upload de múltiplos arquivos
|
|
276
|
+
*/
|
|
277
|
+
declare function zFiles(description?: string): z.ZodArray<z.ZodAny, "many">;
|
|
278
|
+
/**
|
|
279
|
+
* Verifica se um schema Zod é um schema de arquivo
|
|
280
|
+
*/
|
|
281
|
+
declare function isFileSchema(schema: z.ZodTypeAny): boolean;
|
|
282
|
+
/**
|
|
283
|
+
* Verifica se um schema Zod é um schema de múltiplos arquivos
|
|
284
|
+
*/
|
|
285
|
+
declare function isMultipleFileSchema(schema: z.ZodTypeAny): boolean;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Cria middleware que resolve o banco de dados e coloca no contexto.
|
|
289
|
+
*
|
|
290
|
+
* Este middleware usa o TenantManager.getContextualClient() para:
|
|
291
|
+
* 1. Resolver a URL do banco (single ou dynamic)
|
|
292
|
+
* 2. Aplicar $extends com filtro de tenantId (se aplicável)
|
|
293
|
+
* 3. Colocar o cliente no contexto via c.set('db', client)
|
|
294
|
+
*
|
|
295
|
+
* @param tenantManager - Instância do TenantManager
|
|
296
|
+
* @returns Middleware do Hono
|
|
297
|
+
*
|
|
298
|
+
* @example
|
|
299
|
+
* ```typescript
|
|
300
|
+
* // No framework.ts
|
|
301
|
+
* const dbMiddleware = createDatabaseMiddleware(tenantManager);
|
|
302
|
+
* honoApp.use('*', dbMiddleware);
|
|
303
|
+
*
|
|
304
|
+
* // Nas rotas
|
|
305
|
+
* app.get('/users', {
|
|
306
|
+
* route: async ({ db }) => {
|
|
307
|
+
* // db já vem com filtro de tenant aplicado
|
|
308
|
+
* const users = await db.user.findMany();
|
|
309
|
+
* return { data: users };
|
|
310
|
+
* },
|
|
311
|
+
* });
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
314
|
+
declare function createDatabaseMiddleware(tenantManager: TenantManager): (c: Context, next: Next) => Promise<void>;
|
|
315
|
+
/**
|
|
316
|
+
* Tipo do contexto com db disponível.
|
|
317
|
+
* Útil para tipar middlewares customizados.
|
|
318
|
+
*/
|
|
319
|
+
interface DatabaseContext {
|
|
320
|
+
db: any;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Helper para obter db do contexto de forma tipada.
|
|
324
|
+
*
|
|
325
|
+
* @example
|
|
326
|
+
* ```typescript
|
|
327
|
+
* const db = getDbFromContext<PrismaClient>(c);
|
|
328
|
+
* const users = await db.user.findMany();
|
|
329
|
+
* ```
|
|
330
|
+
*/
|
|
331
|
+
declare function getDbFromContext<TPrisma = any>(c: Context): TPrisma;
|
|
332
|
+
|
|
333
|
+
export { type DatabaseContext, FILE_SCHEMA_SYMBOL, type PrismaConfigOptions, RedisConfig, SchemaDefinition, type StartZetiOptions, SwaggerRegistry, TenantManager, WorkerConfig, WorkerInstance, WorkerManager, type ZetiApp, ZetiConfigInternal, ZetiMethodOptions, type ZetiMiddlewareHandler, ZetiPrismaConnectionConfig, autoInitializeZetiApp, badRequestError, conflictError, createAppProxy, createDatabaseMiddleware, createZetiApp, definePrismaConfig, env, forbiddenError, getAllDatabaseUrls, getDbFromContext, getPrismaClient, getPrismaConnectionConfig, getRedis, getRedisConfiguration, getWorkerManager, getZetiApp, getZetiAppTyped, goneError, hasRedis, honoRoutesZeti, initializeZetiApp, internalServerError, isFileSchema, isMultipleFileSchema, loadEnv, notFoundError, shutdownZeti, startZeti, stopAllWorkers, unauthorizedError, unprocessableEntityError, zFile, zFiles };
|