raiton 6.10.0-beta.28 → 6.11.1-beta.30

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 (96) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +19 -0
  3. package/benchmarks/README.md +15 -0
  4. package/benchmarks/ai-debug.json +145 -0
  5. package/benchmarks/ai-debug.md +64 -0
  6. package/benchmarks/latest.json +71 -71
  7. package/benchmarks/latest.md +25 -25
  8. package/build/bin/index.mjs +6028 -2098
  9. package/build/types/commands/call.command.d.ts +10 -0
  10. package/build/types/commands/debug.shared.d.ts +16 -0
  11. package/build/types/commands/explain.command.d.ts +8 -0
  12. package/build/types/commands/mcp.command.d.ts +1 -0
  13. package/build/types/commands/requests.command.d.ts +8 -0
  14. package/build/types/commands/verify.command.d.ts +8 -0
  15. package/build/types/contracts/decorators.d.ts +18 -0
  16. package/build/types/contracts/errors.d.ts +29 -3
  17. package/build/types/contracts/schema.d.ts +13 -0
  18. package/build/types/core/application.d.ts +8 -0
  19. package/build/types/debug/cli.d.ts +33 -0
  20. package/build/types/debug/collector.d.ts +41 -0
  21. package/build/types/debug/collector.internal.d.ts +27 -0
  22. package/build/types/debug/config.d.ts +19 -0
  23. package/build/types/debug/examples.d.ts +43 -0
  24. package/build/types/debug/explain.d.ts +9 -0
  25. package/build/types/debug/index.d.ts +15 -0
  26. package/build/types/debug/invocation.d.ts +53 -0
  27. package/build/types/debug/journal.d.ts +49 -0
  28. package/build/types/debug/mcp-http.d.ts +17 -0
  29. package/build/types/debug/mcp.d.ts +14 -0
  30. package/build/types/debug/redaction.d.ts +48 -0
  31. package/build/types/debug/requests.d.ts +37 -0
  32. package/build/types/debug/runtime.d.ts +52 -0
  33. package/build/types/debug/session.d.ts +21 -0
  34. package/build/types/debug/source.d.ts +17 -0
  35. package/build/types/debug/surface.d.ts +10 -0
  36. package/build/types/debug/types.d.ts +271 -0
  37. package/build/types/debug/verify.d.ts +23 -0
  38. package/build/types/framework/errors/catalog.d.ts +16 -1
  39. package/build/types/manifest/schema.d.ts +64 -0
  40. package/build/types/types/config.d.ts +50 -0
  41. package/docs/AGENTS.md +1 -1
  42. package/docs/CLAUDE.md +1 -1
  43. package/docs/generated/cli/commands.md +5 -0
  44. package/docs/generated/config-schema.json +93 -0
  45. package/docs/generated/manifest-schema.json +76 -0
  46. package/docs/generated/manifest.json +20 -3
  47. package/docs/llms-full.txt +183 -4
  48. package/docs/llms.txt +6 -1
  49. package/docs/user-guide/README.md +1 -0
  50. package/docs/user-guide/cli.md +5 -0
  51. package/docs/user-guide/config.md +18 -0
  52. package/docs/user-guide/debug.md +130 -0
  53. package/package.json +3 -1
  54. package/scripts/bench-ai-debug.ts +572 -0
  55. package/source/bin/commands.registry.ts +8 -0
  56. package/source/commands/call.command.ts +247 -0
  57. package/source/commands/debug.shared.ts +90 -0
  58. package/source/commands/docs.command.ts +6 -0
  59. package/source/commands/explain.command.ts +119 -0
  60. package/source/commands/mcp.command.ts +64 -0
  61. package/source/commands/requests.command.ts +137 -0
  62. package/source/commands/verify.command.ts +173 -0
  63. package/source/contracts/decorators.ts +67 -2
  64. package/source/contracts/errors.ts +64 -5
  65. package/source/contracts/schema.ts +61 -0
  66. package/source/core/application.ts +120 -12
  67. package/source/core/builder.ts +4 -0
  68. package/source/core/config/config.ts +11 -0
  69. package/source/core/config/schema.ts +143 -0
  70. package/source/core/router/handler.ts +162 -13
  71. package/source/debug/cli.ts +206 -0
  72. package/source/debug/collector.internal.ts +27 -0
  73. package/source/debug/collector.ts +294 -0
  74. package/source/debug/config.ts +142 -0
  75. package/source/debug/examples.ts +188 -0
  76. package/source/debug/explain.ts +187 -0
  77. package/source/debug/index.ts +15 -0
  78. package/source/debug/invocation.ts +695 -0
  79. package/source/debug/journal.ts +249 -0
  80. package/source/debug/mcp-http.ts +145 -0
  81. package/source/debug/mcp.ts +410 -0
  82. package/source/debug/redaction.ts +225 -0
  83. package/source/debug/requests.ts +136 -0
  84. package/source/debug/runtime.ts +181 -0
  85. package/source/debug/session.ts +107 -0
  86. package/source/debug/source.ts +95 -0
  87. package/source/debug/surface.ts +375 -0
  88. package/source/debug/types.ts +311 -0
  89. package/source/debug/verify.ts +186 -0
  90. package/source/framework/errors/catalog.ts +57 -11
  91. package/source/framework/mcp/handler.ts +9 -1
  92. package/source/framework/utilities/openapi.utils.impl.ts +28 -0
  93. package/source/manifest/introspect.ts +5 -0
  94. package/source/manifest/manifest.ts +24 -1
  95. package/source/manifest/schema.ts +52 -1
  96. package/source/types/config.ts +56 -0
