@maykonpaulo/maestro-core 0.2.1 → 0.3.0-next.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.
package/README.md CHANGED
@@ -1,110 +1,114 @@
1
1
  # @maykonpaulo/maestro-core
2
2
 
3
- Pacote central da plataforma Maestro. Fornece capacidades administrativas genéricas e reutilizáveis para sistemas internos.
3
+ Central package of the Maestro engine. Provides the complete runtime for operating any system's data without direct database access.
4
4
 
5
- ## Módulos disponíveis
6
-
7
- | Módulo | Classes / Interfaces principais |
8
- |-----------------|----------------------------------------------------------------------|
9
- | `audit` | `AuditRecorder`, `InMemoryAuditRepository`, `AuditRepository` |
10
- | `rbac` | `RbacEngine`, `RbacPolicy`, `Role` |
11
- | `logging` | `ConsoleLogger`, `Logger` |
12
- | `feature-flags` | `InMemoryFeatureFlagProvider`, `FeatureFlagProvider` |
13
- | `config` | `InMemoryConfigProvider`, `ConfigProvider` |
14
- | `events` | `InMemoryEventBus`, `EventBus`, `DomainEvent` |
15
- | `errors` | `MaestroError`, `ErrorCode` |
16
- | `types` | `Actor`, `ResourceRef`, `Metadata` |
17
-
18
- ## Instalação
5
+ ## Installation
19
6
 
20
7
  ```bash
21
8
  pnpm add @maykonpaulo/maestro-core
22
9
  ```
23
10
 
24
- ## Uso básico
11
+ ## Quick start
25
12
 
26
- ```typescript
13
+ ```ts
27
14
  import {
28
- AuditRecorder,
15
+ createMaestro,
16
+ InMemoryDatasourceProvider,
29
17
  InMemoryAuditRepository,
30
- RbacEngine,
31
- ConsoleLogger,
32
- InMemoryFeatureFlagProvider,
33
- InMemoryConfigProvider,
34
- InMemoryEventBus,
18
+ type EntitySchema,
19
+ type RbacPolicy,
20
+ type Actor,
35
21
  } from '@maykonpaulo/maestro-core';
36
- import type { Actor, RbacPolicy } from '@maykonpaulo/maestro-core';
37
22
 
38
- // Actor
39
- const actor: Actor = { id: 'user-1', type: 'user', roles: ['editor'] };
40
-
41
- // Auditoria
42
- const audit = new AuditRecorder(new InMemoryAuditRepository());
43
- await audit.record({ action: 'contract.updated', actor });
23
+ // 1. Implement or use a datasource provider
24
+ const datasource = new InMemoryDatasourceProvider();
25
+ datasource.seed('users', [
26
+ { id: 'u1', name: 'Alice', email: 'alice@example.com', active: true },
27
+ ]);
28
+
29
+ // 2. Define entities
30
+ const usersEntity: EntitySchema = {
31
+ id: 'users',
32
+ label: { singular: 'User', plural: 'Users' },
33
+ source: { datasource: 'main', table: 'users', primaryKey: 'id' },
34
+ capabilities: { list: true, detail: true, create: true, update: true, export: true },
35
+ fields: [
36
+ { name: 'id', label: 'ID', type: 'uuid', readonly: true },
37
+ { name: 'name', label: 'Name', type: 'string', required: true, searchable: true },
38
+ { name: 'email', label: 'Email', type: 'email', required: true },
39
+ { name: 'active', label: 'Active',type: 'boolean', filterable: true },
40
+ ],
41
+ };
44
42
 
