@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.
@@ -1,45 +1,65 @@
1
1
  import type { ModularLogger } from './logger/logger';
2
2
  /**
3
- * **Contract** — use `implements Input`.
3
+ * **Contract** — use `extends Input`.
4
4
  *
5
- * Pure interface: all members must be provided by the implementor.
6
- * No default behavior is inherited — every Input is self-contained.
5
+ * When subclass fields are decorated with `@Field`, `toJson()` and
6
+ * `toSchema()` are provided automatically. Manual overrides still work
7
+ * (deprecated — will be removed in v0.5.0).
7
8
  *
8
9
  * ```ts
9
- * class HelloInput implements Input {
10
- * constructor(readonly name: string) {}
11
- * toJson() { return { name: this.name }; }
12
- * toSchema() { return { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }; }
10
+ * class HelloInput extends Input {
11
+ * @Field.string({ description: 'Name to greet' })
12
+ * name!: string;
13
+ *
14
+ * static fromJson(json: Record<string, unknown>) {
15
+ * const instance = new HelloInput();
16
+ * instance.name = (json['name'] ?? '').toString();
17
+ * return instance;
18
+ * }
13
19
  * }
14
20
  * ```
15
21
  */
16
22
  export declare abstract class Input {
17
- abstract toJson(): Record<string, unknown>;
23
+ constructor();
24
+ toJson(): Record<string, unknown>;
18
25
  /**
19
26
  * Returns an OpenAPI-compatible JSON Schema describing this input.
20
- * Used to auto-generate Swagger documentation.
27
+ * Derived automatically from `@Field` decorators when present.
28
+ */
29
+ toSchema(): Record<string, unknown>;
30
+ /**
31
+ * Validates raw JSON against `@Field` metadata of `targetClass`.
32
+ *
33
+ * Throws {@link InputValidationError} when a required field is missing
34
+ * or has the wrong JSON type. The handler catches this and returns 400.
35
+ *
36
+ * Error messages follow the cross-SDK parity contract:
37
+ * - `"Missing required field: {name}"`
38
+ * - `"Field '{name}' must be of type {type}"`
21
39
  */
22
- abstract toSchema(): Record<string, unknown>;
40
+ static validateJson(json: Record<string, unknown>, targetClass: abstract new (...args: unknown[]) => unknown): void;
23
41
  }
24
42
  /**
25
- * **Contract** — use `implements Output`.
43
+ * **Contract** — use `extends Output`.
26
44
  *
27
- * Pure interface: all members must be provided by the implementor.
28
- * The implementor must define `statusCode` explicitly — this forces
29
- * developers to think about HTTP status codes for every response.
45
+ * When subclass fields are decorated with `@Field`, `toJson()` and
46
+ * `toSchema()` are provided automatically. The implementor must define
47
+ * `statusCode` explicitly — this forces developers to think about
48
+ * HTTP status codes for every response.
30
49
  *
31
50
  * ```ts
32
- * class HelloOutput implements Output {
33
- * constructor(readonly message: string) {}
51
+ * class HelloOutput extends Output {
52
+ * @Field.string({ description: 'Greeting message' })
53
+ * message!: string;
54
+ *
34
55
  * get statusCode() { return 200; }
35
- * toJson() { return { message: this.message }; }
36
- * toSchema() { return { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] }; }
37
56
  * }
38
57
  * ```
39
58
  */
40
59
  export declare abstract class Output {
41
- abstract toJson(): Record<string, unknown>;
42
- abstract toSchema(): Record<string, unknown>;
60
+ constructor();
61
+ toJson(): Record<string, unknown>;
62
+ toSchema(): Record<string, unknown>;
43
63
  /**
44
64
  * HTTP status code for the response.
45
65
  * Must be implemented explicitly (e.g. 200, 201, 400, 404).
@@ -93,8 +113,6 @@ export type UseCaseFactory<I extends Input = Input, O extends Output = Output> =
93
113
  export declare abstract class UseCase<I extends Input, O extends Output> {
94
114
  /** Input DTO — set in constructor. */
95
115
  abstract readonly input: I;
96
- /** Output DTO — set in execute(). */
97
- abstract output: O;
98
116
  /**
99
117
  * Request-scoped logger injected by the framework's logging middleware.
100
118
  * Available inside `execute()`. Undefined when running without middleware
@@ -108,13 +126,8 @@ export declare abstract class UseCase<I extends Input, O extends Output> {
108
126
  */
109
127
  abstract validate(): string | null;
110
128
  /**
111
- * Business logic. Must set `this.output` before returning.
129
+ * Business logic. Returns the Output DTO.
112
130
  * Keep this method free of HTTP concerns.
113
131
  */
114
- abstract execute(): Promise<void>;
115
- /**
116
- * Serializes the output DTO to a plain object for the HTTP response.
117
- * Typically implemented as `return this.output.toJson();`
118
- */
119
- abstract toJson(): Record<string, unknown>;
132
+ abstract execute(): Promise<O>;
120
133
  }