@@ -0,0 +1,137 @@
1
+ import {RaitonCommand} from "../core/command.ts";
2
+ import {CliError, ExitCode, fail, print, silenceStdout} from "../bin/cli-output.ts";
3
+ import {RaitonConfig} from "../core/config/config.ts";
4
+ import {resolveDebugConfig} from "../debug/config.ts";
5
+ import {remoteDebug} from "../debug/cli.ts";
6
+ import {listRequests} from "../debug/requests.ts";
7
+ import type {DebugRequestsList} from "../debug/types.ts";
8
+ import {asCliError} from "./debug.shared.ts";
9
+
10
+ interface RequestsOptions {
11
+ since?: string;
12
+ status?: string;
13
+ route?: string;
14
+ limit?: string;
15
+ url?: string;
16
+ token?: string;
17
+ json?: boolean;
18
+ }
19
+
20
+ export default class RequestsCommand extends RaitonCommand {
21
+ public readonly name = "requests";
22
+ public readonly description = "List recently captured requests";
23
+
24
+ public register(): void {
25
+ this.cli
26
+ .command("requests")
27
+ .description(this.description)
28
+ .option("--since <period>", "Only requests newer than this period (e.g. 5m, 30s)")
29
+ .option("--status <filter>", "Status filter (e.g. 4xx, 500)")
30
+ .option("--route <path>", "Route substring filter")
31
+ .option("--limit <n>", "Maximum number of entries", "20")
32
+ .option("--url <base>", "Target an already running application")
33
+ .option("--token <token>", "Debug token for a protected surface")
34
+ .option("--json", "Emit one JSON document on stdout")
35
+ .action((options: RequestsOptions) => this.action(options));
36
+ }
37
+
38
+ private async action(options: RequestsOptions): Promise<void> {
39
+ const json = options.json === true;
40
+ try {
41
+ const output = json
42
+ ? await silenceStdout(() => this.run(options, true))
43
+ : await this.run(options, false);
44
+ if (json) print(output.list, true);
45
+ else print(output.text);
46
+ } catch (error) {
47
+ fail(asCliError(error), json);
48
+ }
49
+ }
50
+
51
+ private async run(options: RequestsOptions, json: boolean): Promise<{list: DebugRequestsList; text: string}> {
52
+ await RaitonConfig.sync(this.workdir, {force: true});
53
+ const debugConfig = resolveDebugConfig({development: true, workdir: this.workdir});
54
+
55
+ // Build the target URL from the project configuration when no running
56
+ // application is explicitly targeted.
57
+ const target = options.url?.replace(/\/+$/, "") ?? configuredBaseUrl();
58
+
59
+ const query = new URLSearchParams();
60
+ if (options.since) query.set("since", options.since);
61
+ if (options.status) query.set("status", options.status);
62
+ if (options.route) query.set("route", options.route);
63
+ if (options.limit) query.set("limit", options.limit);
64
+
65
+ let remote: any;
66
+ try {
67
+ const response = await remoteDebug(
68
+ {baseUrl: target, token: options.token, timeoutMs: options.url ? 1_500 : 300},
69
+ `/__raiton/requests?${query.toString()}`,
70
+ );
71
+ if (response.status === 200 && response.body && Array.isArray(response.body.requests)) {
72
+ remote = response.body;
73
+ } else if (response.status === 401 || response.status === 403) {
74
+ throw new CliError("The running application rejected the debug token", {
75
+ code: "DEBUG_UNAUTHORIZED",
76
+ hint: "Pass --token or set RAITON_DEBUG_TOKEN.",
77
+ exitCode: ExitCode.PREREQUISITE_MISSING,
78
+ });
79
+ }
80
+ } catch (error) {
81
+ if (error instanceof CliError) throw error;
82
+ // No running application: fall back to the bounded CLI session.
83
+ }
84
+
85
+ const list: DebugRequestsList = remote ?? listRequests({
86
+ since: options.since,
87
+ status: options.status,
88
+ route: options.route,
89
+ limit: Number(options.limit ?? 20),
90
+ workdir: this.workdir,
91
+ });
92
+
93
+ if (!list.enabled) {
94
+ if (!debugConfig.journal.enabled) {
95
+ throw new CliError("The request journal is disabled", {
96
+ code: "DEBUG_JOURNAL_DISABLED",
97
+ hint: "Enable `debug.journal.enabled` in raiton.config.ts or start the app with RAITON_DEBUG_JOURNAL=1.",
98
+ exitCode: ExitCode.PREREQUISITE_MISSING,
99
+ });
100
+ }
101
+ return {
102
+ list,
103
+ text: "No request captured in the selected window.",
104
+ };
105
+ }
106
+
107
+ if (!list.requests.length) {
108
+ return {
109
+ list,
110
+ text: "No request captured in the selected window.",
111
+ };
112
+ }
113
+
114
+ const lines: string[] = [];
115
+ lines.push(`Recent requests (${list.count}/${list.capacity})`);
116
+ for (const entry of list.requests) {
117
+ lines.push(
118
+ `${entry.startedAt} ${entry.method.padEnd(6)} ${entry.route.padEnd(28)} ` +
119
+ `${String(entry.status).padEnd(4)} ${entry.durationMs}ms ${entry.requestId}` +
120
+ (entry.stale ? " [stale]" : ""),
121
+ );
122
+ }
123
+ lines.push("Use `raiton explain <requestId>` for the timeline and root cause.");
124
+ return {list, text: lines.join("\n")};
125
+ }
126
+ }
127
+
128
+ function configuredBaseUrl(): string {
129
+ const protocol = (RaitonConfig.get("protocole") as string) || "http";
130
+ const host = RaitonConfig.get("hostname") || "localhost";
131
+ const port = RaitonConfig.get("port");
132
+ const pathname = RaitonConfig.get("pathname");
133
+ const prefix = RaitonConfig.get("prefix");
134
+ const path = pathname && pathname !== "/" ? pathname.replace(/\/+$/, "") : "";
135
+ const prefixed = prefix ? `/${String(prefix).replace(/^\/+|\/+$/g, "")}` : "";
136
+ return `${protocol}://${host === "0.0.0.0" ? "localhost" : host}${port ? `:${port}` : ""}${path}${prefixed}`;
137
+ }
@@ -0,0 +1,173 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import {RaitonCommand} from "../core/command.ts";
4
+ import {CliError, ExitCode, fail, print, silenceStdout} from "../bin/cli-output.ts";
5
+ import {loadProject} from "../bin/project-utils.ts";
6
+ import {enableCliDebug} from "../debug/cli.ts";
7
+ import {verifyManifest, verifyHuman} from "../debug/verify.ts";
8
+ import {defaultExample} from "../debug/examples.ts";
9
+ import type {ProjectManifest, ProjectRouteManifest} from "../manifest/schema.ts";
10
+ import type {DebugVerificationReport} from "../debug/types.ts";
11
+ import {asCliError, parseMethods} from "./debug.shared.ts";
12
+
13
+ interface VerifyOptions {
14
+ from?: string;
15
+ route?: string;
16
+ json?: boolean;
17
+ failOn?: string;
18
+ url?: string;
19
+ token?: string;
20
+ unsafe?: boolean;
21
+ allowUnsafe?: boolean;
22
+ timeout?: string;
23
+ }
24
+
25
+ export default class VerifyCommand extends RaitonCommand {
26
+ public readonly name = "verify";
27
+ public readonly description = "Call route examples and validate status and output contracts";
28
+
29
+ public register(): void {
30
+ this.cli
31
+ .command("verify")
32
+ .description(this.description)
33
+ .option("--from <source>", "Route source: manifest (default) or openapi", "manifest")
34
+ .option("--route <path>", "Only verify routes containing this path")
35
+ .option("--fail-on <codes>", "Additional status filters considered failures (e.g. 4xx,5xx)")
36
+ .option("--url <base>", "Target an already running application")
37
+ .option("--token <token>", "Bearer token sent to the target")
38
+ .option("--allow-unsafe", "Verify non-idempotent methods explicitly")
39
+ .option("--timeout <ms>", "Per-route timeout in milliseconds", "10000")
40
+ .option("--json", "Emit one JSON document on stdout")
41
+ .action((options: VerifyOptions) => this.action(options));
42
+ }
43
+
44
+ private async action(options: VerifyOptions): Promise<void> {
45
+ const json = options.json === true;
46
+ try {
47
+ const output = json
48
+ ? await silenceStdout(() => this.run(options, true))
49
+ : await this.run(options, false);
50
+ if (json) print(output.report, true);
51
+ else print(output.text);
52
+ if (output.report.summary.failed > 0) process.exitCode = ExitCode.DIAGNOSTIC_FAILED;
53
+ } catch (error) {
54
+ fail(asCliError(error), json);
55
+ }
56
+ }
57
+
58
+ private async run(options: VerifyOptions, json: boolean): Promise<{report: DebugVerificationReport; text: string}> {
59
+ const {application, manifest} = await loadProject(this.workdir, json);
60
+ const runtime = enableCliDebug(application, this.workdir);
61
+
62
+ let routes = manifest.routes;
63
+ if ((options.from ?? "manifest").toLowerCase() === "openapi") {
64
+ routes = loadOpenApiRoutes(this.workdir);
65
+ }
66
+
67
+ const selectedManifest: ProjectManifest = {...manifest, routes};
68
+ const baseUrl = options.url?.replace(/\/+$/, "");
69
+ const headers: Record<string, string> = {};
70
+ if (options.token) headers.authorization = `Bearer ${options.token}`;
71
+
72
+ const report = await verifyManifest({
73
+ manifest: selectedManifest,
74
+ application: baseUrl ? undefined : application,
75
+ config: runtime.config,
76
+ baseUrl,
77
+ workdir: this.workdir,
78
+ route: options.route,
79
+ allowUnsafe: options.allowUnsafe === true || options.unsafe === true,
80
+ failOn: parseMethods(options.failOn),
81
+ timeoutMs: Number(options.timeout ?? 10_000),
82
+ headers,
83
+ });
84
+
85
+ return {report, text: verifyHuman(report)};
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Minimal OpenAPI baseline reader used by `raiton verify --from openapi`.
91
+ * Schemas are taken from the request/response media types; examples are
92
+ * regenerated from those schemas.
93
+ */
94
+ function loadOpenApiRoutes(workdir: string): ProjectRouteManifest[] {
95
+ const candidates = [
96
+ path.join(workdir, "openapi.json"),
97
+ path.join(workdir, ".raiton", "openapi.json"),
98
+ path.join(workdir, "docs", "openapi.json"),
99
+ path.join(workdir, "docs", "generated", "openapi.json"),
100
+ ];
101
+ const filename = candidates.find(candidate => fs.existsSync(candidate));
102
+ if (!filename) {
103
+ throw new CliError("No OpenAPI document found", {
104
+ code: "OPENAPI_NOT_FOUND",
105
+ hint: "Run `raiton openapi export --out openapi.json` first, or use --from manifest.",
106
+ exitCode: ExitCode.PREREQUISITE_MISSING,
107
+ });
108
+ }
109
+
110
+ let document: any;
111
+ try {
112
+ document = JSON.parse(fs.readFileSync(filename, "utf-8"));
113
+ } catch (error: any) {
114
+ throw new CliError(`Invalid OpenAPI document: ${error.message}`, {
115
+ code: "INVALID_OPENAPI",
116
+ location: filename,
117
+ exitCode: ExitCode.PREREQUISITE_MISSING,
118
+ });
119
+ }
120
+
121
+ const routes: ProjectRouteManifest[] = [];
122
+ for (const [routePath, item] of Object.entries(document.paths ?? {})) {
123
+ for (const [method, operation] of Object.entries(item as any)) {
124
+ const op: any = operation;
125
+ const inputSchema = dereference(op?.requestBody?.content?.["application/json"]?.schema, document);
126
+ const outputSchema = dereference(op?.responses?.["200"]?.content?.["application/json"]?.schema, document);
127
+ const querySchema = {
128
+ type: "object",
129
+ properties: Object.fromEntries(
130
+ (op?.parameters ?? [])
131
+ .filter((parameter: any) => parameter?.in === "query")
132
+ .map((parameter: any) => [parameter.name, dereference(parameter.schema ?? {}, document)]),
133
+ ),
134
+ };
135
+ routes.push({
136
+ method: method.toUpperCase(),
137
+ path: routePath,
138
+ controller: "OpenAPI",
139
+ handler: op?.operationId ?? method,
140
+ file: "",
141
+ line: 0,
142
+ ...(inputSchema ? {inputSchema} : {}),
143
+ ...(outputSchema ? {outputSchema} : {}),
144
+ ...(Object.keys(querySchema.properties).length ? {querySchema} : {}),
145
+ examples: [defaultExample({
146
+ bodySchema: inputSchema,
147
+ querySchema: Object.keys(querySchema.properties).length ? querySchema : undefined,
148
+ expectedStatus: 200,
149
+ })],
150
+ });
151
+ }
152
+ }
153
+ return routes;
154
+ }
155
+
156
+ function dereference(schema: any, document: any, seen = new Set<string>()): any {
157
+ if (!schema || typeof schema !== "object") return schema;
158
+ if (typeof schema.$ref === "string" && schema.$ref.startsWith("#/")) {
159
+ if (seen.has(schema.$ref)) return {type: "object"};
160
+ seen.add(schema.$ref);
161
+ const target = schema.$ref
162
+ .slice(2)
163
+ .split("/")
164
+ .reduce((value: any, key: string) => value?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], document);
165
+ return dereference(target ?? {type: "object"}, document, seen);
166
+ }
167
+ if (Array.isArray(schema)) return schema.map(item => dereference(item, document, seen));
168
+ const output: Record<string, any> = {};
169
+ for (const [key, value] of Object.entries(schema)) {
170
+ output[key] = dereference(value, document, seen);
171
+ }
172
+ return output;
173
+ }
@@ -14,9 +14,23 @@ export interface RouteInputContract {
14
14
  headers?: ContractSchema;
15
15
  }
16
16
 
17
+ export interface RouteExampleDeclaration {
18
+ name: string;
19
+ body?: any;
20
+ params?: Record<string, any>;
21
+ query?: Record<string, any>;
22
+ headers?: Record<string, any>;
23
+ expectedStatus?: number;
24
+ }
25
+
17
26
  export interface RouteContract {
18
27
  input?: ContractSchema | RouteInputContract;
19
28
  output?: ContractSchema;
29
+ /** Declared examples, in declaration order. */
30
+ examples?: RouteExampleDeclaration[];
31
+ /** Development-only source locations of the decorators. */
32
+ inputLocation?: string;
33
+ outputLocation?: string;
20
34
  }
21
35
 
22
36
  const INPUT_PARTS = ["body", "query", "params", "headers"] as const;
@@ -41,6 +55,32 @@ function writeContract(target: any, propertyKey: string | symbol, patch: Partial
41
55
  );
42
56
  }
