@macss/modular-api 0.4.3 → 0.4.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/core/health/health_check.js +3 -0
- package/dist/core/health/health_service.js +7 -1
- package/dist/core/input_validation_error.d.ts +10 -0
- package/dist/core/input_validation_error.js +26 -0
- package/dist/core/logger/logger.js +4 -0
- package/dist/core/metrics/metric.d.ts +100 -0
- package/dist/core/metrics/metric.js +284 -0
- package/dist/core/metrics/metric_registry.d.ts +40 -13
- package/dist/core/metrics/metric_registry.js +87 -29
- package/dist/core/metrics/metrics_middleware.d.ts +3 -3
- package/dist/core/metrics/metrics_middleware.js +3 -2
- package/dist/core/modular_api.js +21 -5
- package/dist/core/module_builder.d.ts +13 -4
- package/dist/core/module_builder.js +35 -25
- package/dist/core/registry.d.ts +3 -2
- package/dist/core/registry.js +1 -3
- package/dist/core/schema/field.d.ts +60 -0
- package/dist/core/schema/field.js +100 -0
- package/dist/core/use_case_exception.js +4 -0
- package/dist/core/usecase.d.ts +42 -29
- package/dist/core/usecase.js +165 -15
- package/dist/core/usecase_handler.d.ts +17 -9
- package/dist/core/usecase_handler.js +28 -11
- package/dist/index.d.ts +6 -0
- package/dist/index.js +16 -2
- package/dist/openapi/openapi.js +11 -6
- package/dist/openapi/swagger_docs.d.ts +21 -0
- package/dist/openapi/swagger_docs.js +223 -0
- package/package.json +1 -1
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
// ============================================================
|
|
3
3
|
// core/metrics/metric_registry.ts
|
|
4
|
-
//
|
|
5
|
-
// MetricRegistry — internal, manages
|
|
4
|
+
// Pure TypeScript metric registry — zero external dependencies.
|
|
5
|
+
// MetricRegistry — internal, manages all metrics + serialization
|
|
6
6
|
// MetricsRegistrar — public, validates names before delegating
|
|
7
|
+
// Mirror of metric_registry.dart and metric_registry.py.
|
|
7
8
|
// ============================================================
|
|
8
9
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
10
|
exports.MetricsRegistrar = exports.MetricRegistry = void 0;
|
|
10
|
-
const
|
|
11
|
+
const metric_1 = require("./metric");
|
|
11
12
|
/** Prometheus metric name regex. */
|
|
12
13
|
const VALID_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
|
|
13
14
|
function assertValidName(name) {
|
|
@@ -15,70 +16,127 @@ function assertValidName(name) {
|
|
|
15
16
|
throw new Error(`Invalid metric name "${name}": must match [a-zA-Z_:][a-zA-Z0-9_:]*`);
|
|
16
17
|
}
|
|
17
18
|
}
|
|
18
|
-
|
|
19
|
+
function metricType(m) {
|
|
20
|
+
return m.type;
|
|
21
|
+
}
|
|
22
|
+
// ── MetricRegistry (internal) ─────────────────────────────────
|
|
19
23
|
/**
|
|
20
|
-
* Internal registry
|
|
24
|
+
* Internal registry that holds all metrics and serializes them.
|
|
21
25
|
*
|
|
22
26
|
* On construction, registers `process_start_time_seconds` as a gauge
|
|
23
27
|
* set to the current epoch in seconds.
|
|
24
28
|
*/
|
|
25
29
|
class MetricRegistry {
|
|
30
|
+
_metrics = [];
|
|
31
|
+
_names = new Set();
|
|
26
32
|
constructor() {
|
|
27
|
-
|
|
28
|
-
this.registry = new prom_client_1.Registry();
|
|
29
|
-
// Auto-register process_start_time_seconds.
|
|
30
|
-
const startTime = this.createGauge({
|
|
33
|
+
const gauge = this.createGauge({
|
|
31
34
|
name: 'process_start_time_seconds',
|
|
32
35
|
help: 'Start time of the process since unix epoch in seconds.',
|
|
33
36
|
});
|
|
34
|
-
|
|
37
|
+
gauge.set(Date.now() / 1000);
|
|
35
38
|
}
|
|
36
39
|
createCounter(config) {
|
|
37
40
|
this.assertUnique(config.name);
|
|
38
|
-
const counter = new
|
|
39
|
-
|
|
40
|
-
registers: [this.registry],
|
|
41
|
-
});
|
|
41
|
+
const counter = new metric_1.Counter({ name: config.name, help: config.help });
|
|
42
|
+
this._metrics.push({ name: config.name, help: config.help, metric: counter });
|
|
42
43
|
return counter;
|
|
43
44
|
}
|
|
44
45
|
createGauge(config) {
|
|
45
46
|
this.assertUnique(config.name);
|
|
46
|
-
const gauge = new
|
|
47
|
-
|
|
48
|
-
registers: [this.registry],
|
|
49
|
-
});
|
|
47
|
+
const gauge = new metric_1.Gauge({ name: config.name, help: config.help });
|
|
48
|
+
this._metrics.push({ name: config.name, help: config.help, metric: gauge });
|
|
50
49
|
return gauge;
|
|
51
50
|
}
|
|
52
51
|
createHistogram(config) {
|
|
53
52
|
this.assertUnique(config.name);
|
|
54
|
-
const histogram = new
|
|
55
|
-
|
|
56
|
-
|
|
53
|
+
const histogram = new metric_1.Histogram({
|
|
54
|
+
name: config.name,
|
|
55
|
+
help: config.help,
|
|
56
|
+
buckets: config.buckets,
|
|
57
57
|
});
|
|
58
|
+
this._metrics.push({ name: config.name, help: config.help, metric: histogram });
|
|
58
59
|
return histogram;
|
|
59
60
|
}
|
|
60
61
|
/** Serializes all metrics to Prometheus text exposition format. */
|
|
61
|
-
|
|
62
|
-
|
|
62
|
+
serialize() {
|
|
63
|
+
const lines = [];
|
|
64
|
+
for (let i = 0; i < this._metrics.length; i++) {
|
|
65
|
+
const entry = this._metrics[i];
|
|
66
|
+
// Blank line between metric families (not before the first one).
|
|
67
|
+
if (i > 0)
|
|
68
|
+
lines.push('');
|
|
69
|
+
lines.push(`# HELP ${entry.name} ${entry.help}`);
|
|
70
|
+
lines.push(`# TYPE ${entry.name} ${metricType(entry.metric)}`);
|
|
71
|
+
const metric = entry.metric;
|
|
72
|
+
if (metric instanceof metric_1.Counter) {
|
|
73
|
+
this.serializeCounter(lines, metric);
|
|
74
|
+
}
|
|
75
|
+
else if (metric instanceof metric_1.Gauge) {
|
|
76
|
+
this.serializeGauge(lines, metric);
|
|
77
|
+
}
|
|
78
|
+
else if (metric instanceof metric_1.Histogram) {
|
|
79
|
+
this.serializeHistogram(lines, metric);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return lines.join('\n') + '\n';
|
|
83
|
+
}
|
|
84
|
+
serializeCounter(lines, counter) {
|
|
85
|
+
const samples = counter.collect();
|
|
86
|
+
if (samples.length === 0)
|
|
87
|
+
return;
|
|
88
|
+
for (const s of samples) {
|
|
89
|
+
lines.push(`${counter.name}${formatLabels(s.labels)} ${formatValue(s.value)}`);
|
|
90
|
+
}
|
|
63
91
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
92
|
+
serializeGauge(lines, gauge) {
|
|
93
|
+
const samples = gauge.collect();
|
|
94
|
+
if (samples.length === 0) {
|
|
95
|
+
// Root gauge with no labeled children — emit the root value.
|
|
96
|
+
lines.push(`${gauge.name} ${formatValue(gauge.value)}`);
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
for (const s of samples) {
|
|
100
|
+
lines.push(`${gauge.name}${formatLabels(s.labels)} ${formatValue(s.value)}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
serializeHistogram(lines, histogram) {
|
|
105
|
+
const samples = histogram.collect();
|
|
106
|
+
if (samples.length === 0)
|
|
107
|
+
return;
|
|
108
|
+
for (const s of samples) {
|
|
109
|
+
lines.push(`${histogram.name}${s.suffix}${formatLabels(s.labels)} ${formatValue(s.value)}`);
|
|
110
|
+
}
|
|
67
111
|
}
|
|
68
112
|
assertUnique(name) {
|
|
69
|
-
if (this.
|
|
113
|
+
if (this._names.has(name)) {
|
|
70
114
|
throw new Error(`Metric "${name}" is already registered.`);
|
|
71
115
|
}
|
|
72
|
-
this.
|
|
116
|
+
this._names.add(name);
|
|
73
117
|
}
|
|
74
118
|
}
|
|
75
119
|
exports.MetricRegistry = MetricRegistry;
|
|
76
|
-
// ──
|
|
120
|
+
// ── Serialization helpers ─────────────────────────────────────
|
|
121
|
+
function formatLabels(labels) {
|
|
122
|
+
const keys = Object.keys(labels);
|
|
123
|
+
if (keys.length === 0)
|
|
124
|
+
return '';
|
|
125
|
+
const pairs = keys.map((k) => `${k}="${labels[k]}"`).join(',');
|
|
126
|
+
return `{${pairs}}`;
|
|
127
|
+
}
|
|
128
|
+
function formatValue(v) {
|
|
129
|
+
if (Number.isInteger(v))
|
|
130
|
+
return String(v);
|
|
131
|
+
return String(v);
|
|
132
|
+
}
|
|
133
|
+
// ── MetricsRegistrar (public) ─────────────────────────────────
|
|
77
134
|
/**
|
|
78
135
|
* Public API for users to register custom metrics.
|
|
79
136
|
* Validates names and rejects reserved prefixes before delegating.
|
|
80
137
|
*/
|
|
81
138
|
class MetricsRegistrar {
|
|
139
|
+
registry;
|
|
82
140
|
constructor(registry) {
|
|
83
141
|
this.registry = registry;
|
|
84
142
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { RequestHandler } from 'express';
|
|
2
|
-
import type { Counter, Gauge, Histogram } from '
|
|
2
|
+
import type { Counter, Gauge, Histogram } from './metric';
|
|
3
3
|
import type { MetricRegistry } from './metric_registry';
|
|
4
4
|
export interface MetricsMiddlewareOptions {
|
|
5
|
-
requestsTotal: Counter
|
|
5
|
+
requestsTotal: Counter;
|
|
6
6
|
requestsInFlight: Gauge;
|
|
7
|
-
requestDuration: Histogram
|
|
7
|
+
requestDuration: Histogram;
|
|
8
8
|
excludedRoutes: string[];
|
|
9
9
|
registeredPaths: string[];
|
|
10
10
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// ============================================================
|
|
3
3
|
// core/metrics/metrics_middleware.ts
|
|
4
4
|
// Express middleware + handler for Prometheus metrics.
|
|
5
|
+
// Zero external dependencies — uses pure metric types.
|
|
5
6
|
// ============================================================
|
|
6
7
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
8
|
exports.metricsMiddleware = metricsMiddleware;
|
|
@@ -44,8 +45,8 @@ function metricsMiddleware(opts) {
|
|
|
44
45
|
* Always returns HTTP 200 with `text/plain; version=0.0.4; charset=utf-8`.
|
|
45
46
|
*/
|
|
46
47
|
function metricsHandler(registry) {
|
|
47
|
-
return
|
|
48
|
-
const body =
|
|
48
|
+
return (_req, res) => {
|
|
49
|
+
const body = registry.serialize();
|
|
49
50
|
res.status(200).set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8').send(body);
|
|
50
51
|
};
|
|
51
52
|
}
|
package/dist/core/modular_api.js
CHANGED
|
@@ -12,7 +12,7 @@ exports.ModularApi = void 0;
|
|
|
12
12
|
const express_1 = __importDefault(require("express"));
|
|
13
13
|
const module_builder_1 = require("./module_builder");
|
|
14
14
|
const openapi_1 = require("../openapi/openapi");
|
|
15
|
-
const
|
|
15
|
+
const swagger_docs_1 = require("../openapi/swagger_docs");
|
|
16
16
|
const health_service_1 = require("./health/health_service");
|
|
17
17
|
const health_handler_1 = require("./health/health_handler");
|
|
18
18
|
const metric_registry_1 = require("./metrics/metric_registry");
|
|
@@ -42,12 +42,28 @@ const registry_1 = require("./registry");
|
|
|
42
42
|
* GET /docs → Swagger UI
|
|
43
43
|
*/
|
|
44
44
|
class ModularApi {
|
|
45
|
+
app;
|
|
46
|
+
rootRouter;
|
|
47
|
+
basePath;
|
|
48
|
+
title;
|
|
49
|
+
middlewares = [];
|
|
50
|
+
healthService;
|
|
51
|
+
// Metrics
|
|
52
|
+
metricsEnabled;
|
|
53
|
+
metricsPath;
|
|
54
|
+
excludedMetricsRoutes;
|
|
55
|
+
metricRegistry;
|
|
56
|
+
_metricsRegistrar;
|
|
57
|
+
httpRequestsTotal;
|
|
58
|
+
httpRequestsInFlight;
|
|
59
|
+
httpRequestDuration;
|
|
60
|
+
// Logging
|
|
61
|
+
logLevel;
|
|
45
62
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
46
63
|
get metrics() {
|
|
47
64
|
return this._metricsRegistrar;
|
|
48
65
|
}
|
|
49
66
|
constructor(options = {}) {
|
|
50
|
-
this.middlewares = [];
|
|
51
67
|
this.basePath = options.basePath ?? '/api';
|
|
52
68
|
this.title = options.title ?? 'Modular API';
|
|
53
69
|
this.healthService = new health_service_1.HealthService({
|
|
@@ -172,10 +188,10 @@ class ModularApi {
|
|
|
172
188
|
this.app.get('/health', (0, health_handler_1.healthHandler)(this.healthService));
|
|
173
189
|
// Module use case routes.
|
|
174
190
|
this.app.use(this.rootRouter);
|
|
175
|
-
// Swagger
|
|
176
|
-
|
|
177
|
-
this.app.use('/docs', swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(spec));
|
|
191
|
+
// Swagger UI docs — inline HTML, no external dependency (PRD-003).
|
|
192
|
+
this.app.get('/docs', (0, swagger_docs_1.swaggerDocsHandler)({ title: this.title }));
|
|
178
193
|
// Raw spec endpoints
|
|
194
|
+
const spec = (0, openapi_1.buildOpenApiSpec)({ title: this.title, port });
|
|
179
195
|
this.app.get('/openapi.json', (0, openapi_1.openApiJsonHandler)(spec));
|
|
180
196
|
this.app.get('/openapi.yaml', (0, openapi_1.openApiYamlHandler)(spec));
|
|
181
197
|
const server = this.app.listen(port, host, () => {
|
|
@@ -10,6 +10,10 @@ export interface UseCaseOptions {
|
|
|
10
10
|
inputSchema?: Record<string, unknown>;
|
|
11
11
|
/** Override output schema for OpenAPI (if fromJson fails with empty data) */
|
|
12
12
|
outputSchema?: Record<string, unknown>;
|
|
13
|
+
/** Input class for pre-validation and schema extraction (enables strict fromJson). */
|
|
14
|
+
inputClass: abstract new (...args: unknown[]) => Input;
|
|
15
|
+
/** Output class for schema extraction. */
|
|
16
|
+
outputClass: abstract new (...args: unknown[]) => Output;
|
|
13
17
|
}
|
|
14
18
|
/**
|
|
15
19
|
* Fluent builder that registers use cases on a module-scoped Express Router.
|
|
@@ -34,12 +38,17 @@ export declare class ModuleBuilder {
|
|
|
34
38
|
/**
|
|
35
39
|
* Registers a use case as an HTTP endpoint.
|
|
36
40
|
*
|
|
37
|
-
* @param
|
|
41
|
+
* @param command Route segment and operationId root, e.g. 'hello-world' → POST /api/greetings/hello-world.
|
|
42
|
+
* Convention: command, class name, and file name share the same root.
|
|
38
43
|
* @param factory The static `fromJson` of your UseCase class
|
|
39
|
-
* @param options
|
|
44
|
+
* @param options HTTP method, inputClass/outputClass, and optional OpenAPI metadata
|
|
45
|
+
*/
|
|
46
|
+
usecase<I extends Input, O extends Output>(command: string, factory: UseCaseFactory<I, O>, options: UseCaseOptions): this;
|
|
47
|
+
/**
|
|
48
|
+
* Capture Input and Output schemas from decorator metadata.
|
|
49
|
+
*
|
|
50
|
+
* Uses @Field metadata from inputClass/outputClass to build schemas.
|
|
40
51
|
*/
|
|
41
|
-
usecase<I extends Input, O extends Output>(name: string, factory: UseCaseFactory<I, O>, options?: UseCaseOptions): this;
|
|
42
|
-
/** Try to get schemas from a dummy factory call. Fails gracefully. */
|
|
43
52
|
private _extractSchemas;
|
|
44
53
|
/** @internal — called by ModularApi after the builder callback runs */
|
|
45
54
|
_mount(): void;
|
|
@@ -9,6 +9,7 @@ exports.ModuleBuilder = void 0;
|
|
|
9
9
|
const express_1 = require("express");
|
|
10
10
|
const usecase_handler_1 = require("./usecase_handler");
|
|
11
11
|
const registry_1 = require("./registry");
|
|
12
|
+
const field_1 = require("./schema/field");
|
|
12
13
|
/**
|
|
13
14
|
* Fluent builder that registers use cases on a module-scoped Express Router.
|
|
14
15
|
* Returned and used inside the callback of `ModularApi.module()`.
|
|
@@ -24,6 +25,10 @@ const registry_1 = require("./registry");
|
|
|
24
25
|
* });
|
|
25
26
|
*/
|
|
26
27
|
class ModuleBuilder {
|
|
28
|
+
basePath;
|
|
29
|
+
moduleName;
|
|
30
|
+
rootRouter;
|
|
31
|
+
router;
|
|
27
32
|
constructor(basePath, moduleName, rootRouter) {
|
|
28
33
|
this.basePath = basePath;
|
|
29
34
|
this.moduleName = moduleName;
|
|
@@ -33,20 +38,20 @@ class ModuleBuilder {
|
|
|
33
38
|
/**
|
|
34
39
|
* Registers a use case as an HTTP endpoint.
|
|
35
40
|
*
|
|
36
|
-
* @param
|
|
41
|
+
* @param command Route segment and operationId root, e.g. 'hello-world' → POST /api/greetings/hello-world.
|
|
42
|
+
* Convention: command, class name, and file name share the same root.
|
|
37
43
|
* @param factory The static `fromJson` of your UseCase class
|
|
38
|
-
* @param options
|
|
44
|
+
* @param options HTTP method, inputClass/outputClass, and optional OpenAPI metadata
|
|
39
45
|
*/
|
|
40
|
-
usecase(
|
|
41
|
-
const { method = 'POST', summary, description, inputSchema, outputSchema } = options;
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
const subPath = `/${cleanName}`;
|
|
46
|
+
usecase(command, factory, options) {
|
|
47
|
+
const { method = 'POST', summary, description, inputSchema, outputSchema, inputClass, outputClass } = options;
|
|
48
|
+
const cleanCommand = command.trim().replace(/^\//g, '');
|
|
49
|
+
const subPath = `/${cleanCommand}`;
|
|
45
50
|
const methodL = method.toLowerCase();
|
|
46
|
-
// Mount the Express handler
|
|
47
|
-
this.router[methodL](subPath, (0, usecase_handler_1.useCaseHandler)(factory));
|
|
48
|
-
//
|
|
49
|
-
const extracted = this._extractSchemas(
|
|
51
|
+
// Mount the Express handler (with optional pre-validation)
|
|
52
|
+
this.router[methodL](subPath, (0, usecase_handler_1.useCaseHandler)(factory, { inputClass }));
|
|
53
|
+
// Capture schemas from @Field decorator metadata
|
|
54
|
+
const extracted = this._extractSchemas(inputClass, outputClass);
|
|
50
55
|
const schemas = {
|
|
51
56
|
input: inputSchema ?? extracted.input,
|
|
52
57
|
output: outputSchema ?? extracted.output,
|
|
@@ -54,31 +59,36 @@ class ModuleBuilder {
|
|
|
54
59
|
// Register in the global registry for OpenAPI generation
|
|
55
60
|
registry_1.apiRegistry.routes.push({
|
|
56
61
|
module: this.moduleName,
|
|
57
|
-
|
|
62
|
+
command: cleanCommand,
|
|
58
63
|
method: method,
|
|
59
|
-
path: `${this._normalizeBase(this.basePath)}/${this.moduleName}/${
|
|
64
|
+
path: `${this._normalizeBase(this.basePath)}/${this.moduleName}/${cleanCommand}`,
|
|
60
65
|
factory: factory,
|
|
61
66
|
schemas,
|
|
62
67
|
doc: {
|
|
63
|
-
summary: summary ?? `Use case ${
|
|
64
|
-
description: description ?? `Auto-generated documentation for ${
|
|
68
|
+
summary: summary ?? `Use case ${cleanCommand} in module ${this.moduleName}`,
|
|
69
|
+
description: description ?? `Auto-generated documentation for ${cleanCommand}`,
|
|
65
70
|
tags: [this.moduleName],
|
|
66
71
|
},
|
|
67
72
|
});
|
|
68
73
|
return this;
|
|
69
74
|
}
|
|
70
|
-
/**
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
/**
|
|
76
|
+
* Capture Input and Output schemas from decorator metadata.
|
|
77
|
+
*
|
|
78
|
+
* Uses @Field metadata from inputClass/outputClass to build schemas.
|
|
79
|
+
*/
|
|
80
|
+
_extractSchemas(inputClass, outputClass) {
|
|
81
|
+
let input = {};
|
|
82
|
+
let output = {};
|
|
83
|
+
const inputFields = (0, field_1.getFieldMetadata)(inputClass);
|
|
84
|
+
if (inputFields.length > 0) {
|
|
85
|
+
input = new inputClass().toSchema();
|
|
78
86
|
}
|
|
79
|
-
|
|
80
|
-
|
|
87
|
+
const outputFields = (0, field_1.getFieldMetadata)(outputClass);
|
|
88
|
+
if (outputFields.length > 0) {
|
|
89
|
+
output = new outputClass().toSchema();
|
|
81
90
|
}
|
|
91
|
+
return { input, output };
|
|
82
92
|
}
|
|
83
93
|
/** @internal — called by ModularApi after the builder callback runs */
|
|
84
94
|
_mount() {
|
package/dist/core/registry.d.ts
CHANGED
|
@@ -12,10 +12,11 @@ export interface UseCaseDocMeta {
|
|
|
12
12
|
}
|
|
13
13
|
export interface UseCaseRegistration {
|
|
14
14
|
module: string;
|
|
15
|
-
|
|
15
|
+
/** Route segment and operationId root, e.g. 'hello-world' */
|
|
16
|
+
command: string;
|
|
16
17
|
/** HTTP method in uppercase: "POST" | "GET" | "PUT" | "PATCH" | "DELETE" */
|
|
17
18
|
method: string;
|
|
18
|
-
/** Full path e.g. "/api/
|
|
19
|
+
/** Full path e.g. "/api/v1/greetings/hello-world" */
|
|
19
20
|
path: string;
|
|
20
21
|
factory: UseCaseFactory<Input, Output>;
|
|
21
22
|
doc?: UseCaseDocMeta;
|
package/dist/core/registry.js
CHANGED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
declare global {
|
|
2
|
+
interface SymbolConstructor {
|
|
3
|
+
readonly metadata: unique symbol;
|
|
4
|
+
}
|
|
5
|
+
}
|
|
6
|
+
/** Metadata stored per decorated field. */
|
|
7
|
+
export interface FieldMeta {
|
|
8
|
+
name: string;
|
|
9
|
+
type: 'string' | 'integer' | 'number' | 'boolean' | 'array';
|
|
10
|
+
description?: string;
|
|
11
|
+
required: boolean;
|
|
12
|
+
nullable: boolean;
|
|
13
|
+
items?: {
|
|
14
|
+
type: string;
|
|
15
|
+
};
|
|
16
|
+
example?: unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Options accepted by every primitive Field decorator. */
|
|
19
|
+
export interface FieldOptions {
|
|
20
|
+
description?: string;
|
|
21
|
+
example?: unknown;
|
|
22
|
+
}
|
|
23
|
+
type FieldDecorator = (value: undefined, context: ClassFieldDecoratorContext) => void;
|
|
24
|
+
/** Internal marker returned by primitive Field methods for use with Field.optional(). */
|
|
25
|
+
interface PendingField {
|
|
26
|
+
__pending: true;
|
|
27
|
+
type: FieldMeta['type'];
|
|
28
|
+
options: FieldOptions;
|
|
29
|
+
extra: Partial<FieldMeta>;
|
|
30
|
+
}
|
|
31
|
+
export declare const Field: {
|
|
32
|
+
string(options?: FieldOptions): FieldDecorator & PendingField;
|
|
33
|
+
integer(options?: FieldOptions): FieldDecorator & PendingField;
|
|
34
|
+
number(options?: FieldOptions): FieldDecorator & PendingField;
|
|
35
|
+
boolean(options?: FieldOptions): FieldDecorator & PendingField;
|
|
36
|
+
/**
|
|
37
|
+
* Marks a field as optional (nullable, not required).
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* @Field.optional(Field.string({ description: 'Nickname' }))
|
|
41
|
+
* nickname?: string;
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
optional(inner: PendingField): FieldDecorator;
|
|
45
|
+
/**
|
|
46
|
+
* Array field with typed items.
|
|
47
|
+
*
|
|
48
|
+
* ```ts
|
|
49
|
+
* @Field.array(Field.string(), { description: 'tags' })
|
|
50
|
+
* tags!: string[];
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
array(itemType: PendingField, options?: FieldOptions): FieldDecorator & PendingField;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Retrieves the `@Field` metadata registered on a class.
|
|
57
|
+
* Returns an empty array if the class has no decorated fields.
|
|
58
|
+
*/
|
|
59
|
+
export declare function getFieldMetadata(target: abstract new (...args: unknown[]) => unknown): FieldMeta[];
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================
|
|
3
|
+
// core/schema/field.ts
|
|
4
|
+
// Stage 3 decorators that store OpenAPI-compatible field metadata.
|
|
5
|
+
//
|
|
6
|
+
// Usage:
|
|
7
|
+
// class HelloInput extends Input {
|
|
8
|
+
// @Field.string({ description: 'Name to greet' })
|
|
9
|
+
// name!: string;
|
|
10
|
+
//
|
|
11
|
+
// @Field.optional(Field.integer({ description: 'Age' }))
|
|
12
|
+
// age?: number;
|
|
13
|
+
// }
|
|
14
|
+
//
|
|
15
|
+
// At runtime, `getFieldMetadata(HelloInput)` returns the list of
|
|
16
|
+
// FieldMeta entries in declaration order, which Input.toSchema()
|
|
17
|
+
// uses to build an OpenAPI 3.0.3-compatible JSON Schema.
|
|
18
|
+
// ============================================================
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.Field = void 0;
|
|
21
|
+
exports.getFieldMetadata = getFieldMetadata;
|
|
22
|
+
Symbol.metadata ??= Symbol('Symbol.metadata');
|
|
23
|
+
// ── Internal storage key ─────────────────────────────────────
|
|
24
|
+
const FIELD_KEY = Symbol('FieldMeta');
|
|
25
|
+
function makeFieldDecorator(type, options = {}, extra = {}) {
|
|
26
|
+
return function (_value, context) {
|
|
27
|
+
const meta = {
|
|
28
|
+
name: String(context.name),
|
|
29
|
+
type,
|
|
30
|
+
description: options.description,
|
|
31
|
+
required: true,
|
|
32
|
+
nullable: false,
|
|
33
|
+
...extra,
|
|
34
|
+
};
|
|
35
|
+
if (options.example !== undefined) {
|
|
36
|
+
meta.example = options.example;
|
|
37
|
+
}
|
|
38
|
+
const metadata = context.metadata;
|
|
39
|
+
if (!metadata[FIELD_KEY]) {
|
|
40
|
+
metadata[FIELD_KEY] = [];
|
|
41
|
+
}
|
|
42
|
+
metadata[FIELD_KEY].push(meta);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// ── Public API ───────────────────────────────────────────────
|
|
46
|
+
exports.Field = {
|
|
47
|
+
string(options = {}) {
|
|
48
|
+
const decorator = makeFieldDecorator('string', options);
|
|
49
|
+
return Object.assign(decorator, { __pending: true, type: 'string', options, extra: {} });
|
|
50
|
+
},
|
|
51
|
+
integer(options = {}) {
|
|
52
|
+
const decorator = makeFieldDecorator('integer', options);
|
|
53
|
+
return Object.assign(decorator, { __pending: true, type: 'integer', options, extra: {} });
|
|
54
|
+
},
|
|
55
|
+
number(options = {}) {
|
|
56
|
+
const decorator = makeFieldDecorator('number', options);
|
|
57
|
+
return Object.assign(decorator, { __pending: true, type: 'number', options, extra: {} });
|
|
58
|
+
},
|
|
59
|
+
boolean(options = {}) {
|
|
60
|
+
const decorator = makeFieldDecorator('boolean', options);
|
|
61
|
+
return Object.assign(decorator, { __pending: true, type: 'boolean', options, extra: {} });
|
|
62
|
+
},
|
|
63
|
+
/**
|
|
64
|
+
* Marks a field as optional (nullable, not required).
|
|
65
|
+
*
|
|
66
|
+
* ```ts
|
|
67
|
+
* @Field.optional(Field.string({ description: 'Nickname' }))
|
|
68
|
+
* nickname?: string;
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
optional(inner) {
|
|
72
|
+
return makeFieldDecorator(inner.type, inner.options, {
|
|
73
|
+
...inner.extra,
|
|
74
|
+
required: false,
|
|
75
|
+
nullable: true,
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
/**
|
|
79
|
+
* Array field with typed items.
|
|
80
|
+
*
|
|
81
|
+
* ```ts
|
|
82
|
+
* @Field.array(Field.string(), { description: 'tags' })
|
|
83
|
+
* tags!: string[];
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
array(itemType, options = {}) {
|
|
87
|
+
const extra = { items: { type: itemType.type } };
|
|
88
|
+
const decorator = makeFieldDecorator('array', options, extra);
|
|
89
|
+
return Object.assign(decorator, { __pending: true, type: 'array', options, extra });
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
// ── Public accessor ──────────────────────────────────────────
|
|
93
|
+
/**
|
|
94
|
+
* Retrieves the `@Field` metadata registered on a class.
|
|
95
|
+
* Returns an empty array if the class has no decorated fields.
|
|
96
|
+
*/
|
|
97
|
+
function getFieldMetadata(target) {
|
|
98
|
+
const metadata = target[Symbol.metadata];
|
|
99
|
+
return metadata?.[FIELD_KEY] ?? [];
|
|
100
|
+
}
|