@@ -6,40 +6,184 @@
6
6
  // ============================================================
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.UseCase = exports.Output = exports.Input = void 0;
9
+ const field_1 = require("./schema/field");
10
+ const input_validation_error_1 = require("./input_validation_error");
9
11
  /**
10
- * **Contract** — use `implements Input`.
12
+ * Build an OpenAPI 3.0.3 JSON Schema from `@Field` decorator metadata.
13
+ * Shared by both Input and Output base classes.
14
+ */
15
+ function buildSchemaFromMetadata(fields) {
16
+ const properties = {};
17
+ const required = [];
18
+ const exampleValues = {};
19
+ for (const field of fields) {
20
+ const prop = { type: field.type };
21
+ if (field.description)
22
+ prop.description = field.description;
23
+ if (field.nullable)
24
+ prop.nullable = true;
25
+ if (field.items)
26
+ prop.items = field.items;
27
+ if (field.example !== undefined) {
28
+ prop.example = field.example;
29
+ exampleValues[field.name] = field.example;
30
+ }
31
+ properties[field.name] = prop;
32
+ if (field.required) {
33
+ required.push(field.name);
34
+ }
35
+ }
36
+ const schema = { type: 'object', properties };
37
+ if (required.length > 0) {
38
+ schema.required = required;
39
+ }
40
+ if (Object.keys(exampleValues).length > 0) {
41
+ schema.example = exampleValues;
42
+ }
43
+ return schema;
44
+ }
45
+ /**
46
+ * Serialize decorated fields from an instance to a plain object.
47
+ * Shared by both Input and Output base classes.
48
+ */
49
+ function serializeFromMetadata(instance, fields) {
50
+ const result = {};
51
+ for (const field of fields) {
52
+ const value = instance[field.name];
53
+ if (value !== undefined) {
54
+ result[field.name] = value;
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+ // Track classes that have already emitted a deprecation warning (once per class)
60
+ const _warnedInputClasses = new Set();
61
+ const _warnedOutputClasses = new Set();
62
+ /** Checks whether a JSON value matches the expected OpenAPI type. */
63
+ function isJsonTypeValid(value, expectedType) {
64
+ switch (expectedType) {
65
+ case 'string': return typeof value === 'string';
66
+ case 'integer': return typeof value === 'number' && Number.isInteger(value);
67
+ case 'number': return typeof value === 'number';
68
+ case 'boolean': return typeof value === 'boolean';
69
+ case 'array': return Array.isArray(value);
70
+ default: return true;
71
+ }
72
+ }
73
+ /**
74
+ * **Contract** — use `extends Input`.
11
75
  *
12
- * Pure interface: all members must be provided by the implementor.
13
- * No default behavior is inherited — every Input is self-contained.
76
+ * When subclass fields are decorated with `@Field`, `toJson()` and
77
+ * `toSchema()` are provided automatically. Manual overrides still work
78
+ * (deprecated — will be removed in v0.5.0).
14
79
  *
15
80
  * ```ts
16
- * class HelloInput implements Input {
17
- * constructor(readonly name: string) {}
18
- * toJson() { return { name: this.name }; }
19
- * toSchema() { return { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }; }
81
+ * class HelloInput extends Input {
82
+ * @Field.string({ description: 'Name to greet' })
83
+ * name!: string;
84
+ *
85
+ * static fromJson(json: Record<string, unknown>) {
86
+ * const instance = new HelloInput();
87
+ * instance.name = (json['name'] ?? '').toString();
88
+ * return instance;
89
+ * }
20
90
  * }
21
91
  * ```
22
92
  */
23
93
  class Input {
94
+ constructor() {
95
+ const cls = this.constructor;
96
+ if (!_warnedInputClasses.has(cls) &&
97
+ cls.prototype.toSchema !== Input.prototype.toSchema) {
98
+ _warnedInputClasses.add(cls);
99
+ console.warn(`${cls.name}.toSchema() is deprecated. Remove it — schema is derived automatically from @Field decorators.`);
100
+ }
101
+ }
102
+ toJson() {
103
+ const fields = (0, field_1.getFieldMetadata)(this.constructor);
104
+ if (fields.length > 0) {
105
+ return serializeFromMetadata(this, fields);
106
+ }
107
+ // No decorator metadata — subclass must override (legacy path)
108
+ throw new Error(`${this.constructor.name}.toJson() not implemented. Use @Field decorators or override toJson().`);
109
+ }
110
+ /**
111
+ * Returns an OpenAPI-compatible JSON Schema describing this input.
112
+ * Derived automatically from `@Field` decorators when present.
113
+ */
114
+ toSchema() {
115
+ const fields = (0, field_1.getFieldMetadata)(this.constructor);
116
+ if (fields.length > 0) {
117
+ return buildSchemaFromMetadata(fields);
118
+ }
119
+ // No decorator metadata — subclass must override (legacy path)
120
+ throw new Error(`${this.constructor.name}.toSchema() not implemented. Use @Field decorators or override toSchema().`);
121
+ }
122
+ /**
123
+ * Validates raw JSON against `@Field` metadata of `targetClass`.
124
+ *
125
+ * Throws {@link InputValidationError} when a required field is missing
126
+ * or has the wrong JSON type. The handler catches this and returns 400.
127
+ *
128
+ * Error messages follow the cross-SDK parity contract:
129
+ * - `"Missing required field: {name}"`
130
+ * - `"Field '{name}' must be of type {type}"`
131
+ */
132
+ static validateJson(json, targetClass) {
133
+ const fields = (0, field_1.getFieldMetadata)(targetClass);
134
+ for (const field of fields) {
135
+ if (!field.required)
136
+ continue;
137
+ if (!(field.name in json) || json[field.name] === undefined || json[field.name] === null) {
138
+ throw new input_validation_error_1.InputValidationError(`Missing required field: ${field.name}`);
139
+ }
140
+ if (!isJsonTypeValid(json[field.name], field.type)) {
141
+ throw new input_validation_error_1.InputValidationError(`Field '${field.name}' must be of type ${field.type}`);
142
+ }
143
+ }
144
+ }
24
145
  }
25
146
  exports.Input = Input;
26
147
  /**
27
- * **Contract** — use `implements Output`.
148
+ * **Contract** — use `extends Output`.
28
149
  *
29
- * Pure interface: all members must be provided by the implementor.
30
- * The implementor must define `statusCode` explicitly — this forces
31
- * developers to think about HTTP status codes for every response.
150
+ * When subclass fields are decorated with `@Field`, `toJson()` and
151
+ * `toSchema()` are provided automatically. The implementor must define
152
+ * `statusCode` explicitly — this forces developers to think about
153
+ * HTTP status codes for every response.
32
154
  *
33
155
  * ```ts
34
- * class HelloOutput implements Output {
35
- * constructor(readonly message: string) {}
156
+ * class HelloOutput extends Output {
157
+ * @Field.string({ description: 'Greeting message' })
158
+ * message!: string;
159
+ *
36
160
  * get statusCode() { return 200; }
37
- * toJson() { return { message: this.message }; }
38
- * toSchema() { return { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] }; }
39
161
  * }
40
162
  * ```
41
163
  */
42
164
  class Output {
165
+ constructor() {
166
+ const cls = this.constructor;
167
+ if (!_warnedOutputClasses.has(cls) &&
168
+ cls.prototype.toSchema !== Output.prototype.toSchema) {
169
+ _warnedOutputClasses.add(cls);
170
+ console.warn(`${cls.name}.toSchema() is deprecated. Remove it — schema is derived automatically from @Field decorators.`);
171
+ }
172
+ }
173
+ toJson() {
174
+ const fields = (0, field_1.getFieldMetadata)(this.constructor);
175
+ if (fields.length > 0) {
176
+ return serializeFromMetadata(this, fields);
177
+ }
178
+ throw new Error(`${this.constructor.name}.toJson() not implemented. Use @Field decorators or override toJson().`);
179
+ }
180
+ toSchema() {
181
+ const fields = (0, field_1.getFieldMetadata)(this.constructor);
182
+ if (fields.length > 0) {
183
+ return buildSchemaFromMetadata(fields);
184
+ }
185
+ throw new Error(`${this.constructor.name}.toSchema() not implemented. Use @Field decorators or override toSchema().`);
186
+ }
43
187
  }
44
188
  exports.Output = Output;
45
189
  /**
@@ -79,5 +223,11 @@ exports.Output = Output;
79
223
  * ```
80
224
  */
81
225
  class UseCase {
226
+ /**
227
+ * Request-scoped logger injected by the framework's logging middleware.
228
+ * Available inside `execute()`. Undefined when running without middleware
229
+ * or in tests that don't provide one.
230
+ */
231
+ logger;
82
232
  }
83
233
  exports.UseCase = UseCase;
@@ -1,22 +1,30 @@
1
1
  import type { RequestHandler } from 'express';
2
- import type { UseCaseFactory, Input, Output } from './usecase';
2
+ import type { UseCaseFactory, Output } from './usecase';
3
+ import { Input } from './usecase';
4
+ export interface UseCaseHandlerOptions {
5
+ /** Input class for pre-validation before fromJson (enables strict factories). */
6
+ inputClass?: abstract new (...args: unknown[]) => Input;
7
+ }
3
8
  /**
4
9
  * Wraps any UseCase factory into an Express RequestHandler.
5
10
  *
6
11
  * Lifecycle (mirrors Dart useCaseHttpHandler):
7
12
  * 1. Parse body (POST/PUT/PATCH) or query params (GET/DELETE)
8
- * 2. Build UseCase via factory(json)
9
- * 3. Call validate() — return 400 if error string returned
10
- * 4. Call execute()
11
- * 5. Return output.toJson() with output.statusCode
13
+ * 2. Pre-validate against @Field metadata (when inputClass provided)
14
+ * 3. Build UseCase via factory(json)
15
+ * 4. Post-validate (legacy fallback when no inputClass)
16
+ * 5. Call validate() — return 400 if error string returned
17
+ * 6. Call execute()
18
+ * 7. Return output.toJson() with output.statusCode
12
19
  *
13
20
  * Errors:
14
- * - UseCaseException → statusCode from exception, structured JSON body
15
- * - Any other Error → 500 Internal Server Error
21
+ * - InputValidationError → 400 with structured error message
22
+ * - UseCaseException → statusCode from exception, structured JSON body
23
+ * - Any other Error → 500 Internal Server Error
16
24
  *
17
25
  * Usage:
18
26
  * ```ts
19
- * router.post('/hello', useCaseHandler(SayHello.fromJson));
27
+ * router.post('/hello', useCaseHandler(SayHello.fromJson, { inputClass: HelloInput }));
20
28
  * ```
21
29
  */
22
- export declare function useCaseHandler<I extends Input, O extends Output>(factory: UseCaseFactory<I, O>): RequestHandler;
30
+ export declare function useCaseHandler<I extends Input, O extends Output>(factory: UseCaseFactory<I, O>, options?: UseCaseHandlerOptions): RequestHandler;
@@ -6,7 +6,9 @@
6
6
  // ============================================================
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.useCaseHandler = useCaseHandler;
9
+ const usecase_1 = require("./usecase");
9
10
  const use_case_exception_1 = require("./use_case_exception");
11
+ const input_validation_error_1 = require("./input_validation_error");
10
12
  const logging_middleware_1 = require("./logger/logging_middleware");
11
13
  const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8' };
12
14
  /**
@@ -14,29 +16,40 @@ const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8' };
14
16
  *
15
17
  * Lifecycle (mirrors Dart useCaseHttpHandler):
16
18
  * 1. Parse body (POST/PUT/PATCH) or query params (GET/DELETE)
17
- * 2. Build UseCase via factory(json)
18
- * 3. Call validate() — return 400 if error string returned
19
- * 4. Call execute()
20
- * 5. Return output.toJson() with output.statusCode
19
+ * 2. Pre-validate against @Field metadata (when inputClass provided)
20
+ * 3. Build UseCase via factory(json)
21
+ * 4. Post-validate (legacy fallback when no inputClass)
22
+ * 5. Call validate() — return 400 if error string returned
23
+ * 6. Call execute()
24
+ * 7. Return output.toJson() with output.statusCode
21
25
  *
22
26
  * Errors:
23
- * - UseCaseException → statusCode from exception, structured JSON body
24
- * - Any other Error → 500 Internal Server Error
27
+ * - InputValidationError → 400 with structured error message
28
+ * - UseCaseException → statusCode from exception, structured JSON body
29
+ * - Any other Error → 500 Internal Server Error
25
30
  *
26
31
  * Usage:
27
32
  * ```ts
28
- * router.post('/hello', useCaseHandler(SayHello.fromJson));
33
+ * router.post('/hello', useCaseHandler(SayHello.fromJson, { inputClass: HelloInput }));
29
34
  * ```
30
35
  */
31
- function useCaseHandler(factory) {
36
+ function useCaseHandler(factory, options = {}) {
32
37
  return async (req, res) => {
33
38
  try {
34
39
  // 1. Extract payload
35
40
  const data = req.method.toUpperCase() === 'GET' || req.method.toUpperCase() === 'DELETE'
36
41
  ? { ...req.query, ...req.params }
37
42
  : (req.body ?? {});
38
- // 2. Build use case
43
+ // 2. Pre-validate BEFORE fromJson (when inputClass provided)
44
+ if (options.inputClass) {
45
+ usecase_1.Input.validateJson(data, options.inputClass);
46
+ }
47
+ // 3. Build use case
39
48
  const useCase = factory(data);
49
+ // 3a. Post-validate for legacy path (no inputClass)
50
+ if (!options.inputClass) {
51
+ usecase_1.Input.validateJson(data, useCase.input.constructor);
52
+ }
40
53
  // 2b. Inject request-scoped logger (if logging middleware is active)
41
54
  const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
42
55
  if (logger) {
@@ -49,11 +62,15 @@ function useCaseHandler(factory) {
49
62
  return;
50
63
  }
51
64
  // 4. Execute
52
- await useCase.execute();
65
+ const output = await useCase.execute();
53
66
  // 5. Respond
54
- res.status(useCase.output.statusCode).set(JSON_HEADERS).json(useCase.toJson());
67
+ res.status(output.statusCode).set(JSON_HEADERS).json(output.toJson());
55
68
  }
56
69
  catch (err) {
70
+ if (err instanceof input_validation_error_1.InputValidationError) {
71
+ res.status(400).set(JSON_HEADERS).json({ error: err.message });
72
+ return;
73
+ }
57
74
  if (err instanceof use_case_exception_1.UseCaseException) {
58
75
  console.error('UseCaseException:', err.toString());
59
76
  res.status(err.statusCode).set(JSON_HEADERS).json(err.toJson());
package/dist/index.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export { Input, Output, UseCase } from './core/usecase';
2
2
  export type { UseCaseFactory } from './core/usecase';
3
+ export { Field, getFieldMetadata } from './core/schema/field';
4
+ export type { FieldMeta, FieldOptions } from './core/schema/field';
3
5
  export { UseCaseException } from './core/use_case_exception';
6
+ export { InputValidationError } from './core/input_validation_error';
4
7
  export { ModularApi } from './core/modular_api';
5
8
  export type { ModularApiOptions } from './core/modular_api';
6
9
  export { ModuleBuilder } from './core/module_builder';
@@ -12,6 +15,8 @@ export type { HealthStatus } from './core/health/health_check';
12
15
  export { HealthService, HealthResponse } from './core/health/health_service';
13
16
  export type { HealthServiceOptions } from './core/health/health_service';
14
17
  export { healthHandler } from './core/health/health_handler';
18
+ export { Counter, Gauge, Histogram, DEFAULT_BUCKETS } from './core/metrics/metric';
19
+ export type { MetricSample } from './core/metrics/metric';
15
20
  export { MetricRegistry, MetricsRegistrar } from './core/metrics/metric_registry';
16
21
  export { metricsMiddleware, metricsHandler } from './core/metrics/metrics_middleware';
17
22
  export type { MetricsMiddlewareOptions } from './core/metrics/metrics_middleware';
@@ -20,3 +25,4 @@ export type { ModularLogger } from './core/logger/logger';
20
25
  export { loggingMiddleware, LOGGER_LOCALS_KEY } from './core/logger/logging_middleware';
21
26
  export type { LoggingMiddlewareOptions } from './core/logger/logging_middleware';
22
27
  export { buildOpenApiSpec, jsonToYaml, openApiJsonHandler, openApiYamlHandler, } from './openapi/openapi';
28
+ export { swaggerDocsHandler } from './openapi/swagger_docs';
package/dist/index.js CHANGED
@@ -5,15 +5,21 @@
5
5
  // import { ModularApi, UseCase, Input, Output } from 'modular_api'
6
6
  // ============================================================
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.openApiYamlHandler = exports.openApiJsonHandler = exports.jsonToYaml = exports.buildOpenApiSpec = exports.LOGGER_LOCALS_KEY = exports.loggingMiddleware = exports.RequestScopedLogger = exports.LogLevel = exports.metricsHandler = exports.metricsMiddleware = exports.MetricsRegistrar = exports.MetricRegistry = exports.healthHandler = exports.HealthResponse = exports.HealthService = exports.HealthCheckResult = exports.HealthCheck = exports.cors = exports.ModuleBuilder = exports.ModularApi = exports.UseCaseException = exports.UseCase = exports.Output = exports.Input = void 0;
8
+ exports.swaggerDocsHandler = exports.openApiYamlHandler = exports.openApiJsonHandler = exports.jsonToYaml = exports.buildOpenApiSpec = exports.LOGGER_LOCALS_KEY = exports.loggingMiddleware = exports.RequestScopedLogger = exports.LogLevel = exports.metricsHandler = exports.metricsMiddleware = exports.MetricsRegistrar = exports.MetricRegistry = exports.DEFAULT_BUCKETS = exports.Histogram = exports.Gauge = exports.Counter = exports.healthHandler = exports.HealthResponse = exports.HealthService = exports.HealthCheckResult = exports.HealthCheck = exports.cors = exports.ModuleBuilder = exports.ModularApi = exports.InputValidationError = exports.UseCaseException = exports.getFieldMetadata = exports.Field = exports.UseCase = exports.Output = exports.Input = void 0;
9
9
  // Core abstractions
10
10
  var usecase_1 = require("./core/usecase");
11
11
  Object.defineProperty(exports, "Input", { enumerable: true, get: function () { return usecase_1.Input; } });
12
12
  Object.defineProperty(exports, "Output", { enumerable: true, get: function () { return usecase_1.Output; } });
13
13
  Object.defineProperty(exports, "UseCase", { enumerable: true, get: function () { return usecase_1.UseCase; } });
14
+ // Schema decorators
15
+ var field_1 = require("./core/schema/field");
16
+ Object.defineProperty(exports, "Field", { enumerable: true, get: function () { return field_1.Field; } });
17
+ Object.defineProperty(exports, "getFieldMetadata", { enumerable: true, get: function () { return field_1.getFieldMetadata; } });
14
18
  // Controlled error responses
15
19
  var use_case_exception_1 = require("./core/use_case_exception");
16
20
  Object.defineProperty(exports, "UseCaseException", { enumerable: true, get: function () { return use_case_exception_1.UseCaseException; } });
21
+ var input_validation_error_1 = require("./core/input_validation_error");
22
+ Object.defineProperty(exports, "InputValidationError", { enumerable: true, get: function () { return input_validation_error_1.InputValidationError; } });
17
23
  // Main orchestrator
18
24
  var modular_api_1 = require("./core/modular_api");
19
25
  Object.defineProperty(exports, "ModularApi", { enumerable: true, get: function () { return modular_api_1.ModularApi; } });
@@ -32,7 +38,12 @@ Object.defineProperty(exports, "HealthService", { enumerable: true, get: functio
32
38
  Object.defineProperty(exports, "HealthResponse", { enumerable: true, get: function () { return health_service_1.HealthResponse; } });
33
39
  var health_handler_1 = require("./core/health/health_handler");
34
40
  Object.defineProperty(exports, "healthHandler", { enumerable: true, get: function () { return health_handler_1.healthHandler; } });
35
- // Metrics — Prometheus /metrics endpoint
41
+ // Metrics — Prometheus /metrics endpoint (zero external dependencies)
42
+ var metric_1 = require("./core/metrics/metric");
43
+ Object.defineProperty(exports, "Counter", { enumerable: true, get: function () { return metric_1.Counter; } });
44
+ Object.defineProperty(exports, "Gauge", { enumerable: true, get: function () { return metric_1.Gauge; } });
45
+ Object.defineProperty(exports, "Histogram", { enumerable: true, get: function () { return metric_1.Histogram; } });
46
+ Object.defineProperty(exports, "DEFAULT_BUCKETS", { enumerable: true, get: function () { return metric_1.DEFAULT_BUCKETS; } });
36
47
  var metric_registry_1 = require("./core/metrics/metric_registry");
37
48
  Object.defineProperty(exports, "MetricRegistry", { enumerable: true, get: function () { return metric_registry_1.MetricRegistry; } });
38
49
  Object.defineProperty(exports, "MetricsRegistrar", { enumerable: true, get: function () { return metric_registry_1.MetricsRegistrar; } });
@@ -52,3 +63,6 @@ Object.defineProperty(exports, "buildOpenApiSpec", { enumerable: true, get: func
52
63
  Object.defineProperty(exports, "jsonToYaml", { enumerable: true, get: function () { return openapi_1.jsonToYaml; } });
53
64
  Object.defineProperty(exports, "openApiJsonHandler", { enumerable: true, get: function () { return openapi_1.openApiJsonHandler; } });
54
65
  Object.defineProperty(exports, "openApiYamlHandler", { enumerable: true, get: function () { return openapi_1.openApiYamlHandler; } });
66
+ // Swagger UI — inline HTML docs handler (PRD-003)
67
+ var swagger_docs_1 = require("./openapi/swagger_docs");
68
+ Object.defineProperty(exports, "swaggerDocsHandler", { enumerable: true, get: function () { return swagger_docs_1.swaggerDocsHandler; } });
@@ -24,12 +24,16 @@ function buildOpenApiSpec(options) {
24
24
  const { title, port, version = '0.1.0', description = 'Auto-generated by modular-api', servers, } = options;
25
25
  const defaultServers = [{ url: `http://localhost:${port}`, description: 'Local' }];
26
26
  const paths = {};
27
+ const componentSchemas = {};
27
28
  for (const route of registry_1.apiRegistry.routes) {
28
29
  const method = route.method.toLowerCase();
29
30
  const path = route.path;
30
- // Use schemas captured at registration time
31
- const inputSchema = route.schemas.input;
32
- const outputSchema = route.schemas.output;
31
+ // Store named schemas in components for Swagger UI "Schemas" section
32
+ const safeCommand = route.command.replace(/-/g, '_');
33
+ const inputRefName = `${route.module}_${safeCommand}_Input`;
34
+ const outputRefName = `${route.module}_${safeCommand}_Output`;
35
+ componentSchemas[inputRefName] = route.schemas.input;
36
+ componentSchemas[outputRefName] = route.schemas.output;
33
37
  if (!paths[path]) {
34
38
  paths[path] = {};
35
39
  }
@@ -43,20 +47,20 @@ function buildOpenApiSpec(options) {
43
47
  required: true,
44
48
  content: {
45
49
  'application/json': {
46
- schema: inputSchema,
50
+ schema: { $ref: `#/components/schemas/${inputRefName}` },
47
51
  },
48
52
  },
49
53
  },
50
54
  }
51
55
  : {
52
- parameters: _schemaToQueryParams(inputSchema),
56
+ parameters: _schemaToQueryParams(route.schemas.input),
53
57
  }),
54
58
  responses: {
55
59
  '200': {
56
60
  description: 'Successful response',
57
61
  content: {
58
62
  'application/json': {
59
- schema: outputSchema,
63
+ schema: { $ref: `#/components/schemas/${outputRefName}` },
60
64
  },
61
65
  },
62
66
  },
@@ -82,6 +86,7 @@ function buildOpenApiSpec(options) {
82
86
  info: { title, version, description },
83
87
  servers: servers ?? defaultServers,
84
88
  paths,
89
+ components: { schemas: componentSchemas },
85
90
  };
86
91
  }
87
92
  /** Converts a JSON Schema object properties to OpenAPI query parameters */
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Swagger UI docs handler — serves an HTML page with the Swagger UI widget.
3
+ *
4
+ * Loads `swagger-ui-dist@5` from jsdelivr CDN and points it at the local
5
+ * `/openapi.json` endpoint. No server-side dependencies; no npm packages
6
+ * required.
7
+ *
8
+ * Canonical HTML payload defined in PRD-003.
9
+ */
10
+ import type { RequestHandler } from 'express';
11
+ /**
12
+ * Returns an Express handler that serves the Swagger UI HTML.
13
+ *
14
+ * Usage:
15
+ * ```ts
16
+ * app.get('/docs', swaggerDocsHandler({ title: 'My API' }));
17
+ * ```
18
+ */
19
+ export declare function swaggerDocsHandler(options: {
20
+ title: string;
21
+ }): RequestHandler;