43
57
 
58
+ /**
59
+ * Capture the decorator call site. Only used in development diagnostics; the
60
+ * value is never exposed by production error bodies.
61
+ */
62
+ function captureLocation(): string | undefined {
63
+ try {
64
+ const stack = new Error().stack;
65
+ if (!stack) return undefined;
66
+ for (const line of stack.split(/\r?\n/)) {
67
+ const match = line.match(/\(?([^()\s]+):(\d+):(\d+)\)?$/);
68
+ if (!match) continue;
69
+ const file = match[1];
70
+ if (file.startsWith("node:")) continue;
71
+ if (file.includes("bun:")) continue;
72
+ if (file.includes("/contracts/decorators.")) continue;
73
+ if (file.includes("/contracts/index.")) continue;
74
+ if (file.includes("node_modules")) continue;
75
+ if (!/\.(ts|tsx|js|mjs|cjs|mts|cts)$/.test(file)) continue;
76
+ return `${file}:${match[2]}`;
77
+ }
78
+ } catch {
79
+ // Location capture is best effort.
80
+ }
81
+ return undefined;
82
+ }
83
+
44
84
  /**
45
85
  * Declare the input contract of a route. A single schema validates the request
46
86
  * body; an object with `body`/`query`/`params`/`headers` keys validates each
@@ -48,7 +88,10 @@ function writeContract(target: any, propertyKey: string | symbol, patch: Partial
48
88
  */