45
- // RBAC
46
- const policy: RbacPolicy = {
43
+ // 3. Configure RBAC
44
+ const policies: RbacPolicy = {
47
45
  roles: {
48
- editor: { id: 'editor', name: 'editor', permissions: ['contracts.*'] },
46
+ admin: { id: 'admin', name: 'Admin', permissions: ['*'] },
47
+ viewer: { id: 'viewer', name: 'Viewer', permissions: ['entity.users.list', 'entity.users.detail'] },
49
48
  },
50
49
  };
51
- const rbac = new RbacEngine(policy);
52
- rbac.can(actor, 'contracts.update'); // true
53
-
54
- // Logging
55
- const logger = new ConsoleLogger('info');
56
- logger.info({ message: 'Operação concluída', correlationId: 'req-123' });
57
-
58
- // Feature flags
59
- const flags = new InMemoryFeatureFlagProvider([{ key: 'new-ui', enabled: true }]);
60
- await flags.isEnabled('new-ui', actor); // true
61
-
62
- // Config
63
- const config = new InMemoryConfigProvider({ 'app.name': 'meu-sistema' });
64
- config.get('app.name'); // 'meu-sistema'
65
-
66
- // Eventos
67
- const bus = new InMemoryEventBus();
68
- bus.subscribe('contract.updated', (event) => console.log(event));
69
- await bus.publish({ id: 'evt-1', type: 'contract.updated', payload: {}, occurredAt: new Date() });
70
- ```
71
-
72
- ## API pública
73
-
74
- Todas as exportações estão documentadas em `src/index.ts`. Importe apenas pelo nome do pacote:
75
-
76
- ```typescript
77
- import { ... } from '@maykonpaulo/maestro-core';
78
- ```
79
50
 
80
- ## Extensão com adapters próprios
81
-
82
- O Maestro expõe contratos bem definidos para cada módulo. Implemente a interface correspondente para integrar com qualquer banco, serviço ou infraestrutura:
83
-
84
- | Interface | Implementar quando quiser... |
85
- |----------------------|-------------------------------------------------------|
86
- | `AuditRepository` | Persistir eventos de auditoria em banco de dados |
87
- | `FeatureFlagProvider`| Gerenciar flags via banco, Redis ou serviço externo |
88
- | `ConfigProvider` | Carregar configurações de variáveis de ambiente ou DB |
89
- | `EventBus` | Publicar eventos em filas (RabbitMQ, SQS, etc.) |
90
- | `Logger` | Enviar logs para Pino, Winston, Datadog, etc. |
91
-
92
- ```typescript
93
- import type { AuditRepository, AuditEvent, AuditFilter } from '@maykonpaulo/maestro-core';
94
- import { AuditRecorder } from '@maykonpaulo/maestro-core';
95
-
96
- // Sua implementação concreta — qualquer banco, qualquer ORM
97
- class PrismaAuditRepository implements AuditRepository {
98
- async record(event: AuditEvent): Promise<void> {
99
- await db.auditEvent.create({ data: event });
100
- }
101
- async list(filter?: AuditFilter): Promise<AuditEvent[]> {
102
- return db.auditEvent.findMany({ where: filter });
103
- }
104
- }
105
-
106
- // Injeta no AuditRecorder — o core não sabe nem se importa com o banco
107
- const audit = new AuditRecorder(new PrismaAuditRepository());
51
+ // 4. Create the engine
52
+ const engine = createMaestro({
53
+ datasources: { main: datasource },
54
+ entities: [usersEntity],
55
+ policies,
56
+ audit: new InMemoryAuditRepository(),
57
+ });
58
+
59
+ // 5. Use the engine
60
+ const actor: Actor = { id: 'admin-1', type: 'user', roles: ['admin'] };
61
+
62
+ const result = await engine.list('users', {
63
+ filters: [{ field: 'active', operator: 'isTrue' }],
64
+ sort: [{ field: 'name', direction: 'asc' }],
65
+ pagination: { strategy: 'page', page: 1, pageSize: 20 },
66
+ }, actor);
67
+
68
+ const user = await engine.findById('users', 'u1', actor);
69
+ const created = await engine.create('users', { name: 'Bob', email: 'bob@example.com', active: true }, actor);
70
+ const exported = await engine.export('users', {}, actor, 'csv');
108
71
  ```
109
72
 
110
- As implementações `InMemory*` incluídas no pacote são funcionais para testes e desenvolvimento local.
73
+ ## Module reference
74
+
75
+ | Module | Exports |
76
+ |---|---|
77
+ | **Engine** | `createMaestro`, `MaestroEngine`, `MetadataEngine` |
78
+ | **Schema** | `EntitySchema`, `FieldSchema`, `RelationSchema`, `MaestroConfig`, `validateMaestroConfig` |
79
+ | **Metadata** | `EntityMetadata`, `FieldMetadata`, `RelationMetadata`, `MaestroMetadata`, `OperationMetadata`, `EntityCapabilities`, `DEFAULT_CAPABILITIES` |
80
+ | **Query** | `QueryInput`, `FilterDescriptor`, `FilterOperator`, `SortDescriptor`, `PaginationInput`, `SearchInput`, `ListResult` |
81
+ | **Datasource** | `DatasourceProvider`, `DatasourceRegistry`, `InMemoryDatasourceProvider` |
82
+ | **Operation** | `OperationDef`, `OperationContext`, `OperationResult`, `OperationRegistry` |
83
+ | **Export** | `ExportProvider`, `CsvExportProvider`, `ExportFormat`, `ExportResult`, `ExportOptions` |
84
+ | **RBAC** | `RbacEngine`, `RbacPolicy`, `Role`, `Permission` |
85
+ | **Audit** | `AuditRecorder`, `AuditRepository`, `AuditEvent`, `InMemoryAuditRepository` |
86
+ | **Logging** | `Logger`, `ConsoleLogger`, `LogLevel` |
87
+ | **Events** | `DomainEvent`, `EventBus`, `InMemoryEventBus` |
88
+ | **Feature Flags** | `FeatureFlagProvider`, `InMemoryFeatureFlagProvider` |
89
+ | **Config** | `ConfigProvider`, `InMemoryConfigProvider` |
90
+ | **Errors** | `MaestroError`, `ErrorCode` |
91
+ | **Types** | `Actor`, `Metadata`, `ResourceRef` |
92
+
93
+ ## Filter operators
94
+
95
+ `equals`, `notEquals`, `contains`, `startsWith`, `endsWith`, `in`, `notIn`, `gt`, `gte`, `lt`, `lte`, `between`, `isNull`, `isNotNull`, `isTrue`, `isFalse`
96
+
97
+ ## Permission patterns
98
+
99
+ | Pattern | Matches |
100
+ |---|---|
101
+ | `*` | Everything |
102
+ | `entity.users.list` | Exact permission |
103
+ | `entity.users.*` | All operations on users entity |
104
+ | `entity.*.list` | List on all entities |
105
+
106
+ ## Design constraints
107
+
108
+ The core has **zero runtime dependencies** on:
109
+ - Any web framework (Express, Nest, Fastify...)
110
+ - Any ORM (Prisma, TypeORM, Sequelize...)
111
+ - Any database (PostgreSQL, MySQL, MongoDB...)
112
+ - React or any UI library
113
+
114
+ You provide a `DatasourceProvider` implementation. Maestro handles everything else.