micro-contracts 0.19.0 → 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 +68 -11
- package/cli-contract.yaml +1 -1
- package/dist/cli/templates.d.ts +2 -1
- package/dist/cli/templates.d.ts.map +1 -1
- package/dist/cli/templates.js +163 -81
- package/dist/cli/templates.js.map +1 -1
- package/dist/generated/contract.js +2 -2
- package/dist/generator/index.js +6 -0
- package/dist/generator/index.js.map +1 -1
- package/dist/generator/linter.d.ts.map +1 -1
- package/dist/generator/linter.js +4 -5
- package/dist/generator/linter.js.map +1 -1
- package/dist/generator/overlayProcessor.d.ts +11 -0
- package/dist/generator/overlayProcessor.d.ts.map +1 -1
- package/dist/generator/overlayProcessor.js +21 -16
- package/dist/generator/overlayProcessor.js.map +1 -1
- package/dist/generator/schemaGenerator.js +31 -19
- package/dist/generator/schemaGenerator.js.map +1 -1
- package/dist/generator/serviceGenerator.js +8 -24
- package/dist/generator/serviceGenerator.js.map +1 -1
- package/dist/generator/templateProcessor.d.ts +35 -3
- package/dist/generator/templateProcessor.d.ts.map +1 -1
- package/dist/generator/templateProcessor.js +54 -30
- package/dist/generator/templateProcessor.js.map +1 -1
- package/dist/generator/typeGenerator.d.ts +41 -3
- package/dist/generator/typeGenerator.d.ts.map +1 -1
- package/dist/generator/typeGenerator.js +62 -53
- package/dist/generator/typeGenerator.js.map +1 -1
- package/dist/micro-contracts.bundle.mjs +586 -506
- package/dist/micro-contracts.bundle.mjs.map +3 -3
- package/dist/types.d.ts +35 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +74 -2
- package/dist/types.js.map +1 -1
- package/docs/cli-reference.md +1 -1
- package/docs/development-guardrails.md +5 -0
- package/docs/overlays-deep-dive.md +8 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -438,6 +438,16 @@ would be dropped from every artifact, so they are errors (`MISSING_X_SERVICE`,
|
|
|
438
438
|
(`screen: true`) operations are consumed via `TemplateContext.screens` and these rules
|
|
439
439
|
do not apply.
|
|
440
440
|
|
|
441
|
+
An operation's success response is its lowest 2xx status code, else its `2XX` range, else
|
|
442
|
+
`default`: the service returns that response's body and the generated route answers with
|
|
443
|
+
that status (200 for `2XX` and `default`). An operation that declares none of them is an
|
|
444
|
+
error: declare the response a successful call returns. Its request body and success response
|
|
445
|
+
must be in a media type generated code carries — `application/json` — since a body in any
|
|
446
|
+
other media type would be dropped from every generated artifact; one declared otherwise is an
|
|
447
|
+
error: remove that media type, and declare the body as `application/json`. A response of any
|
|
448
|
+
other status, which documents an error, may use any media type; generated code has a schema
|
|
449
|
+
only for an `application/json` one.
|
|
450
|
+
|
|
441
451
|
`<input>` is linted under the rules of the module in `micro-contracts.config.yaml` whose
|
|
442
452
|
`openapi` it is — the rules `generate` applies to it — and as a service API spec when no
|
|
443
453
|
module declares it.
|
|
@@ -612,20 +622,67 @@ export class UserService implements UserServiceApi {
|
|
|
612
622
|
### Validators
|
|
613
623
|
|
|
614
624
|
`schemas/validators.ts` holds every schema as the JSON Schema Fastify validates requests and
|
|
615
|
-
serializes responses with, plus the path, query and
|
|
616
|
-
operation (`<Service>_<method>PathParams`, `…QueryParams`, `…
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
625
|
+
serializes responses with, plus the path, query, header and cookie parameter schemas of each
|
|
626
|
+
operation (`<Service>_<method>PathParams`, `…QueryParams`, `…HeaderParams`, `…CookieParams`)
|
|
627
|
+
and its inline request body and response schemas (`…Body`; `…Response` for the success
|
|
628
|
+
response, and `…404Response`, `…4XXResponse` or `…DefaultResponse` for another).
|
|
629
|
+
`schemas/types.ts` names the inline body types the same way. A header parameter schema names headers in lower case, as a
|
|
630
|
+
request delivers them, and is not in `allSchemas`: the starter routes give it to Fastify
|
|
631
|
+
inline (`schema.headers`), since Fastify matches header names case-insensitively only in an
|
|
632
|
+
inline schema. Fastify does not parse cookies, so a starter route reads the cookie parameters
|
|
633
|
+
from the Cookie header and validates them against `…CookieParams` with the validator Fastify
|
|
634
|
+
validates the rest with (`request.compileValidationSchema`). A request missing a required
|
|
635
|
+
header or cookie, or carrying one that does not match its schema, is answered with 400 before
|
|
636
|
+
the service runs. The service's input holds the path, query and cookie parameters; headers
|
|
637
|
+
are validated only. A client is called without cookies, which the browser sends: an operation
|
|
638
|
+
with cookie parameters gets a client input (`<Service>_<method>ClientInput`) — its input with
|
|
639
|
+
the cookie parameters optional — which the starter fetch client takes. Being wider than the
|
|
640
|
+
service's input, it lets the client still satisfy the service interface.
|
|
641
|
+
|
|
642
|
+
The starter fetch client calls `fetch` without a `credentials` option and takes no fetch
|
|
643
|
+
options, so the browser sends cookies under fetch's default, `same-origin`: with a request to
|
|
644
|
+
the page's own origin — directly, or through a dev-server proxy — and with no other. For an
|
|
645
|
+
API on another origin, set `credentials: 'include'` on the `fetch` calls in your copy of
|
|
646
|
+
`fetch-client.hbs`, and have the server allow credentialed CORS: an explicit allowed origin and
|
|
647
|
+
`Access-Control-Allow-Credentials: true` (with `@fastify/cors`, `credentials: true`). A cookie
|
|
648
|
+
sent to another site must also be `SameSite=None; Secure`.
|
|
649
|
+
|
|
650
|
+
Every validation keyword of the contract is kept. Only what JSON Schema spells differently is
|
|
651
|
+
translated (`$ref`, `nullable`, OpenAPI 3.0's boolean `exclusiveMinimum` /
|
|
652
|
+
`exclusiveMaximum`), and what never validates is left out: `x-*` extensions, the annotations
|
|
653
|
+
`example`, `examples`, `xml`, `externalDocs` and `discriminator`, and `$id` / `$schema` (each
|
|
654
|
+
schema is named by its component name). A `oneOf` selects its member by validating each one,
|
|
655
|
+
so a member is chosen by its `discriminator` tag when each member fixes the tag with `enum` or
|
|
656
|
+
`const`.
|
|
657
|
+
|
|
658
|
+
The starter routes (`fastify-routes.hbs`) register, for each operation, the schema of every
|
|
659
|
+
declared response whose body is `application/json`: the success response's under the status
|
|
660
|
+
the route answers with, any other under its status code — a range as Fastify reads it (`4XX`
|
|
661
|
+
as `4xx`), and `default`. Fastify serializes every response with the schema of its status, an
|
|
662
|
+
error included, so a property the contract does not declare for that status is not sent. The
|
|
663
|
+
server's error handler must therefore send the shape the contract declares for the error's
|
|
664
|
+
status — as the example's ProblemDetails handler (`examples/server/src/server.ts`) does: a body
|
|
665
|
+
missing a required property fails serialization and is answered with 500, which is what
|
|
666
|
+
Fastify's default error handler does for a `ProblemDetails` response.
|
|
667
|
+
|
|
668
|
+
Validate with Fastify's default validator options except `removeAdditional`, set to `false`.
|
|
669
|
+
Ajv validates each member of a `oneOf` or `anyOf` against the value itself, and with
|
|
670
|
+
`removeAdditional: true` — Fastify's default — validating a member removes every property that
|
|
671
|
+
member's `additionalProperties: false` does not allow, whether or not the member matches: a
|
|
672
|
+
valid value is rejected, or reaches the service with properties missing. With `false`, a
|
|
673
|
+
property a schema does not allow is rejected rather than removed — and a property a schema
|
|
674
|
+
without `additionalProperties: false` does not declare reaches the service, so a service reads
|
|
675
|
+
the fields its input declares rather than storing the value it receives as a whole.
|
|
676
|
+
|
|
677
|
+
```typescript
|
|
678
|
+
const fastify = Fastify({ ajv: { customOptions: { removeAdditional: false } } });
|
|
679
|
+
```
|
|
622
680
|
|
|
623
681
|
Fastify validates with Ajv on JSON Schema draft-07. A contract using the keywords JSON Schema
|
|
624
682
|
2019-09 / 2020-12 added — `prefixItems`, `dependentRequired`, `dependentSchemas`,
|
|
625
683
|
`minContains` / `maxContains`, `unevaluatedProperties` / `unevaluatedItems` — stops Fastify
|
|
626
684
|
from starting (`strict mode: unknown keyword`). To use them, validate with Ajv on the 2020-12
|
|
627
|
-
dialect, with the options
|
|
628
|
-
your dependencies). A validator set this way does not read `fastify.addSchema`, so it is given
|
|
685
|
+
dialect, with the options above (add `ajv` and `ajv-formats` to your dependencies). A validator set this way does not read `fastify.addSchema`, so it is given
|
|
629
686
|
the generated schemas itself; the generated routes still register them with Fastify, which
|
|
630
687
|
serializes responses with them.
|
|
631
688
|
|
|
@@ -635,8 +692,8 @@ import { Ajv2020 } from 'ajv/dist/2020.js';
|
|
|
635
692
|
import ajvFormats from 'ajv-formats';
|
|
636
693
|
import { allSchemas } from '@project/contract/core/schemas/index.js';
|
|
637
694
|
|
|
638
|
-
//
|
|
639
|
-
const ajv = new Ajv2020({ coerceTypes: 'array', useDefaults: true, removeAdditional:
|
|
695
|
+
// Fastify's default validator options with removeAdditional: false, on the 2020-12 dialect.
|
|
696
|
+
const ajv = new Ajv2020({ coerceTypes: 'array', useDefaults: true, removeAdditional: false, allErrors: false });
|
|
640
697
|
ajvFormats.default(ajv);
|
|
641
698
|
// A custom validator does not read fastify.addSchema: give it every module's schemas, once each.
|
|
642
699
|
for (const schema of allSchemas) {
|
package/cli-contract.yaml
CHANGED
package/dist/cli/templates.d.ts
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
|
/**
|
|
8
9
|
* Get all starter templates
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAugBH;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ5D;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKlE"}
|
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,8 +14,47 @@ 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> {
|
|
@@ -37,24 +77,49 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
37
77
|
|
|
38
78
|
{{#each routes}}
|
|
39
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}}
|
|
40
84
|
fastify.{{method}}('{{fastifyPath}}', {
|
|
41
85
|
schema: {
|
|
42
|
-
{{#if
|
|
43
|
-
params: { $ref: '{{
|
|
86
|
+
{{#if parameterSchemas.path}}
|
|
87
|
+
params: { $ref: '{{parameterSchemas.path}}#' },
|
|
44
88
|
{{/if}}
|
|
45
|
-
{{#if
|
|
46
|
-
querystring: { $ref: '{{
|
|
89
|
+
{{#if parameterSchemas.query}}
|
|
90
|
+
querystring: { $ref: '{{parameterSchemas.query}}#' },
|
|
91
|
+
{{/if}}
|
|
92
|
+
{{#if parameterSchemas.header}}
|
|
93
|
+
headers: {{parameterSchemas.header}},
|
|
47
94
|
{{/if}}
|
|
48
95
|
{{#if requestBody}}
|
|
49
96
|
body: { $ref: '{{requestBody.schemaName}}#' },
|
|
50
97
|
{{/if}}
|
|
51
|
-
{{#if
|
|
52
|
-
response: { {{#each
|
|
98
|
+
{{#if responseSchemas.length}}
|
|
99
|
+
response: { {{#each responseSchemas}}'{{status}}': { $ref: '{{schemaName}}#' }{{#unless @last}}, {{/unless}}{{/each}} },
|
|
53
100
|
{{/if}}
|
|
54
101
|
},
|
|
55
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}}
|
|
56
121
|
{{#if extensions.length}}
|
|
57
|
-
const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req));
|
|
122
|
+
const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req, cookies));
|
|
58
123
|
if (!result.success) return sendError(reply, result.error);
|
|
59
124
|
{{/if}}
|
|
60
125
|
// Build input object (always required, even if empty)
|
|
@@ -65,11 +130,21 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
65
130
|
{{#if queryParams.length}}
|
|
66
131
|
...(req.query as types.{{typeNameBase}}Params),
|
|
67
132
|
{{/if}}
|
|
133
|
+
{{#if cookieParams.length}}
|
|
134
|
+
...(cookieParams as unknown as types.{{typeNameBase}}Params),
|
|
135
|
+
{{/if}}
|
|
68
136
|
{{#if requestBody}}
|
|
69
137
|
data: req.body as types.{{requestBody.schemaName}},
|
|
70
138
|
{{/if}}
|
|
71
139
|
};
|
|
72
|
-
|
|
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}}
|
|
73
148
|
});
|
|
74
149
|
|
|
75
150
|
{{/each}}
|
|
@@ -83,6 +158,7 @@ const STARTER_FETCH_CLIENT_TEMPLATE = `/**
|
|
|
83
158
|
*
|
|
84
159
|
* Client API matches Service API signature (single input object).
|
|
85
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.
|
|
86
162
|
*/
|
|
87
163
|
|
|
88
164
|
import type {
|
|
@@ -124,7 +200,7 @@ async function handleResponse<T>(res: Response): Promise<T> {
|
|
|
124
200
|
// ==========================================================================
|
|
125
201
|
// {{name}} API Client
|
|
126
202
|
// ==========================================================================
|
|
127
|
-
export const {{key}}Api
|
|
203
|
+
export const {{key}}Api = {
|
|
128
204
|
{{#each ../routes}}
|
|
129
205
|
{{#if (eq service ../name)}}
|
|
130
206
|
/**
|
|
@@ -132,7 +208,7 @@ export const {{key}}Api: {{name}}ServiceApi = {
|
|
|
132
208
|
{{#if summary}}* {{summary}}{{/if}}
|
|
133
209
|
{{#if isPublished}}* @published{{/if}}
|
|
134
210
|
*/
|
|
135
|
-
async {{serviceMethod}}(input: {{
|
|
211
|
+
async {{serviceMethod}}(input: {{clientInputType}}): Promise<{{responseType}}> {
|
|
136
212
|
{{#if queryParams.length}}
|
|
137
213
|
const searchParams = new URLSearchParams();
|
|
138
214
|
{{#each queryParams}}
|
|
@@ -164,33 +240,31 @@ export const {{key}}Api: {{name}}ServiceApi = {
|
|
|
164
240
|
|
|
165
241
|
{{/if}}
|
|
166
242
|
{{/each}}
|
|
167
|
-
};
|
|
243
|
+
} satisfies {{name}}ServiceApi;
|
|
168
244
|
|
|
169
245
|
{{/each}}
|
|
170
246
|
`;
|
|
171
|
-
const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs
|
|
172
|
-
{{!-- Generates skeleton implementations for service methods --}}
|
|
247
|
+
const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs: a class per service, implementing its generated interface --}}
|
|
173
248
|
// Auto-generated service stubs - Edit to implement business logic
|
|
174
|
-
import type { {{#each services}}{{
|
|
175
|
-
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';
|
|
176
251
|
|
|
177
252
|
{{#each services}}
|
|
178
253
|
/**
|
|
179
|
-
* {{
|
|
180
|
-
*
|
|
254
|
+
* {{name}} Service Implementation
|
|
255
|
+
*
|
|
181
256
|
* Implement the methods below with your business logic.
|
|
182
|
-
*
|
|
257
|
+
* Methods receive HTTP-agnostic input objects.
|
|
183
258
|
*/
|
|
184
|
-
export class {{
|
|
185
|
-
{{#each ../
|
|
186
|
-
{{#if (eq service ../
|
|
259
|
+
export class {{name}}Service implements {{name}}ServiceApi {
|
|
260
|
+
{{#each ../routes}}
|
|
261
|
+
{{#if (eq service ../name)}}
|
|
187
262
|
/**
|
|
188
|
-
* {{summary}}
|
|
189
|
-
* {{method}} {{path}}
|
|
263
|
+
* {{httpMethod}} {{path}}{{#if summary}}: {{summary}}{{/if}}
|
|
190
264
|
*/
|
|
191
|
-
async {{serviceMethod}}(
|
|
265
|
+
async {{serviceMethod}}(input: types.{{inputType}}): Promise<{{#if (eq responseType "void")}}void{{else}}types.{{responseType}}{{/if}}> {
|
|
192
266
|
// TODO: Implement {{serviceMethod}}
|
|
193
|
-
throw new Error('Not implemented: {{serviceMethod}}');
|
|
267
|
+
throw new Error('Not implemented: {{service}}.{{serviceMethod}}');
|
|
194
268
|
}
|
|
195
269
|
|
|
196
270
|
{{/if}}
|
|
@@ -213,11 +287,13 @@ import type { ProblemDetails } from '{{contractPackage}}/schemas/types.js';
|
|
|
213
287
|
// Types
|
|
214
288
|
// ==========================================================================
|
|
215
289
|
|
|
216
|
-
/** HTTP request abstraction */
|
|
290
|
+
/** HTTP request abstraction: what a route hands the overlays */
|
|
217
291
|
export interface HttpRequest {
|
|
218
292
|
headers: Record<string, string | string[] | undefined>;
|
|
219
293
|
params: Record<string, string>;
|
|
220
294
|
query: Record<string, unknown>;
|
|
295
|
+
/** The cookies the request carries, by name */
|
|
296
|
+
cookies: ReadonlyMap<string, string>;
|
|
221
297
|
body: unknown;
|
|
222
298
|
}
|
|
223
299
|
|
|
@@ -235,17 +311,26 @@ const getQuery = (req: HttpRequest, name: string): unknown => req.query[name];
|
|
|
235
311
|
|
|
236
312
|
const getParam = (req: HttpRequest, name: string): string | undefined => req.params[name];
|
|
237
313
|
|
|
314
|
+
const getCookie = (req: HttpRequest, name: string): string | undefined => req.cookies.get(name);
|
|
315
|
+
|
|
238
316
|
/** Overlay parameter extractors - each overlay defined once */
|
|
239
317
|
const extractors: Record<string, ParamExtractor> = {
|
|
240
318
|
{{#each uniqueOverlays}}
|
|
241
319
|
'{{name}}': (req) => ({
|
|
242
320
|
{{#each params}}
|
|
243
|
-
'{{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}},
|
|
244
322
|
{{/each}}
|
|
245
323
|
}),
|
|
246
324
|
{{/each}}
|
|
247
325
|
};
|
|
248
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
|
+
|
|
249
334
|
// ==========================================================================
|
|
250
335
|
// Endpoint → Overlay Mapping
|
|
251
336
|
// ==========================================================================
|
|
@@ -278,10 +363,34 @@ export async function runOverlays(
|
|
|
278
363
|
const extract = extractors[name];
|
|
279
364
|
const handler = handlers[name as keyof OverlayRegistry];
|
|
280
365
|
|
|
281
|
-
|
|
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
|
+
}
|
|
282
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.
|
|
283
381
|
const input = extract(req);
|
|
284
|
-
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);
|
|
285
394
|
|
|
286
395
|
if (!result.success) {
|
|
287
396
|
return {
|
|
@@ -302,18 +411,6 @@ export async function runOverlays(
|
|
|
302
411
|
return { success: true, context };
|
|
303
412
|
}
|
|
304
413
|
|
|
305
|
-
/**
|
|
306
|
-
* Build HttpRequest from Fastify request
|
|
307
|
-
*/
|
|
308
|
-
export function toHttpRequest(req: { headers: unknown; params: unknown; query: unknown; body: unknown }): HttpRequest {
|
|
309
|
-
return {
|
|
310
|
-
headers: req.headers as Record<string, string | string[] | undefined>,
|
|
311
|
-
params: req.params as Record<string, string>,
|
|
312
|
-
query: req.query as Record<string, unknown>,
|
|
313
|
-
body: req.body,
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
414
|
/**
|
|
318
415
|
* Send error response
|
|
319
416
|
*/
|
|
@@ -321,55 +418,40 @@ export function sendError(reply: FastifyReply, error: ProblemDetails): void {
|
|
|
321
418
|
reply.status(error.status).send(error);
|
|
322
419
|
}
|
|
323
420
|
`;
|
|
324
|
-
const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!--
|
|
325
|
-
|
|
326
|
-
// 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
|
|
327
423
|
import type {
|
|
328
424
|
OverlayResult,
|
|
329
|
-
{{#each
|
|
330
|
-
{{
|
|
331
|
-
{{this}}Overlay,
|
|
425
|
+
{{#each extensionInfo}}
|
|
426
|
+
{{overlayTypeName name}}OverlayInput,
|
|
332
427
|
{{/each}}
|
|
333
428
|
OverlayRegistry,
|
|
334
|
-
} from '{{
|
|
429
|
+
} from '{{contractPackage}}/overlays/index.js';
|
|
335
430
|
|
|
336
|
-
{{#each extensions}}
|
|
337
431
|
/**
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
* Called when an endpoint has x-middleware: [{{name}}]
|
|
341
|
-
* Returns OverlayResult with success/error status
|
|
432
|
+
* Registry of all overlay handlers
|
|
433
|
+
* Register this with your server framework
|
|
342
434
|
*/
|
|
343
|
-
export
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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:
|
|
349
445
|
{{#each injectedParameters}}
|
|
350
|
-
|
|
446
|
+
* - {{name}} (in: {{this.in}}){{#if required}} required{{/if}}
|
|
351
447
|
{{/each}}
|
|
352
448
|
{{/if}}
|
|
449
|
+
*/
|
|
450
|
+
'{{name}}': async (input: {{overlayTypeName name}}OverlayInput): Promise<OverlayResult> => {
|
|
451
|
+
// TODO: Implement {{name}}
|
|
452
|
+
throw new Error('Not implemented: {{name}}');
|
|
453
|
+
},
|
|
353
454
|
|
|
354
|
-
// Example implementation:
|
|
355
|
-
// if (!validateSomething(input)) {
|
|
356
|
-
// return {
|
|
357
|
-
// success: false,
|
|
358
|
-
// error: { status: 4xx, message: 'Error message', code: 'ERROR_CODE' },
|
|
359
|
-
// };
|
|
360
|
-
// }
|
|
361
|
-
|
|
362
|
-
return { success: true, context: { /* optional context for service */ } };
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
{{/each}}
|
|
366
|
-
/**
|
|
367
|
-
* Registry of all overlay handlers
|
|
368
|
-
* Register this with your server framework
|
|
369
|
-
*/
|
|
370
|
-
export const overlayHandlers: OverlayRegistry = {
|
|
371
|
-
{{#each extensions}}
|
|
372
|
-
{{camelCase name}}: {{camelCase name}},
|
|
373
455
|
{{/each}}
|
|
374
456
|
};
|
|
375
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"}
|