micro-contracts 0.18.18 → 0.20.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 +120 -5
- package/cli-contract.yaml +29 -17
- package/dist/agents/context-builder.d.ts.map +1 -1
- package/dist/agents/context-builder.js +3 -3
- package/dist/agents/context-builder.js.map +1 -1
- package/dist/cli/templates.d.ts +2 -1
- package/dist/cli/templates.d.ts.map +1 -1
- package/dist/cli/templates.js +173 -80
- package/dist/cli/templates.js.map +1 -1
- package/dist/cli.js +85 -54
- package/dist/cli.js.map +1 -1
- package/dist/generated/contract.d.ts.map +1 -1
- package/dist/generated/contract.js +2 -2
- package/dist/generated/contract.js.map +1 -1
- package/dist/generated/dsl/dsl-data.js +1 -1
- package/dist/generated/dsl/dsl-data.js.map +1 -1
- package/dist/generated/policy-runtime.d.ts +19 -5
- package/dist/generated/policy-runtime.d.ts.map +1 -1
- package/dist/generated/policy-runtime.js +65 -40
- package/dist/generated/policy-runtime.js.map +1 -1
- package/dist/generated/policy.d.ts +0 -4
- package/dist/generated/policy.d.ts.map +1 -1
- package/dist/generated/policy.js +6 -28
- package/dist/generated/policy.js.map +1 -1
- package/dist/generated/program.d.ts.map +1 -1
- package/dist/generated/program.js +14 -8
- package/dist/generated/program.js.map +1 -1
- package/dist/generator/index.d.ts +15 -5
- package/dist/generator/index.d.ts.map +1 -1
- package/dist/generator/index.js +71 -33
- package/dist/generator/index.js.map +1 -1
- package/dist/generator/inputHash.d.ts.map +1 -1
- package/dist/generator/inputHash.js +3 -57
- package/dist/generator/inputHash.js.map +1 -1
- package/dist/generator/linter.d.ts.map +1 -1
- package/dist/generator/linter.js +23 -25
- package/dist/generator/linter.js.map +1 -1
- package/dist/generator/overlayProcessor.d.ts +15 -11
- package/dist/generator/overlayProcessor.d.ts.map +1 -1
- package/dist/generator/overlayProcessor.js +63 -124
- package/dist/generator/overlayProcessor.js.map +1 -1
- package/dist/generator/schemaGenerator.d.ts.map +1 -1
- package/dist/generator/schemaGenerator.js +124 -140
- package/dist/generator/schemaGenerator.js.map +1 -1
- package/dist/generator/schemaGenerator.test.js +109 -0
- package/dist/generator/schemaGenerator.test.js.map +1 -1
- package/dist/generator/serviceGenerator.d.ts.map +1 -1
- package/dist/generator/serviceGenerator.js +18 -70
- package/dist/generator/serviceGenerator.js.map +1 -1
- package/dist/generator/specLoader.d.ts +33 -0
- package/dist/generator/specLoader.d.ts.map +1 -0
- package/dist/generator/specLoader.js +175 -0
- package/dist/generator/specLoader.js.map +1 -0
- package/dist/generator/templateProcessor.d.ts +35 -3
- package/dist/generator/templateProcessor.d.ts.map +1 -1
- package/dist/generator/templateProcessor.js +84 -77
- package/dist/generator/templateProcessor.js.map +1 -1
- package/dist/generator/typeGenerator.d.ts +42 -4
- package/dist/generator/typeGenerator.d.ts.map +1 -1
- package/dist/generator/typeGenerator.js +83 -72
- package/dist/generator/typeGenerator.js.map +1 -1
- package/dist/generator/typeGenerator.test.js +16 -0
- package/dist/generator/typeGenerator.test.js.map +1 -1
- package/dist/guardrails/allowlist.d.ts.map +1 -1
- package/dist/guardrails/allowlist.js +2 -1
- package/dist/guardrails/allowlist.js.map +1 -1
- package/dist/guardrails/config.js +3 -3
- package/dist/guardrails/config.js.map +1 -1
- package/dist/guardrails/drift.d.ts +5 -2
- package/dist/guardrails/drift.d.ts.map +1 -1
- package/dist/guardrails/drift.js +20 -15
- package/dist/guardrails/drift.js.map +1 -1
- package/dist/guardrails/index.d.ts +2 -2
- package/dist/guardrails/index.d.ts.map +1 -1
- package/dist/guardrails/index.js +1 -1
- package/dist/guardrails/index.js.map +1 -1
- package/dist/guardrails/lint.d.ts.map +1 -1
- package/dist/guardrails/lint.js +5 -6
- package/dist/guardrails/lint.js.map +1 -1
- package/dist/guardrails/manifest.d.ts +52 -8
- package/dist/guardrails/manifest.d.ts.map +1 -1
- package/dist/guardrails/manifest.js +157 -34
- package/dist/guardrails/manifest.js.map +1 -1
- package/dist/guardrails/types.d.ts +3 -1
- package/dist/guardrails/types.d.ts.map +1 -1
- package/dist/micro-contracts.bundle.mjs +640 -526
- package/dist/micro-contracts.bundle.mjs.map +4 -4
- package/dist/types.d.ts +135 -12
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +175 -14
- package/dist/types.js.map +1 -1
- package/docs/cli-reference.md +14 -14
- package/docs/development-guardrails.md +45 -31
- package/docs/guardrails-concept.svg +2 -2
- package/docs/overlays-deep-dive.md +14 -9
- package/package.json +3 -3
package/dist/cli/templates.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Starter Templates for micro-contracts init command
|
|
3
3
|
*
|
|
4
4
|
* These templates are created in spec/default/templates/ and can be customized.
|
|
5
|
-
*
|
|
5
|
+
* examples/spec/default/templates/ holds exactly these files, as init writes
|
|
6
|
+
* them: the example project is generated and type-checked with them.
|
|
6
7
|
*/
|
|
7
8
|
const STARTER_FASTIFY_ROUTES_TEMPLATE = `/**
|
|
8
9
|
* Auto-generated Fastify routes
|
|
@@ -13,13 +14,60 @@ const STARTER_FASTIFY_ROUTES_TEMPLATE = `/**
|
|
|
13
14
|
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
|
14
15
|
import { allSchemas } from '{{contractPackage}}/schemas/index.js';
|
|
15
16
|
import * as types from '{{contractPackage}}/schemas/types.js';
|
|
17
|
+
{{!-- A header schema is given inline: Fastify matches header names case-insensitively only in an inline schema --}}
|
|
18
|
+
import { {{#each routes}}{{#if parameterSchemas.header}}{{parameterSchemas.header}}, {{/if}}{{/each~}} } from '{{contractPackage}}/schemas/validators.js';
|
|
16
19
|
{{#if extensionInfo.length}}
|
|
17
|
-
import { runOverlays,
|
|
20
|
+
import { runOverlays, sendError, type HttpRequest } from './overlayAdapter.generated.js';
|
|
21
|
+
{{/if}}
|
|
22
|
+
{{#if readsCookies}}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The cookies of a Cookie header (\`name=value; name=value\`), by name.
|
|
26
|
+
* Of two cookies with one name, the first is kept: it is the more specific.
|
|
27
|
+
*/
|
|
28
|
+
function parseCookies(header: string | string[] | undefined): Map<string, string> {
|
|
29
|
+
const cookies = new Map<string, string>();
|
|
30
|
+
for (const pair of [header ?? []].flat().join('; ').split(';')) {
|
|
31
|
+
const separator = pair.indexOf('=');
|
|
32
|
+
const name = pair.slice(0, separator).trim();
|
|
33
|
+
if (separator < 0 || !name || cookies.has(name)) continue;
|
|
34
|
+
|
|
35
|
+
let value = pair.slice(separator + 1).trim();
|
|
36
|
+
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
|
|
37
|
+
try {
|
|
38
|
+
cookies.set(name, decodeURIComponent(value));
|
|
39
|
+
} catch {
|
|
40
|
+
cookies.set(name, value);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return cookies;
|
|
44
|
+
}
|
|
45
|
+
{{/if}}
|
|
46
|
+
{{#if extensionInfo.length}}
|
|
47
|
+
|
|
48
|
+
/** The request as the overlays read it */
|
|
49
|
+
function toHttpRequest(req: FastifyRequest, cookies: ReadonlyMap<string, string>): HttpRequest {
|
|
50
|
+
return {
|
|
51
|
+
headers: req.headers as Record<string, string | string[] | undefined>,
|
|
52
|
+
params: req.params as Record<string, string>,
|
|
53
|
+
query: req.query as Record<string, unknown>,
|
|
54
|
+
cookies,
|
|
55
|
+
body: req.body,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
18
58
|
{{/if}}
|
|
19
59
|
|
|
20
60
|
export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
|
|
61
|
+
// A component referenced from a shared file is a schema of every module that
|
|
62
|
+
// references it: the first module registers it, and a module defining a
|
|
63
|
+
// different schema under the same id is an error.
|
|
21
64
|
for (const schema of allSchemas) {
|
|
22
|
-
fastify.
|
|
65
|
+
const registered = fastify.getSchema(schema.$id);
|
|
66
|
+
if (registered === undefined) {
|
|
67
|
+
fastify.addSchema(schema);
|
|
68
|
+
} else if (JSON.stringify(registered) !== JSON.stringify(schema)) {
|
|
69
|
+
throw new Error(\`Schema '\${schema.$id}' is already registered with a different definition\`);
|
|
70
|
+
}
|
|
23
71
|
}
|
|
24
72
|
|
|
25
73
|
const { {{#each services}}{{key}}{{#unless @last}}, {{/unless}}{{/each}} } = {{servicesPath}};
|
|
@@ -29,21 +77,49 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
29
77
|
|
|
30
78
|
{{#each routes}}
|
|
31
79
|
// {{uppercase method}} {{path}}{{#if isPublished}} [PUBLISHED]{{/if}}
|
|
80
|
+
{{#if parameterSchemas.cookie}}
|
|
81
|
+
{{!-- Fastify parses no cookies: the route validates them, with the validator Fastify validates the rest with --}}
|
|
82
|
+
const {{parameterSchemas.cookie}} = { $ref: '{{parameterSchemas.cookie}}#' };
|
|
83
|
+
{{/if}}
|
|
32
84
|
fastify.{{method}}('{{fastifyPath}}', {
|
|
33
85
|
schema: {
|
|
34
|
-
{{#if
|
|
35
|
-
params: { $ref: '{{
|
|
86
|
+
{{#if parameterSchemas.path}}
|
|
87
|
+
params: { $ref: '{{parameterSchemas.path}}#' },
|
|
88
|
+
{{/if}}
|
|
89
|
+
{{#if parameterSchemas.query}}
|
|
90
|
+
querystring: { $ref: '{{parameterSchemas.query}}#' },
|
|
91
|
+
{{/if}}
|
|
92
|
+
{{#if parameterSchemas.header}}
|
|
93
|
+
headers: {{parameterSchemas.header}},
|
|
36
94
|
{{/if}}
|
|
37
95
|
{{#if requestBody}}
|
|
38
96
|
body: { $ref: '{{requestBody.schemaName}}#' },
|
|
39
97
|
{{/if}}
|
|
40
|
-
{{#if
|
|
41
|
-
response: { {{#each
|
|
98
|
+
{{#if responseSchemas.length}}
|
|
99
|
+
response: { {{#each responseSchemas}}'{{status}}': { $ref: '{{schemaName}}#' }{{#unless @last}}, {{/unless}}{{/each}} },
|
|
42
100
|
{{/if}}
|
|
43
101
|
},
|
|
44
102
|
}, async (req: FastifyRequest, reply: FastifyReply) => {
|
|
103
|
+
{{#if (or cookieParams.length extensions.length)}}
|
|
104
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
105
|
+
{{/if}}
|
|
106
|
+
{{#if parameterSchemas.cookie}}
|
|
107
|
+
const cookieParams: Record<string, unknown> = {};
|
|
108
|
+
for (const name of [{{#each cookieParams}}'{{name}}', {{/each~}} ]) {
|
|
109
|
+
const value = cookies.get(name);
|
|
110
|
+
if (value !== undefined) cookieParams[name] = value;
|
|
111
|
+
}
|
|
112
|
+
const validateCookies = req.compileValidationSchema({{parameterSchemas.cookie}});
|
|
113
|
+
if (!validateCookies(cookieParams)) {
|
|
114
|
+
{{!-- The error Fastify itself raises for a schema it validates --}}
|
|
115
|
+
throw Object.assign(
|
|
116
|
+
new Error((validateCookies.errors ?? []).map(e => \`cookies\${e.instancePath} \${e.message}\`).join(', ')),
|
|
117
|
+
{ statusCode: 400, code: 'FST_ERR_VALIDATION', validation: validateCookies.errors, validationContext: 'cookies' },
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
{{/if}}
|
|
45
121
|
{{#if extensions.length}}
|
|
46
|
-
const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req));
|
|
122
|
+
const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req, cookies));
|
|
47
123
|
if (!result.success) return sendError(reply, result.error);
|
|
48
124
|
{{/if}}
|
|
49
125
|
// Build input object (always required, even if empty)
|
|
@@ -54,11 +130,21 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
54
130
|
{{#if queryParams.length}}
|
|
55
131
|
...(req.query as types.{{typeNameBase}}Params),
|
|
56
132
|
{{/if}}
|
|
133
|
+
{{#if cookieParams.length}}
|
|
134
|
+
...(cookieParams as unknown as types.{{typeNameBase}}Params),
|
|
135
|
+
{{/if}}
|
|
57
136
|
{{#if requestBody}}
|
|
58
137
|
data: req.body as types.{{requestBody.schemaName}},
|
|
59
138
|
{{/if}}
|
|
60
139
|
};
|
|
61
|
-
|
|
140
|
+
{{!-- The success status is set once the service has returned: an error it throws keeps its own status. --}}
|
|
141
|
+
{{#if (eq responseType "void")}}
|
|
142
|
+
await {{serviceKey}}.{{serviceMethod}}(input);
|
|
143
|
+
return reply.code({{successStatus}}).send();
|
|
144
|
+
{{else}}
|
|
145
|
+
const output = await {{serviceKey}}.{{serviceMethod}}(input);
|
|
146
|
+
return reply.code({{successStatus}}).send(output);
|
|
147
|
+
{{/if}}
|
|
62
148
|
});
|
|
63
149
|
|
|
64
150
|
{{/each}}
|
|
@@ -72,6 +158,7 @@ const STARTER_FETCH_CLIENT_TEMPLATE = `/**
|
|
|
72
158
|
*
|
|
73
159
|
* Client API matches Service API signature (single input object).
|
|
74
160
|
* Internally maps input to HTTP request (path params, query params, body).
|
|
161
|
+
* Cookie parameters are optional: the browser sends cookies, the client does not.
|
|
75
162
|
*/
|
|
76
163
|
|
|
77
164
|
import type {
|
|
@@ -113,7 +200,7 @@ async function handleResponse<T>(res: Response): Promise<T> {
|
|
|
113
200
|
// ==========================================================================
|
|
114
201
|
// {{name}} API Client
|
|
115
202
|
// ==========================================================================
|
|
116
|
-
export const {{key}}Api
|
|
203
|
+
export const {{key}}Api = {
|
|
117
204
|
{{#each ../routes}}
|
|
118
205
|
{{#if (eq service ../name)}}
|
|
119
206
|
/**
|
|
@@ -121,7 +208,7 @@ export const {{key}}Api: {{name}}ServiceApi = {
|
|
|
121
208
|
{{#if summary}}* {{summary}}{{/if}}
|
|
122
209
|
{{#if isPublished}}* @published{{/if}}
|
|
123
210
|
*/
|
|
124
|
-
async {{serviceMethod}}(input: {{
|
|
211
|
+
async {{serviceMethod}}(input: {{clientInputType}}): Promise<{{responseType}}> {
|
|
125
212
|
{{#if queryParams.length}}
|
|
126
213
|
const searchParams = new URLSearchParams();
|
|
127
214
|
{{#each queryParams}}
|
|
@@ -153,33 +240,31 @@ export const {{key}}Api: {{name}}ServiceApi = {
|
|
|
153
240
|
|
|
154
241
|
{{/if}}
|
|
155
242
|
{{/each}}
|
|
156
|
-
};
|
|
243
|
+
} satisfies {{name}}ServiceApi;
|
|
157
244
|
|
|
158
245
|
{{/each}}
|
|
159
246
|
`;
|
|
160
|
-
const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs
|
|
161
|
-
{{!-- Generates skeleton implementations for service methods --}}
|
|
247
|
+
const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs: a class per service, implementing its generated interface --}}
|
|
162
248
|
// Auto-generated service stubs - Edit to implement business logic
|
|
163
|
-
import type { {{#each services}}{{
|
|
164
|
-
import type * as types from '{{
|
|
249
|
+
import type { {{#each services}}{{name}}ServiceApi{{#unless @last}}, {{/unless}}{{/each}} } from '{{contractPackage}}/services/index.js';
|
|
250
|
+
import type * as types from '{{contractPackage}}/schemas/types.js';
|
|
165
251
|
|
|
166
252
|
{{#each services}}
|
|
167
253
|
/**
|
|
168
|
-
* {{
|
|
169
|
-
*
|
|
254
|
+
* {{name}} Service Implementation
|
|
255
|
+
*
|
|
170
256
|
* Implement the methods below with your business logic.
|
|
171
|
-
*
|
|
257
|
+
* Methods receive HTTP-agnostic input objects.
|
|
172
258
|
*/
|
|
173
|
-
export class {{
|
|
174
|
-
{{#each ../
|
|
175
|
-
{{#if (eq service ../
|
|
259
|
+
export class {{name}}Service implements {{name}}ServiceApi {
|
|
260
|
+
{{#each ../routes}}
|
|
261
|
+
{{#if (eq service ../name)}}
|
|
176
262
|
/**
|
|
177
|
-
* {{summary}}
|
|
178
|
-
* {{method}} {{path}}
|
|
263
|
+
* {{httpMethod}} {{path}}{{#if summary}}: {{summary}}{{/if}}
|
|
179
264
|
*/
|
|
180
|
-
async {{serviceMethod}}(
|
|
265
|
+
async {{serviceMethod}}(input: types.{{inputType}}): Promise<{{#if (eq responseType "void")}}void{{else}}types.{{responseType}}{{/if}}> {
|
|
181
266
|
// TODO: Implement {{serviceMethod}}
|
|
182
|
-
throw new Error('Not implemented: {{serviceMethod}}');
|
|
267
|
+
throw new Error('Not implemented: {{service}}.{{serviceMethod}}');
|
|
183
268
|
}
|
|
184
269
|
|
|
185
270
|
{{/if}}
|
|
@@ -202,11 +287,13 @@ import type { ProblemDetails } from '{{contractPackage}}/schemas/types.js';
|
|
|
202
287
|
// Types
|
|
203
288
|
// ==========================================================================
|
|
204
289
|
|
|
205
|
-
/** HTTP request abstraction */
|
|
290
|
+
/** HTTP request abstraction: what a route hands the overlays */
|
|
206
291
|
export interface HttpRequest {
|
|
207
292
|
headers: Record<string, string | string[] | undefined>;
|
|
208
293
|
params: Record<string, string>;
|
|
209
294
|
query: Record<string, unknown>;
|
|
295
|
+
/** The cookies the request carries, by name */
|
|
296
|
+
cookies: ReadonlyMap<string, string>;
|
|
210
297
|
body: unknown;
|
|
211
298
|
}
|
|
212
299
|
|
|
@@ -224,17 +311,26 @@ const getQuery = (req: HttpRequest, name: string): unknown => req.query[name];
|
|
|
224
311
|
|
|
225
312
|
const getParam = (req: HttpRequest, name: string): string | undefined => req.params[name];
|
|
226
313
|
|
|
314
|
+
const getCookie = (req: HttpRequest, name: string): string | undefined => req.cookies.get(name);
|
|
315
|
+
|
|
227
316
|
/** Overlay parameter extractors - each overlay defined once */
|
|
228
317
|
const extractors: Record<string, ParamExtractor> = {
|
|
229
318
|
{{#each uniqueOverlays}}
|
|
230
319
|
'{{name}}': (req) => ({
|
|
231
320
|
{{#each params}}
|
|
232
|
-
'{{name}}': {{#if (eq location "headers")}}getHeader(req, '{{name}}'){{else if (eq location "query")}}getQuery(req, '{{name}}'){{else}}getParam(req, '{{name}}'){{/if}},
|
|
321
|
+
'{{name}}': {{#if (eq location "headers")}}getHeader(req, '{{name}}'){{else if (eq location "query")}}getQuery(req, '{{name}}'){{else if (eq location "params")}}getParam(req, '{{name}}'){{else if (eq location "cookies")}}getCookie(req, '{{name}}'){{/if}},
|
|
233
322
|
{{/each}}
|
|
234
323
|
}),
|
|
235
324
|
{{/each}}
|
|
236
325
|
};
|
|
237
326
|
|
|
327
|
+
/** The parameters each overlay requires: a request without one is refused before the overlay runs */
|
|
328
|
+
const requiredParams: Record<string, string[]> = {
|
|
329
|
+
{{#each uniqueOverlays}}
|
|
330
|
+
'{{name}}': [{{#each params}}{{#if required}}'{{name}}', {{/if}}{{/each~}} ],
|
|
331
|
+
{{/each}}
|
|
332
|
+
};
|
|
333
|
+
|
|
238
334
|
// ==========================================================================
|
|
239
335
|
// Endpoint → Overlay Mapping
|
|
240
336
|
// ==========================================================================
|
|
@@ -267,10 +363,34 @@ export async function runOverlays(
|
|
|
267
363
|
const extract = extractors[name];
|
|
268
364
|
const handler = handlers[name as keyof OverlayRegistry];
|
|
269
365
|
|
|
270
|
-
|
|
366
|
+
// SECURITY: Never skip a required overlay - fail fast if not registered
|
|
367
|
+
if (!handler) {
|
|
368
|
+
throw new Error(
|
|
369
|
+
\`[SECURITY] Overlay handler "\${name}" is required for operation "\${operationId}" but not registered. \` +
|
|
370
|
+
\`Register it in server.ts: fastify.decorate('overlayHandlers', { \${name}: ... })\`
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
if (!extract) {
|
|
374
|
+
throw new Error(
|
|
375
|
+
\`[SECURITY] Overlay extractor "\${name}" is missing. This indicates a code generation issue.\`
|
|
376
|
+
);
|
|
377
|
+
}
|
|
271
378
|
|
|
379
|
+
// The extractor builds the input the handler is declared with, from the
|
|
380
|
+
// same parameters; looked up by name, TypeScript cannot pair the two.
|
|
272
381
|
const input = extract(req);
|
|
273
|
-
const
|
|
382
|
+
const missing = (requiredParams[name] ?? []).filter(param => input[param] === undefined);
|
|
383
|
+
if (missing.length > 0) {
|
|
384
|
+
return {
|
|
385
|
+
success: false,
|
|
386
|
+
error: {
|
|
387
|
+
type: '/errors/missing_parameter',
|
|
388
|
+
title: \`Missing required parameter: \${missing.join(', ')}\`,
|
|
389
|
+
status: 400,
|
|
390
|
+
},
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
const result = await (handler as unknown as (input: Record<string, unknown>) => Promise<OverlayResult<unknown>>)(input);
|
|
274
394
|
|
|
275
395
|
if (!result.success) {
|
|
276
396
|
return {
|
|
@@ -291,18 +411,6 @@ export async function runOverlays(
|
|
|
291
411
|
return { success: true, context };
|
|
292
412
|
}
|
|
293
413
|
|
|
294
|
-
/**
|
|
295
|
-
* Build HttpRequest from Fastify request
|
|
296
|
-
*/
|
|
297
|
-
export function toHttpRequest(req: { headers: unknown; params: unknown; query: unknown; body: unknown }): HttpRequest {
|
|
298
|
-
return {
|
|
299
|
-
headers: req.headers as Record<string, string | string[] | undefined>,
|
|
300
|
-
params: req.params as Record<string, string>,
|
|
301
|
-
query: req.query as Record<string, unknown>,
|
|
302
|
-
body: req.body,
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
|
|
306
414
|
/**
|
|
307
415
|
* Send error response
|
|
308
416
|
*/
|
|
@@ -310,55 +418,40 @@ export function sendError(reply: FastifyReply, error: ProblemDetails): void {
|
|
|
310
418
|
reply.status(error.status).send(error);
|
|
311
419
|
}
|
|
312
420
|
`;
|
|
313
|
-
const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!--
|
|
314
|
-
|
|
315
|
-
// Auto-generated extension stubs - Edit to implement overlay logic
|
|
421
|
+
const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!-- Overlay handler stubs: a handler per overlay, in the OverlayRegistry --}}
|
|
422
|
+
// Auto-generated overlay handler stubs - Edit to implement overlay logic
|
|
316
423
|
import type {
|
|
317
424
|
OverlayResult,
|
|
318
|
-
{{#each
|
|
319
|
-
{{
|
|
320
|
-
{{this}}Overlay,
|
|
425
|
+
{{#each extensionInfo}}
|
|
426
|
+
{{overlayTypeName name}}OverlayInput,
|
|
321
427
|
{{/each}}
|
|
322
428
|
OverlayRegistry,
|
|
323
|
-
} from '{{
|
|
429
|
+
} from '{{contractPackage}}/overlays/index.js';
|
|
324
430
|
|
|
325
|
-
{{#each extensions}}
|
|
326
431
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
* Called when an endpoint has x-middleware: [{{name}}]
|
|
330
|
-
* Returns OverlayResult with success/error status
|
|
432
|
+
* Registry of all overlay handlers
|
|
433
|
+
* Register this with your server framework
|
|
331
434
|
*/
|
|
332
|
-
export
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
435
|
+
export const overlayHandlers: OverlayRegistry = {
|
|
436
|
+
{{#each extensionInfo}}
|
|
437
|
+
/**
|
|
438
|
+
* {{name}} overlay handler
|
|
439
|
+
*
|
|
440
|
+
* Runs before every operation the overlay applies to. Return
|
|
441
|
+
* { success: false, error: { status, message, code } } to refuse the request.
|
|
442
|
+
{{#if injectedParameters.length}}
|
|
443
|
+
*
|
|
444
|
+
* Input parameters:
|
|
338
445
|
{{#each injectedParameters}}
|
|
339
|
-
|
|
446
|
+
* - {{name}} (in: {{this.in}}){{#if required}} required{{/if}}
|
|
340
447
|
{{/each}}
|
|
341
448
|
{{/if}}
|
|
449
|
+
*/
|
|
450
|
+
'{{name}}': async (input: {{overlayTypeName name}}OverlayInput): Promise<OverlayResult> => {
|
|
451
|
+
// TODO: Implement {{name}}
|
|
452
|
+
throw new Error('Not implemented: {{name}}');
|
|
453
|
+
},
|
|
342
454
|
|
|
343
|
-
// Example implementation:
|
|
344
|
-
// if (!validateSomething(input)) {
|
|
345
|
-
// return {
|
|
346
|
-
// success: false,
|
|
347
|
-
// error: { status: 4xx, message: 'Error message', code: 'ERROR_CODE' },
|
|
348
|
-
// };
|
|
349
|
-
// }
|
|
350
|
-
|
|
351
|
-
return { success: true, context: { /* optional context for service */ } };
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
{{/each}}
|
|
355
|
-
/**
|
|
356
|
-
* Registry of all overlay handlers
|
|
357
|
-
* Register this with your server framework
|
|
358
|
-
*/
|
|
359
|
-
export const overlayHandlers: OverlayRegistry = {
|
|
360
|
-
{{#each extensions}}
|
|
361
|
-
{{camelCase name}}: {{camelCase name}},
|
|
362
455
|
{{/each}}
|
|
363
456
|
};
|
|
364
457
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.js","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"templates.js","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,+BAA+B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgJvC,CAAC;AAEF,MAAM,6BAA6B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6FrC,CAAC;AAEF,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtC,CAAC;AAEF,MAAM,gCAAgC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgJxC,CAAC;AAEF,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCtC,CAAC;AAEF,gFAAgF;AAChF,wBAAwB;AACxB,gFAAgF;AAEhF,MAAM,kCAAkC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4B1C,CAAC;AAEF,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BtC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO;QACL,oBAAoB,EAAE,+BAA+B;QACrD,kBAAkB,EAAE,6BAA6B;QACjD,mBAAmB,EAAE,8BAA8B;QACnD,qBAAqB,EAAE,gCAAgC;QACvD,mBAAmB,EAAE,8BAA8B;KACpD,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB;IACvC,OAAO;QACL,uBAAuB,EAAE,kCAAkC;QAC3D,mBAAmB,EAAE,8BAA8B;KACpD,CAAC;AACJ,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -3,10 +3,10 @@ import fs from 'fs';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import yaml from 'yaml';
|
|
5
5
|
import { createProgram } from './generated/program.js';
|
|
6
|
-
import { generate, loadConfig, findConfigFile, loadOpenAPISpec, lintSpec, formatLintResults, computeInputHash } from './generator/index.js';
|
|
6
|
+
import { generate, loadConfig, findConfigFile, findSpecModule, loadOpenAPISpec, lintSpec, formatLintResults, computeInputHash, configuredOutputs } from './generator/index.js';
|
|
7
7
|
import { isMultiModuleConfig } from './types.js';
|
|
8
8
|
import { getStarterTemplates, getScreenStarterTemplates } from './cli/templates.js';
|
|
9
|
-
import { runAllChecks, formatCheckResults, formatSingleCheckResult, formatCheckStart, formatCheckSummary, formatVerdict, getAvailableChecks, createGuardrailsConfig, generateManifest, writeManifest, canSkipGeneration, GATE_DESCRIPTIONS, loadGuardrailsConfigWithPath, } from './guardrails/index.js';
|
|
9
|
+
import { runAllChecks, formatCheckResults, formatSingleCheckResult, formatCheckStart, formatCheckSummary, formatVerdict, getAvailableChecks, createGuardrailsConfig, generateManifest, writeManifest, canSkipGeneration, generatedFilesRule, resolveManifestDir, GATE_DESCRIPTIONS, loadGuardrailsConfigWithPath, } from './guardrails/index.js';
|
|
10
10
|
import { commandAuditOpenapi } from './commands/audit-openapi.js';
|
|
11
11
|
import { commandReviewPublished } from './commands/review-published.js';
|
|
12
12
|
import { commandProposeOverlays } from './commands/propose-overlays.js';
|
|
@@ -51,8 +51,8 @@ const handlers = {
|
|
|
51
51
|
if (isMultiModuleConfig(config)) {
|
|
52
52
|
inputHash = computeInputHash(config, configPath, VERSION);
|
|
53
53
|
if (useCache) {
|
|
54
|
-
const
|
|
55
|
-
const skipCheck = await canSkipGeneration(manifestDir, inputHash);
|
|
54
|
+
const rule = generatedFilesRule();
|
|
55
|
+
const skipCheck = await canSkipGeneration(resolveManifestDir(opts.manifestDir, rule, configPath), inputHash, rule);
|
|
56
56
|
if (skipCheck.skip) {
|
|
57
57
|
console.log(`No input changes detected, skipping generation (${skipCheck.reason})`);
|
|
58
58
|
return;
|
|
@@ -70,12 +70,14 @@ const handlers = {
|
|
|
70
70
|
if (opts.manifest !== false) {
|
|
71
71
|
const { config: guardrailsConfig } = loadGuardrailsConfigWithPath();
|
|
72
72
|
if (guardrailsConfig?.generated && guardrailsConfig.generated.length > 0) {
|
|
73
|
-
const
|
|
73
|
+
const rule = generatedFilesRule();
|
|
74
|
+
const manifestDir = resolveManifestDir(opts.manifestDir, rule, configPath);
|
|
74
75
|
if (fs.existsSync(manifestDir)) {
|
|
75
76
|
const manifestInputHash = (opts.cache !== false && !isPartialGeneration(opts)) ? inputHash : undefined;
|
|
76
|
-
const { manifest, changed } = await generateManifest(manifestDir, {
|
|
77
|
+
const { manifest, changed, unrecordedOutput } = await generateManifest(manifestDir, rule, {
|
|
77
78
|
generatorVersion: VERSION,
|
|
78
79
|
inputHash: manifestInputHash,
|
|
80
|
+
outputs: isMultiModuleConfig(config) ? configuredOutputs(config) : [],
|
|
79
81
|
});
|
|
80
82
|
const fileCount = Object.keys(manifest.files).length;
|
|
81
83
|
if (changed) {
|
|
@@ -85,6 +87,9 @@ const handlers = {
|
|
|
85
87
|
else {
|
|
86
88
|
console.log(`\nManifest unchanged (${fileCount} files)`);
|
|
87
89
|
}
|
|
90
|
+
if (unrecordedOutput) {
|
|
91
|
+
console.log(`Input hash not recorded: the manifest in ${manifestDir} does not record ${unrecordedOutput}, so the next run regenerates`);
|
|
92
|
+
}
|
|
88
93
|
}
|
|
89
94
|
}
|
|
90
95
|
}
|
|
@@ -104,7 +109,7 @@ const handlers = {
|
|
|
104
109
|
}
|
|
105
110
|
console.log(`Linting: ${specPath}\n`);
|
|
106
111
|
const spec = loadOpenAPISpec(specPath);
|
|
107
|
-
const result = lintSpec(spec, { strict: opts.strict });
|
|
112
|
+
const result = lintSpec(spec, { strict: opts.strict, screen: findSpecModule(specPath)?.screen });
|
|
108
113
|
console.log(formatLintResults(result));
|
|
109
114
|
if (!result.valid) {
|
|
110
115
|
process.exit(1);
|
|
@@ -156,10 +161,10 @@ const handlers = {
|
|
|
156
161
|
fs.writeFileSync(problemDetailsPath, generateProblemDetailsSchema());
|
|
157
162
|
console.log(`Created: ${problemDetailsPath}`);
|
|
158
163
|
}
|
|
159
|
-
const
|
|
160
|
-
if (!fs.existsSync(
|
|
161
|
-
fs.writeFileSync(
|
|
162
|
-
console.log(`Created: ${
|
|
164
|
+
const lintRulesPath = 'spec/redocly.yaml';
|
|
165
|
+
if (!fs.existsSync(lintRulesPath)) {
|
|
166
|
+
fs.writeFileSync(lintRulesPath, generateLintRules());
|
|
167
|
+
console.log(`Created: ${lintRulesPath}`);
|
|
163
168
|
}
|
|
164
169
|
if (opts.screens) {
|
|
165
170
|
const screenSpecDir = `spec/${name}/openapi`;
|
|
@@ -342,6 +347,7 @@ const handlers = {
|
|
|
342
347
|
skip: skipChecks,
|
|
343
348
|
guardrailsPath: opts.guardrails,
|
|
344
349
|
generatedDir: opts.generatedDir,
|
|
350
|
+
configPath: opts.config ? path.resolve(opts.config) : undefined,
|
|
345
351
|
onCheckStart: isStreaming ? (check) => {
|
|
346
352
|
if (process.stdout.isTTY) {
|
|
347
353
|
process.stdout.write(formatCheckStart(check) + '\r');
|
|
@@ -409,8 +415,8 @@ const handlers = {
|
|
|
409
415
|
if (isMultiModuleConfig(config)) {
|
|
410
416
|
inputHash = computeInputHash(config, configPath, VERSION);
|
|
411
417
|
if (useCache) {
|
|
412
|
-
const
|
|
413
|
-
const skipCheck = await canSkipGeneration(
|
|
418
|
+
const rule = generatedFilesRule(opts.guardrails);
|
|
419
|
+
const skipCheck = await canSkipGeneration(resolveManifestDir(opts.generatedDir, rule, configPath), inputHash, rule);
|
|
414
420
|
if (skipCheck.skip) {
|
|
415
421
|
generationCacheSkipped = true;
|
|
416
422
|
generateSkipped = true;
|
|
@@ -437,12 +443,14 @@ const handlers = {
|
|
|
437
443
|
if (opts.manifest !== false) {
|
|
438
444
|
const { config: guardrailsConfig } = loadGuardrailsConfigWithPath(opts.guardrails);
|
|
439
445
|
if (guardrailsConfig?.generated && guardrailsConfig.generated.length > 0) {
|
|
440
|
-
const
|
|
446
|
+
const rule = generatedFilesRule(opts.guardrails);
|
|
447
|
+
const manifestDir = resolveManifestDir(opts.generatedDir, rule, configPath);
|
|
441
448
|
if (fs.existsSync(manifestDir)) {
|
|
442
449
|
const manifestInputHash = (opts.cache !== false && !isPartialGeneration(opts)) ? inputHash : undefined;
|
|
443
|
-
const { manifest, changed } = await generateManifest(manifestDir, {
|
|
450
|
+
const { manifest, changed, unrecordedOutput } = await generateManifest(manifestDir, rule, {
|
|
444
451
|
generatorVersion: VERSION,
|
|
445
452
|
inputHash: manifestInputHash,
|
|
453
|
+
outputs: isMultiModuleConfig(config) ? configuredOutputs(config) : [],
|
|
446
454
|
});
|
|
447
455
|
if (verbose) {
|
|
448
456
|
const fileCount = Object.keys(manifest.files).length;
|
|
@@ -453,6 +461,9 @@ const handlers = {
|
|
|
453
461
|
else {
|
|
454
462
|
originalLog(` Manifest unchanged (${fileCount} files)`);
|
|
455
463
|
}
|
|
464
|
+
if (unrecordedOutput) {
|
|
465
|
+
originalLog(` Input hash not recorded: the manifest in ${manifestDir} does not record ${unrecordedOutput}`);
|
|
466
|
+
}
|
|
456
467
|
}
|
|
457
468
|
else if (changed) {
|
|
458
469
|
writeManifest(manifest, manifestDir);
|
|
@@ -641,14 +652,15 @@ const handlers = {
|
|
|
641
652
|
// ── manifest ──────────────────────────────────────────
|
|
642
653
|
manifest: async (opts) => {
|
|
643
654
|
try {
|
|
644
|
-
const
|
|
655
|
+
const rule = generatedFilesRule();
|
|
656
|
+
const baseDir = resolveManifestDir(opts.dir, rule);
|
|
645
657
|
if (!fs.existsSync(baseDir)) {
|
|
646
658
|
console.error(`Directory not found: ${baseDir}`);
|
|
647
659
|
process.exit(1);
|
|
648
660
|
}
|
|
649
661
|
if (opts.verify) {
|
|
650
662
|
const { verifyManifest, formatManifestResult } = await import('./guardrails/index.js');
|
|
651
|
-
const result = await verifyManifest(baseDir);
|
|
663
|
+
const result = await verifyManifest(baseDir, rule);
|
|
652
664
|
console.log(formatManifestResult(result));
|
|
653
665
|
if (!result.valid) {
|
|
654
666
|
process.exit(1);
|
|
@@ -656,7 +668,7 @@ const handlers = {
|
|
|
656
668
|
}
|
|
657
669
|
else {
|
|
658
670
|
console.log(`Generating manifest for: ${baseDir}`);
|
|
659
|
-
const { manifest, changed } = await generateManifest(baseDir, {
|
|
671
|
+
const { manifest, changed } = await generateManifest(baseDir, rule, {
|
|
660
672
|
generatorVersion: VERSION,
|
|
661
673
|
});
|
|
662
674
|
const fileCount = Object.keys(manifest.files).length;
|
|
@@ -969,50 +981,69 @@ components:
|
|
|
969
981
|
type: string
|
|
970
982
|
`;
|
|
971
983
|
}
|
|
972
|
-
|
|
973
|
-
|
|
984
|
+
/** The Redocly lint rules `init` writes to spec/redocly.yaml. */
|
|
985
|
+
function generateLintRules() {
|
|
986
|
+
return `# Redocly lint rules for micro-contracts specs
|
|
987
|
+
#
|
|
988
|
+
# Run with: npx @redocly/cli lint <spec files> --config spec/redocly.yaml
|
|
989
|
+
# A rule at \`error\` fails the lint; a rule at \`warn\` is reported only.
|
|
990
|
+
# The rules apply to OpenAPI 3.0 and 3.1 documents alike.
|
|
991
|
+
|
|
992
|
+
extends: []
|
|
974
993
|
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
994
|
+
oas3_0Rules: &openapi
|
|
995
|
+
# OpenAPI structure
|
|
996
|
+
struct: error
|
|
997
|
+
no-unresolved-refs: error
|
|
998
|
+
operation-operationId-unique: error
|
|
999
|
+
path-parameters-defined: error
|
|
1000
|
+
operation-parameters-unique: error
|
|
1001
|
+
no-invalid-media-type-examples: error
|
|
1002
|
+
no-invalid-schema-examples: error
|
|
1003
|
+
|
|
1004
|
+
# Every operation names the service and method it is generated into
|
|
1005
|
+
rule/operation-service:
|
|
1006
|
+
message: Operations must have x-micro-contracts-service
|
|
978
1007
|
severity: error
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
1008
|
+
subject:
|
|
1009
|
+
type: Operation
|
|
1010
|
+
property: x-micro-contracts-service
|
|
1011
|
+
filterInParentKeys: [get, post, put, patch, delete]
|
|
1012
|
+
assertions:
|
|
1013
|
+
defined: true
|
|
1014
|
+
nonEmpty: true
|
|
983
1015
|
|
|
984
|
-
operation-method:
|
|
985
|
-
|
|
1016
|
+
rule/operation-method:
|
|
1017
|
+
message: Operations must have x-micro-contracts-method
|
|
986
1018
|
severity: error
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
1019
|
+
subject:
|
|
1020
|
+
type: Operation
|
|
1021
|
+
property: x-micro-contracts-method
|
|
1022
|
+
filterInParentKeys: [get, post, put, patch, delete]
|
|
1023
|
+
assertions:
|
|
1024
|
+
defined: true
|
|
1025
|
+
nonEmpty: true
|
|
991
1026
|
|
|
992
|
-
|
|
993
|
-
|
|
1027
|
+
# Operations should answer a server error
|
|
1028
|
+
rule/operation-error-responses:
|
|
1029
|
+
message: Operations should have a 5XX or default error response
|
|
994
1030
|
severity: warn
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
schema:
|
|
1000
|
-
anyOf:
|
|
1001
|
-
- required: ["500"]
|
|
1002
|
-
- required: ["5XX"]
|
|
1003
|
-
- required: ["default"]
|
|
1031
|
+
subject:
|
|
1032
|
+
type: Responses
|
|
1033
|
+
assertions:
|
|
1034
|
+
requireAny: ['500', '5XX', default]
|
|
1004
1035
|
|
|
1005
|
-
|
|
1006
|
-
|
|
1036
|
+
# The x-micro-contracts-* names, not their short forms
|
|
1037
|
+
rule/canonical-extension-prefix:
|
|
1038
|
+
message: Use x-micro-contracts-* extensions (not x-service, x-method, x-public)
|
|
1007
1039
|
severity: warn
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
function: falsy
|
|
1040
|
+
subject:
|
|
1041
|
+
type: Operation
|
|
1042
|
+
filterInParentKeys: [get, post, put, patch, delete]
|
|
1043
|
+
assertions:
|
|
1044
|
+
disallowed: [x-service, x-method, x-public]
|
|
1045
|
+
|
|
1046
|
+
oas3_1Rules: *openapi
|
|
1016
1047
|
`;
|
|
1017
1048
|
}
|
|
1018
1049
|
function generateScreenSpecTemplate(moduleName) {
|