49
89
  export function Input(input: ContractSchema | RouteInputContract) {
50
90
  return (target: any, propertyKey: string | symbol) => {
51
- writeContract(target, propertyKey, {input});
91
+ writeContract(target, propertyKey, {
92
+ input,
93
+ inputLocation: captureLocation(),
94
+ });
52
95
  };
53
96
  }
54
97
 
@@ -58,7 +101,29 @@ export function Input(input: ContractSchema | RouteInputContract) {
58
101
  */
59
102
  export function Output(output: ContractSchema) {
60
103
  return (target: any, propertyKey: string | symbol) => {
61
- writeContract(target, propertyKey, {output});
104
+ writeContract(target, propertyKey, {
105
+ output,
106
+ outputLocation: captureLocation(),
107
+ });
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Declare a documented, invocable example for a route. `raiton call --example`
113
+ * and `raiton verify` use it directly; the manifest publishes it.
114
+ */
115
+ export function Example(example: RouteExampleDeclaration) {
116
+ return (target: any, propertyKey: string | symbol) => {
117
+ const current: RouteContract = Reflect.getOwnMetadata(
118
+ METADATA_KEYS.CONTRACT_INPUT,
119
+ target,
120
+ propertyKey,
121
+ ) ?? {};
122
+ const examples = [...(current.examples ?? [])];
123
+ const index = examples.findIndex(item => item.name === example.name);
124
+ if (index >= 0) examples[index] = example;
125
+ else examples.push(example);
126
+ writeContract(target, propertyKey, {examples});
62
127
  };
63
128
  }
64
129
 
@@ -1,4 +1,5 @@
1
1
  import type {ContractIssue} from "./schema.ts";
2
+ import {isSensitiveKey, redactionKeys} from "../debug/redaction.ts";
2
3
 
3
4
  export const DOCS_BASE_URL = "https://github.com/protorians/raiton/blob/main/docs";
4
5
 
@@ -6,13 +7,62 @@ export function docsUrl(path = "user-guide/README.md"): string {
6
7
  return `${DOCS_BASE_URL}/${path.replace(/^\//, "")}`;
7
8
  }
8
9
 
10
+ export interface ErrorRenderOptions {
11
+ requestId?: string;
12
+ hint?: string;
13
+ /** Development-only contract location. */
14
+ location?: string;
15
+ /** Development-only stack lines. */
16
+ stack?: string[];
17
+ redact?: string[];
18
+ /**
19
+ * When explicitly false, expected/received/location details are omitted:
20
+ * production error bodies never expose internal contract details.
21
+ */
22
+ development?: boolean;
23
+ }
24
+
25
+ export const ERROR_SCHEMA_VERSION = "1.0.0";
26
+
9
27
  export interface ValidationErrorBody {
10
28
  error: true;
29
+ schemaVersion: string;
11
30
  code: "VALIDATION_ERROR";
12
31
  message: string;
13
32
  statusCode: number;
14
33
  details: ContractIssue[];
15
34
  docsUrl: string;
35
+ requestId?: string;
36
+ hint?: string;
37
+ }
38
+
39
+ const SENSITIVE_SEGMENTS = new Set([
40
+ "authorization", "cookie", "password", "secret", "token", "access-token",
41
+ "access_token", "refresh-token", "refresh_token", "api-key", "apikey",
42
+ "x-api-key", "x-raiton-debug-token",
43
+ ]);
44
+
45
+ /**
46
+ * Mask sensitive received values and attach the contract source location. The
47
+ * rendered error never contains a raw secret, in development or production.
48
+ */
49
+ export function sanitizeIssues(issues: ContractIssue[], options: ErrorRenderOptions = {}): ContractIssue[] {
50
+ const keys = redactionKeys(options.redact ?? []);
51
+ const exposeDetails = options.development !== false;
52
+ return (issues ?? []).map(issue => {
53
+ const segment = String(issue.path ?? "").split(/[./[\]]/).filter(Boolean).pop()?.toLowerCase() ?? "";
54
+ const sensitive = SENSITIVE_SEGMENTS.has(segment) || (segment ? isSensitiveKey(segment, keys) : false);
55
+ return {
56
+ path: issue.path,
57
+ code: issue.code,
58
+ message: issue.message,
59
+ ...(exposeDetails && issue.expected !== undefined ? {expected: issue.expected} : {}),
60
+ ...(exposeDetails && issue.received !== undefined ? {received: sensitive ? "***" : issue.received} : {}),
61
+ ...(exposeDetails && (issue.location ?? options.location)
62
+ ? {location: issue.location ?? options.location}
63
+ : {}),
64
+ };
65
+ });
16
66
  }
17
67
 
18
68
  /**
@@ -22,14 +72,18 @@ export interface ValidationErrorBody {
22
72
  export function validationErrorBody(
23
73
  issues: ContractIssue[],
24
74
  message = "Invalid request",
75
+ options: ErrorRenderOptions = {},
25
76
  ): ValidationErrorBody {
26
77
  return {
27
78
  error: true,
79
+ schemaVersion: ERROR_SCHEMA_VERSION,
28
80
  code: "VALIDATION_ERROR",
29
81
  message,
30
82
  statusCode: 400,
31
- details: issues,
83
+ details: sanitizeIssues(issues, options),
32
84
  docsUrl: docsUrl("user-guide/recipes/contracts.md"),
85
+ ...(options.requestId ? {requestId: options.requestId} : {}),
86
+ hint: options.hint ?? "Fix the listed fields and retry; the handler was not executed.",
33
87
  };
34
88
  }
35
89
 
@@ -44,8 +98,8 @@ export class ContractValidationError extends Error {
44
98
  this.name = "ContractValidationError";
45
99
  }
46
100
 
47
- render() {
48
- return validationErrorBody(this.issues, this.message);
101
+ render(options: ErrorRenderOptions = {}) {
102
+ return validationErrorBody(this.issues, this.message, options);
49
103
  }
50
104
  }
51
105
 
@@ -63,14 +117,19 @@ export class OutputContractError extends Error {
63
117
  this.name = "OutputContractError";
64
118
  }
65
119
 
66
- render() {
120
+ render(options: ErrorRenderOptions = {}) {
121
+ const details = sanitizeIssues(this.issues, options);
67
122
  return {
68
123
  error: true,
124
+ schemaVersion: ERROR_SCHEMA_VERSION,
69
125
  code: "OUTPUT_VALIDATION_ERROR",
70
126
  statusCode: 500,
71
127
  message: `Response contract violation on ${this.route}`,
72
- details: this.issues,
128
+ details,
73
129
  docsUrl: docsUrl("user-guide/recipes/contracts.md"),
130
+ ...(options.requestId ? {requestId: options.requestId} : {}),
131
+ hint: options.hint
132
+ ?? `The handler ran but its response does not match the @Output contract of ${this.route}.`,
74
133
  };
75
134
  }
76
135
  }
@@ -50,6 +50,12 @@ export interface ContractIssue {
50
50
  path: string;
51
51
  code: string;
52
52
  message: string;
53
+ /** Expected value, format or constraint (development diagnostics). */
54
+ expected?: string;
55
+ /** Received value summary (development diagnostics, redacted upstream). */
56
+ received?: string;
57
+ /** Contract or decorator source location, when available. */
58
+ location?: string;
53
59
  }
54
60
 
55
61
  export interface ContractValidationResult<T = unknown> {
@@ -106,6 +112,57 @@ function issueCodeFromTypeBox(error: any): string {
106
112
  return "invalid_value";
107
113
  }
108
114
 
115
+ /**
116
+ * Human-readable description of the expected value for an issue. Kept short so
117
+ * error bodies stay token-efficient.
118
+ */
119
+ export function describeExpected(schema: any): string | undefined {
120
+ if (!schema || typeof schema !== "object") return undefined;
121
+ if (schema.const !== undefined) return JSON.stringify(schema.const);
122
+ if (Array.isArray(schema.enum)) return schema.enum.map((value: any) => JSON.stringify(value)).join(" | ");
123
+ if (schema.format) return `format:${schema.format}`;
124
+ if (Array.isArray(schema.anyOf)) {
125
+ const values = schema.anyOf.map((item: any) => describeExpected(item)).filter(Boolean);
126
+ if (values.length) return values.join(" | ");
127
+ }
128
+ if (schema.type === "string") {
129
+ const constraints: string[] = [];
130
+ if (Number.isFinite(schema.minLength)) constraints.push(`minLength ${schema.minLength}`);
131
+ if (Number.isFinite(schema.maxLength)) constraints.push(`maxLength ${schema.maxLength}`);
132
+ if (typeof schema.pattern === "string") constraints.push(`pattern ${schema.pattern}`);
133
+ return constraints.length ? `string (${constraints.join(", ")})` : "string";
134
+ }
135
+ if (schema.type === "number" || schema.type === "integer") {
136
+ const constraints: string[] = [];
137
+ if (Number.isFinite(schema.minimum)) constraints.push(`>= ${schema.minimum}`);
138
+ if (Number.isFinite(schema.maximum)) constraints.push(`<= ${schema.maximum}`);
139
+ if (Number.isFinite(schema.exclusiveMinimum)) constraints.push(`> ${schema.exclusiveMinimum}`);
140
+ if (Number.isFinite(schema.exclusiveMaximum)) constraints.push(`< ${schema.exclusiveMaximum}`);
141
+ return constraints.length ? `${schema.type} (${constraints.join(", ")})` : String(schema.type);
142
+ }
143
+ if (schema.type === "array") {
144
+ const constraints: string[] = [];
145
+ if (Number.isFinite(schema.minItems)) constraints.push(`minItems ${schema.minItems}`);
146
+ if (Number.isFinite(schema.maxItems)) constraints.push(`maxItems ${schema.maxItems}`);
147
+ return constraints.length ? `array (${constraints.join(", ")})` : "array";
148
+ }
149
+ return schema.type ? String(schema.type) : undefined;
150
+ }
151
+
152
+ /** Bounded, one-line summary of a received value. */
153
+ export function describeReceived(value: any, maxLength = 80): string {
154
+ if (value === undefined) return "undefined";
155
+ if (value === null) return "null";
156
+ if (typeof value === "string") return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
157
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
158
+ if (Array.isArray(value)) return `array(${value.length})`;
159
+ if (typeof value === "object") {
160
+ const name = (value as any)?.constructor?.name;
161
+ return name && name !== "Object" ? name : "object";
162
+ }
163
+ return String(value);
164
+ }
165
+
109
166
  function schemaOptions(schema: any): Record<string, any> {
110
167
  const options: Record<string, any> = {};
111
168
  const keys = [
@@ -227,10 +284,14 @@ export async function validateContract<T = unknown>(
227
284
 
228
285
  const issues: ContractIssue[] = [];
229
286
  for (const error of Value.Errors(typeboxSchema, value)) {
287
+ const expected = describeExpected(error.schema);
288
+ const received = describeReceived(error.value);
230
289
  issues.push({
231
290
  path: normalizePath(error.path),
232
291
  code: issueCodeFromTypeBox(error),
233
292
  message: error.message || "Invalid value",
293
+ ...(expected !== undefined ? {expected} : {}),
294
+ ...(received !== undefined ? {received} : {}),
234
295
  });
235
296
  }
236
297