micro-contracts 0.19.0 → 0.20.1

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 (54) hide show
  1. package/README.md +171 -12
  2. package/cli-contract.yaml +10 -1
  3. package/dist/cli/templates.d.ts +6 -1
  4. package/dist/cli/templates.d.ts.map +1 -1
  5. package/dist/cli/templates.js +622 -91
  6. package/dist/cli/templates.js.map +1 -1
  7. package/dist/cli.js +16 -17
  8. package/dist/cli.js.map +1 -1
  9. package/dist/generated/contract.d.ts.map +1 -1
  10. package/dist/generated/contract.js +2 -2
  11. package/dist/generated/contract.js.map +1 -1
  12. package/dist/generated/policy.d.ts +6 -0
  13. package/dist/generated/policy.d.ts.map +1 -1
  14. package/dist/generated/policy.js +7 -0
  15. package/dist/generated/policy.js.map +1 -1
  16. package/dist/generated/program.d.ts +1 -0
  17. package/dist/generated/program.d.ts.map +1 -1
  18. package/dist/generated/program.js +1 -0
  19. package/dist/generated/program.js.map +1 -1
  20. package/dist/generated/types.d.ts +1 -0
  21. package/dist/generated/types.d.ts.map +1 -1
  22. package/dist/generator/index.js +155 -2
  23. package/dist/generator/index.js.map +1 -1
  24. package/dist/generator/linter.d.ts.map +1 -1
  25. package/dist/generator/linter.js +13 -9
  26. package/dist/generator/linter.js.map +1 -1
  27. package/dist/generator/overlayProcessor.d.ts +11 -0
  28. package/dist/generator/overlayProcessor.d.ts.map +1 -1
  29. package/dist/generator/overlayProcessor.js +21 -16
  30. package/dist/generator/overlayProcessor.js.map +1 -1
  31. package/dist/generator/schemaGenerator.js +31 -19
  32. package/dist/generator/schemaGenerator.js.map +1 -1
  33. package/dist/generator/serviceGenerator.d.ts +6 -0
  34. package/dist/generator/serviceGenerator.d.ts.map +1 -1
  35. package/dist/generator/serviceGenerator.js +14 -28
  36. package/dist/generator/serviceGenerator.js.map +1 -1
  37. package/dist/generator/templateProcessor.d.ts +51 -4
  38. package/dist/generator/templateProcessor.d.ts.map +1 -1
  39. package/dist/generator/templateProcessor.js +68 -31
  40. package/dist/generator/templateProcessor.js.map +1 -1
  41. package/dist/generator/typeGenerator.d.ts +43 -3
  42. package/dist/generator/typeGenerator.d.ts.map +1 -1
  43. package/dist/generator/typeGenerator.js +64 -53
  44. package/dist/generator/typeGenerator.js.map +1 -1
  45. package/dist/micro-contracts.bundle.mjs +1102 -451
  46. package/dist/micro-contracts.bundle.mjs.map +3 -3
  47. package/dist/types.d.ts +56 -4
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/types.js +99 -2
  50. package/dist/types.js.map +1 -1
  51. package/docs/cli-reference.md +5 -1
  52. package/docs/development-guardrails.md +5 -0
  53. package/docs/overlays-deep-dive.md +8 -1
  54. package/package.json +1 -1
@@ -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
- * Keep in sync with examples/spec/default/templates/
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,35 @@ 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, toHttpRequest, sendError } from './overlayAdapter.generated.js';
20
+ import { runOverlays, type HttpRequest } from './overlayAdapter.generated.js';
21
+ {{/if}}
22
+ {{#if streams}}
23
+ import { Readable } from 'node:stream';
24
+ import { encodeStream } from '{{contractPackage}}/streams/index.js';
25
+ {{/if}}
26
+ {{#if readsCookies}}
27
+ import { parseCookies } from '{{contractPackage}}/http/index.js';
28
+ {{/if}}
29
+ {{#if extensionInfo.length}}
30
+
31
+ /** The request as the overlays read it */
32
+ function toHttpRequest(req: FastifyRequest, cookies: ReadonlyMap<string, string>): HttpRequest {
33
+ return {
34
+ headers: req.headers as Record<string, string | string[] | undefined>,
35
+ params: req.params as Record<string, string>,
36
+ query: req.query as Record<string, unknown>,
37
+ cookies,
38
+ body: req.body,
39
+ };
40
+ }
41
+
42
+ /** Answer with an overlay's refusal */
43
+ function sendError(reply: FastifyReply, error: types.ProblemDetails): FastifyReply {
44
+ return reply.status(error.status).send(error);
45
+ }
18
46
  {{/if}}
19
47
 
20
48
  export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
@@ -37,24 +65,53 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
37
65
 
38
66
  {{#each routes}}
39
67
  // {{uppercase method}} {{path}}{{#if isPublished}} [PUBLISHED]{{/if}}
68
+ {{#if parameterSchemas.cookie}}
69
+ {{!-- Fastify parses no cookies: the route validates them, with the validator Fastify validates the rest with --}}
70
+ const {{parameterSchemas.cookie}} = { $ref: '{{parameterSchemas.cookie}}#' };
71
+ {{/if}}
72
+ {{#if stream}}
73
+ {{!-- Events are serialized as a JSON response is: by the schema of one event --}}
74
+ const {{typeNameBase}}EventSchema = { $ref: '{{stream.eventType}}#' };
75
+ {{/if}}
40
76
  fastify.{{method}}('{{fastifyPath}}', {
41
77
  schema: {
42
- {{#if pathParams.length}}
43
- params: { $ref: '{{typeNameBase}}PathParams#' },
78
+ {{#if parameterSchemas.path}}
79
+ params: { $ref: '{{parameterSchemas.path}}#' },
44
80
  {{/if}}
45
- {{#if queryParams.length}}
46
- querystring: { $ref: '{{typeNameBase}}QueryParams#' },
81
+ {{#if parameterSchemas.query}}
82
+ querystring: { $ref: '{{parameterSchemas.query}}#' },
83
+ {{/if}}
84
+ {{#if parameterSchemas.header}}
85
+ headers: {{parameterSchemas.header}},
47
86
  {{/if}}
48
87
  {{#if requestBody}}
49
88
  body: { $ref: '{{requestBody.schemaName}}#' },
50
89
  {{/if}}
51
- {{#if responses.length}}
52
- response: { {{#each responses}}{{#if schemaName}}{{statusCode}}: { $ref: '{{schemaName}}#' }{{#unless @last}}, {{/unless}}{{/if}}{{/each}} },
90
+ {{#if responseSchemas.length}}
91
+ response: { {{#each responseSchemas}}'{{status}}': { $ref: '{{schemaName}}#' }{{#unless @last}}, {{/unless}}{{/each}} },
53
92
  {{/if}}
54
93
  },
55
94
  }, async (req: FastifyRequest, reply: FastifyReply) => {
95
+ {{#if (or cookieParams.length extensions.length)}}
96
+ const cookies = parseCookies(req.headers.cookie);
97
+ {{/if}}
98
+ {{#if parameterSchemas.cookie}}
99
+ const cookieParams: Record<string, unknown> = {};
100
+ for (const name of [{{#each cookieParams}}'{{name}}', {{/each~}} ]) {
101
+ const value = cookies.get(name);
102
+ if (value !== undefined) cookieParams[name] = value;
103
+ }
104
+ const validateCookies = req.compileValidationSchema({{parameterSchemas.cookie}});
105
+ if (!validateCookies(cookieParams)) {
106
+ {{!-- The error Fastify itself raises for a schema it validates --}}
107
+ throw Object.assign(
108
+ new Error((validateCookies.errors ?? []).map(e => \`cookies\${e.instancePath} \${e.message}\`).join(', ')),
109
+ { statusCode: 400, code: 'FST_ERR_VALIDATION', validation: validateCookies.errors, validationContext: 'cookies' },
110
+ );
111
+ }
112
+ {{/if}}
56
113
  {{#if extensions.length}}
57
- const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req));
114
+ const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req, cookies));
58
115
  if (!result.success) return sendError(reply, result.error);
59
116
  {{/if}}
60
117
  // Build input object (always required, even if empty)
@@ -65,11 +122,28 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
65
122
  {{#if queryParams.length}}
66
123
  ...(req.query as types.{{typeNameBase}}Params),
67
124
  {{/if}}
125
+ {{#if cookieParams.length}}
126
+ ...(cookieParams as unknown as types.{{typeNameBase}}Params),
127
+ {{/if}}
68
128
  {{#if requestBody}}
69
129
  data: req.body as types.{{requestBody.schemaName}},
70
130
  {{/if}}
71
131
  };
72
- return {{serviceKey}}.{{serviceMethod}}(input);
132
+ {{!-- The success status is set once the service has returned: an error it throws keeps its own status. --}}
133
+ {{#if stream}}
134
+ {{!-- A stream's first event is awaited before anything is sent: a service that fails at once fails through the error handler --}}
135
+ const events = {{serviceKey}}.{{serviceMethod}}(input)[Symbol.asyncIterator]();
136
+ const first = await events.next();
137
+ const serialize = reply.compileSerializationSchema({{typeNameBase}}EventSchema);
138
+ reply.code({{successStatus}}).header('content-type', '{{stream.mediaType}}').header('cache-control', 'no-cache');
139
+ return reply.send(Readable.from(encodeStream('{{stream.format}}', first, events, serialize, '{{stream.discriminator}}')));
140
+ {{else if (eq responseType "void")}}
141
+ await {{serviceKey}}.{{serviceMethod}}(input);
142
+ return reply.code({{successStatus}}).send();
143
+ {{else}}
144
+ const output = await {{serviceKey}}.{{serviceMethod}}(input);
145
+ return reply.code({{successStatus}}).send(output);
146
+ {{/if}}
73
147
  });
74
148
 
75
149
  {{/each}}
@@ -83,6 +157,7 @@ const STARTER_FETCH_CLIENT_TEMPLATE = `/**
83
157
  *
84
158
  * Client API matches Service API signature (single input object).
85
159
  * Internally maps input to HTTP request (path params, query params, body).
160
+ * Cookie parameters are optional: the browser sends cookies, the client does not.
86
161
  */
87
162
 
88
163
  import type {
@@ -96,6 +171,9 @@ import type {
96
171
  {{/each}}
97
172
  } from '{{contractPackage}}/schemas';
98
173
  import { ApiError } from '{{contractPackage}}/errors';
174
+ {{#if streams}}
175
+ import { decodeStream } from '{{contractPackage}}/streams';
176
+ {{/if}}
99
177
 
100
178
  // BASE_URL derived from OpenAPI servers[0].url: {{baseUrl}}
101
179
  // Can be overridden via environment variable (Vite: VITE_API_BASE_URL)
@@ -119,12 +197,32 @@ async function handleResponse<T>(res: Response): Promise<T> {
119
197
  }
120
198
  return res.json();
121
199
  }
200
+ {{#if streams}}
201
+
202
+ /** The text of a response body in order; reading stopped early cancels the body */
203
+ async function* bodyText(res: Response): AsyncGenerator<string> {
204
+ if (!res.body) return;
205
+ const reader = res.body.getReader();
206
+ const decoder = new TextDecoder();
207
+ let done = false;
208
+ try {
209
+ while (!done) {
210
+ const chunk = await reader.read();
211
+ done = chunk.done;
212
+ const text = decoder.decode(chunk.value, { stream: !done });
213
+ if (text) yield text;
214
+ }
215
+ } finally {
216
+ if (!done) await reader.cancel();
217
+ }
218
+ }
219
+ {{/if}}
122
220
 
123
221
  {{#each services}}
124
222
  // ==========================================================================
125
223
  // {{name}} API Client
126
224
  // ==========================================================================
127
- export const {{key}}Api: {{name}}ServiceApi = {
225
+ export const {{key}}Api = {
128
226
  {{#each ../routes}}
129
227
  {{#if (eq service ../name)}}
130
228
  /**
@@ -132,7 +230,7 @@ export const {{key}}Api: {{name}}ServiceApi = {
132
230
  {{#if summary}}* {{summary}}{{/if}}
133
231
  {{#if isPublished}}* @published{{/if}}
134
232
  */
135
- async {{serviceMethod}}(input: {{inputType}}): Promise<{{responseType}}> {
233
+ async {{#if stream}}*{{/if}}{{serviceMethod}}(input: {{clientInputType}}): {{#if stream}}AsyncGenerator<{{stream.eventType}}>{{else}}Promise<{{responseType}}>{{/if}} {
136
234
  {{#if queryParams.length}}
137
235
  const searchParams = new URLSearchParams();
138
236
  {{#each queryParams}}
@@ -155,7 +253,10 @@ export const {{key}}Api: {{name}}ServiceApi = {
155
253
  {{else}}
156
254
  const res = await fetch(url, { method: '{{httpMethod}}' });
157
255
  {{/if}}
158
- {{#if (eq responseType "void")}}
256
+ {{#if stream}}
257
+ if (!res.ok) await handleResponse<void>(res);
258
+ yield* decodeStream<{{stream.eventType}}>('{{stream.format}}', bodyText(res));
259
+ {{else if (eq responseType "void")}}
159
260
  await handleResponse<void>(res);
160
261
  {{else}}
161
262
  return handleResponse<{{responseType}}>(res);
@@ -164,33 +265,31 @@ export const {{key}}Api: {{name}}ServiceApi = {
164
265
 
165
266
  {{/if}}
166
267
  {{/each}}
167
- };
268
+ } satisfies {{name}}ServiceApi;
168
269
 
169
270
  {{/each}}
170
271
  `;
171
- const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs template --}}
172
- {{!-- Generates skeleton implementations for service methods --}}
272
+ const STARTER_SERVICE_STUBS_TEMPLATE = `{{!-- Service implementation stubs: a class per service, implementing its generated interface --}}
173
273
  // Auto-generated service stubs - Edit to implement business logic
174
- import type { {{#each services}}{{this}}ServiceApi{{#unless @last}}, {{/unless}}{{/each}} } from '{{config.contractPackage}}/services';
175
- import type * as types from '{{config.contractPackage}}/schemas/types';
274
+ import type { {{#each services}}{{name}}ServiceApi{{#unless @last}}, {{/unless}}{{/each}} } from '{{contractPackage}}/services/index.js';
275
+ import type * as types from '{{contractPackage}}/schemas/types.js';
176
276
 
177
277
  {{#each services}}
178
278
  /**
179
- * {{this}} Service Implementation
180
- *
279
+ * {{name}} Service Implementation
280
+ *
181
281
  * Implement the methods below with your business logic.
182
- * Generated methods receive HTTP-agnostic input objects.
282
+ * Methods receive HTTP-agnostic input objects.
183
283
  */
184
- export class {{this}}Service implements {{this}}ServiceApi {
185
- {{#each ../operations}}
186
- {{#if (eq service ../this)}}
284
+ export class {{name}}Service implements {{name}}ServiceApi {
285
+ {{#each ../routes}}
286
+ {{#if (eq service ../name)}}
187
287
  /**
188
- * {{summary}}
189
- * {{method}} {{path}}
288
+ * {{httpMethod}} {{path}}{{#if summary}}: {{summary}}{{/if}}
190
289
  */
191
- async {{serviceMethod}}({{#if inputType}}input: types.{{inputType}}{{/if}}): Promise<types.{{responseType}}> {
290
+ async {{#if stream}}*{{/if}}{{serviceMethod}}(input: types.{{inputType}}): {{#if stream}}AsyncGenerator<types.{{stream.eventType}}>{{else}}Promise<{{#if (eq responseType "void")}}void{{else}}types.{{responseType}}{{/if}}>{{/if}} {
192
291
  // TODO: Implement {{serviceMethod}}
193
- throw new Error('Not implemented: {{serviceMethod}}');
292
+ throw new Error('Not implemented: {{service}}.{{serviceMethod}}');
194
293
  }
195
294
 
196
295
  {{/if}}
@@ -205,19 +304,21 @@ const STARTER_OVERLAY_ADAPTER_TEMPLATE = `/**
205
304
  * DO NOT EDIT MANUALLY
206
305
  */
207
306
 
208
- import type { FastifyReply } from 'fastify';
209
307
  import type { OverlayResult, OverlayRegistry } from '{{contractPackage}}/overlays/index.js';
210
308
  import type { ProblemDetails } from '{{contractPackage}}/schemas/types.js';
309
+ import { toProblemDetails } from '{{contractPackage}}/errors/index.js';
211
310
 
212
311
  // ==========================================================================
213
312
  // Types
214
313
  // ==========================================================================
215
314
 
216
- /** HTTP request abstraction */
315
+ /** HTTP request abstraction: what a route hands the overlays */
217
316
  export interface HttpRequest {
218
317
  headers: Record<string, string | string[] | undefined>;
219
318
  params: Record<string, string>;
220
319
  query: Record<string, unknown>;
320
+ /** The cookies the request carries, by name */
321
+ cookies: ReadonlyMap<string, string>;
221
322
  body: unknown;
222
323
  }
223
324
 
@@ -235,17 +336,26 @@ const getQuery = (req: HttpRequest, name: string): unknown => req.query[name];
235
336
 
236
337
  const getParam = (req: HttpRequest, name: string): string | undefined => req.params[name];
237
338
 
339
+ const getCookie = (req: HttpRequest, name: string): string | undefined => req.cookies.get(name);
340
+
238
341
  /** Overlay parameter extractors - each overlay defined once */
239
342
  const extractors: Record<string, ParamExtractor> = {
240
343
  {{#each uniqueOverlays}}
241
344
  '{{name}}': (req) => ({
242
345
  {{#each params}}
243
- '{{name}}': {{#if (eq location "headers")}}getHeader(req, '{{name}}'){{else if (eq location "query")}}getQuery(req, '{{name}}'){{else}}getParam(req, '{{name}}'){{/if}},
346
+ '{{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
347
  {{/each}}
245
348
  }),
246
349
  {{/each}}
247
350
  };
248
351
 
352
+ /** The parameters each overlay requires: a request without one is refused before the overlay runs */
353
+ const requiredParams: Record<string, string[]> = {
354
+ {{#each uniqueOverlays}}
355
+ '{{name}}': [{{#each params}}{{#if required}}'{{name}}', {{/if}}{{/each~}} ],
356
+ {{/each}}
357
+ };
358
+
249
359
  // ==========================================================================
250
360
  // Endpoint → Overlay Mapping
251
361
  // ==========================================================================
@@ -278,21 +388,38 @@ export async function runOverlays(
278
388
  const extract = extractors[name];
279
389
  const handler = handlers[name as keyof OverlayRegistry];
280
390
 
281
- if (!extract || !handler) continue;
391
+ // SECURITY: Never skip a required overlay - fail fast if not registered
392
+ if (!handler) {
393
+ throw new Error(
394
+ \`[SECURITY] Overlay handler "\${name}" is required for operation "\${operationId}" but not registered. \` +
395
+ \`Register it in the overlay registry the routes are given: { \${name}: ... }\`
396
+ );
397
+ }
398
+ if (!extract) {
399
+ throw new Error(
400
+ \`[SECURITY] Overlay extractor "\${name}" is missing. This indicates a code generation issue.\`
401
+ );
402
+ }
282
403
 
404
+ // The extractor builds the input the handler is declared with, from the
405
+ // same parameters; looked up by name, TypeScript cannot pair the two.
283
406
  const input = extract(req);
284
- const result = await (handler as (input: Record<string, unknown>) => Promise<OverlayResult<unknown>>)(input);
285
-
286
- if (!result.success) {
407
+ const missing = (requiredParams[name] ?? []).filter(param => input[param] === undefined);
408
+ if (missing.length > 0) {
287
409
  return {
288
410
  success: false,
289
- error: {
290
- type: \`/errors/\${result.error?.code?.toLowerCase() ?? 'error'}\`,
291
- title: result.error?.message ?? 'Error',
292
- status: result.error?.status ?? 500,
293
- },
411
+ error: toProblemDetails({
412
+ status: 400,
413
+ message: \`Missing required parameter: \${missing.join(', ')}\`,
414
+ code: 'MISSING_PARAMETER',
415
+ }),
294
416
  };
295
417
  }
418
+ const result = await (handler as unknown as (input: Record<string, unknown>) => Promise<OverlayResult<unknown>>)(input);
419
+
420
+ if (!result.success) {
421
+ return { success: false, error: toProblemDetails(result.error ?? { status: 500, message: 'Error' }) };
422
+ }
296
423
 
297
424
  if (result.context) {
298
425
  Object.assign(context, result.context);
@@ -301,77 +428,473 @@ export async function runOverlays(
301
428
 
302
429
  return { success: true, context };
303
430
  }
431
+ `;
432
+ const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!-- Overlay handler stubs: a handler per overlay, in the OverlayRegistry --}}
433
+ // Auto-generated overlay handler stubs - Edit to implement overlay logic
434
+ import type {
435
+ OverlayResult,
436
+ {{#each extensionInfo}}
437
+ {{overlayTypeName name}}OverlayInput,
438
+ {{/each}}
439
+ OverlayRegistry,
440
+ } from '{{contractPackage}}/overlays/index.js';
304
441
 
305
442
  /**
306
- * Build HttpRequest from Fastify request
443
+ * Registry of all overlay handlers
444
+ * Register this with your server framework
307
445
  */
308
- export function toHttpRequest(req: { headers: unknown; params: unknown; query: unknown; body: unknown }): HttpRequest {
446
+ export const overlayHandlers: OverlayRegistry = {
447
+ {{#each extensionInfo}}
448
+ /**
449
+ * {{name}} overlay handler
450
+ *
451
+ * Runs before every operation the overlay applies to. Return
452
+ * { success: false, error: { status, message, code } } to refuse the request.
453
+ {{#if injectedParameters.length}}
454
+ *
455
+ * Input parameters:
456
+ {{#each injectedParameters}}
457
+ * - {{name}} (in: {{this.in}}){{#if required}} required{{/if}}
458
+ {{/each}}
459
+ {{/if}}
460
+ */
461
+ '{{name}}': async (input: {{overlayTypeName name}}OverlayInput): Promise<OverlayResult> => {
462
+ // TODO: Implement {{name}}
463
+ throw new Error('Not implemented: {{name}}');
464
+ },
465
+
466
+ {{/each}}
467
+ };
468
+ `;
469
+ // =============================================================================
470
+ // AWS Lambda Templates
471
+ // =============================================================================
472
+ const STARTER_LAMBDA_ROUTES_TEMPLATE = `/**
473
+ * Auto-generated AWS Lambda handler
474
+ * Generated from: {{spec.info.title}} v{{spec.info.version}}
475
+ * DO NOT EDIT MANUALLY
476
+ *
477
+ * Answers the events of an API Gateway HTTP API (payload format 2.0) and of a
478
+ * Lambda function URL: routes each to its operation, validates the request
479
+ * against the contract's schemas, runs the operation's overlays and calls its
480
+ * service — as the Fastify routes do, without Fastify.
481
+ */
482
+
483
+ import { Ajv, type ValidateFunction } from 'ajv';
484
+ import ajvFormats from 'ajv-formats';
485
+ import fastJson from 'fast-json-stringify';
486
+ import { allSchemas } from '{{contractPackage}}/schemas/index.js';
487
+ import type * as types from '{{contractPackage}}/schemas/types.js';
488
+ {{!-- A header schema is not registered: it names headers in lower case, as the event carries them --}}
489
+ import { {{#each routes}}{{#if parameterSchemas.header}}{{parameterSchemas.header}}, {{/if}}{{/each~}} } from '{{contractPackage}}/schemas/validators.js';
490
+ import type { ServiceRegistry } from '{{contractPackage}}/services/index.js';
491
+ import { toProblemDetails } from '{{contractPackage}}/errors/index.js';
492
+ import { parseCookies } from '{{contractPackage}}/http/index.js';
493
+ {{#if extensionInfo.length}}
494
+ import type { OverlayRegistry } from '{{contractPackage}}/overlays/index.js';
495
+ import { runOverlays } from './overlayAdapter.generated.js';
496
+ {{/if}}
497
+ {{#if streams}}
498
+ import { Readable, type Writable } from 'node:stream';
499
+ import { pipeline } from 'node:stream/promises';
500
+ import { encodeStream } from '{{contractPackage}}/streams/index.js';
501
+ {{/if}}
502
+
503
+ // ==========================================================================
504
+ // Events
505
+ // ==========================================================================
506
+
507
+ /** What the handler reads of an API Gateway HTTP API event (payload format 2.0) or a function URL event */
508
+ export interface HttpApiEvent {
509
+ rawPath: string;
510
+ rawQueryString: string;
511
+ headers?: Record<string, string | undefined>;
512
+ cookies?: string[];
513
+ body?: string;
514
+ isBase64Encoded: boolean;
515
+ requestContext: { http: { method: string } };
516
+ }
517
+
518
+ /** The response the handler answers an event with */
519
+ export interface HttpApiResult {
520
+ statusCode: number;
521
+ headers: Record<string, string>;
522
+ body: string;
523
+ }
524
+
525
+ export interface HandlerOptions {
526
+ /** The services answering the operations */
527
+ services: ServiceRegistry;
528
+ {{#if extensionInfo.length}}
529
+ /** The overlay handlers run before the services */
530
+ overlays: OverlayRegistry;
531
+ {{/if}}
532
+ /** What the event's path carries before the spec's paths, such as an API Gateway stage (\`/prod\`) */
533
+ basePath?: string;
534
+ }
535
+
536
+ // ==========================================================================
537
+ // Requests and responses
538
+ // ==========================================================================
539
+
540
+ /** A request as its route reads it: the event's parts, parsed */
541
+ interface RouteRequest {
542
+ params: Record<string, string>;
543
+ query: Record<string, unknown>;
544
+ headers: Record<string, string>;
545
+ cookies: ReadonlyMap<string, string>;
546
+ /** The route's cookie parameters, by name */
547
+ cookieParams: Record<string, string>;
548
+ body: unknown;
549
+ }
550
+
551
+ /** A response: its body whole, or (a stream operation's) as the service yields it */
552
+ interface Answer {
553
+ statusCode: number;
554
+ headers: Record<string, string>;
555
+ body: string{{#if streams}} | AsyncIterable<string>{{/if}};
556
+ }
557
+
558
+ type Serialize = (value: unknown) => string;
559
+
560
+ /** How a route answers */
561
+ interface Reply {
562
+ /** Answer with a status, and a body serialized by the schema declared for the status */
563
+ send(statusCode: number, output?: unknown): Answer;
564
+ {{#if streams}}
565
+ /** Answer with a status, and frames as they come */
566
+ stream(statusCode: number, mediaType: string, frames: AsyncIterable<string>): Answer;
567
+ {{/if}}
568
+ }
569
+
570
+ interface RouteDefinition {
571
+ method: string;
572
+ /** The path as the spec writes it, \`{name}\` for a parameter */
573
+ path: string;
574
+ /** The validators of the parts of the request, named as Fastify names them */
575
+ params?: ValidateFunction;
576
+ body?: ValidateFunction;
577
+ querystring?: ValidateFunction;
578
+ headers?: ValidateFunction;
579
+ cookies?: ValidateFunction;
580
+ /** The names of the cookie parameters */
581
+ cookieNames?: string[];
582
+ /** The serializers of the declared responses, by status as Fastify reads it: \`200\`, \`4xx\`, \`default\` */
583
+ response: Record<string, Serialize>;
584
+ handler(request: RouteRequest, reply: Reply): Promise<Answer>;
585
+ }
586
+
587
+ interface Route extends RouteDefinition {
588
+ /** Matches the path, capturing the path parameters in order */
589
+ pattern: RegExp;
590
+ names: string[];
591
+ /** Orders routes as Fastify matches them: a literal segment before a parameter */
592
+ rank: string;
593
+ }
594
+
595
+ const JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
596
+
597
+ /** An error answered with its status */
598
+ function httpError(statusCode: number, message: string): Error {
599
+ return Object.assign(new Error(message), { statusCode });
600
+ }
601
+
602
+ /** The serializer of a status, looked up as Fastify looks it up: the status, its range (\`4xx\`), then \`default\` */
603
+ function serializerOf(response: Record<string, Serialize>, statusCode: number): Serialize {
604
+ return response[statusCode] ?? response[\`\${String(statusCode)[0]}xx\`] ?? response.default ?? JSON.stringify;
605
+ }
606
+
607
+ function replyOf(response: Record<string, Serialize>): Reply {
309
608
  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,
609
+ send: (statusCode, output): Answer => output === undefined
610
+ ? { statusCode, headers: {}, body: '' }
611
+ : { statusCode, headers: { 'content-type': JSON_CONTENT_TYPE }, body: serializerOf(response, statusCode)(output) },
612
+ {{#if streams}}
613
+ stream: (statusCode, mediaType, frames) =>
614
+ ({ statusCode, headers: { 'content-type': mediaType, 'cache-control': 'no-cache' }, body: frames }),
615
+ {{/if}}
314
616
  };
315
617
  }
316
618
 
317
619
  /**
318
- * Send error response
620
+ * A thrown error as the contract's error shape, with the status it carries
621
+ * (\`status\` or \`statusCode\`, 400 to 599) as Fastify reads it, or 500.
319
622
  */
320
- export function sendError(reply: FastifyReply, error: ProblemDetails): void {
321
- reply.status(error.status).send(error);
623
+ function problemOf(error: unknown): types.ProblemDetails {
624
+ const { status, statusCode, message } = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>;
625
+ const carried = [status, statusCode].find((code): code is number => typeof code === 'number' && code >= 400 && code <= 599);
626
+ return toProblemDetails({
627
+ status: carried ?? 500,
628
+ message: typeof message === 'string' && message !== '' ? message : 'Internal Server Error',
629
+ });
322
630
  }
323
- `;
324
- const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!-- Extension implementation stubs template --}}
325
- {{!-- Generates skeleton implementations for overlay handlers --}}
326
- // Auto-generated extension stubs - Edit to implement overlay logic
327
- import type {
328
- OverlayResult,
329
- {{#each extensionTypes}}
330
- {{this}}OverlayInput,
331
- {{this}}Overlay,
631
+
632
+ /** The headers an error carries to its response, as Fastify sends them */
633
+ function headersOf(error: unknown): Record<string, string> {
634
+ const { headers } = (typeof error === 'object' && error !== null ? error : {}) as { headers?: Record<string, string> };
635
+ return headers ?? {};
636
+ }
637
+
638
+ /** A route of the spec's path: a pattern capturing its parameters, and its rank among routes */
639
+ function routeOf(definition: RouteDefinition): Route {
640
+ const names: string[] = [];
641
+ const source = definition.path
642
+ .split(/\\{([^}]+)\\}/)
643
+ .map((part, index) => {
644
+ if (index % 2 === 0) return part.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&');
645
+ names.push(part);
646
+ return '([^/]+)';
647
+ })
648
+ .join('');
649
+ const rank = definition.path.split('/').map(segment => (segment.includes('{') ? '1' : '0')).join('');
650
+ return { ...definition, pattern: new RegExp(\`^\${source}$\`), names, rank };
651
+ }
652
+
653
+ /** A path parameter, decoded as Fastify decodes it */
654
+ function decodeParam(value: string): string {
655
+ try {
656
+ return decodeURIComponent(value);
657
+ } catch {
658
+ throw httpError(400, \`'\${value}' is not a valid url component\`);
659
+ }
660
+ }
661
+
662
+ /** The query of an event: a key given more than once is an array, as Fastify parses it */
663
+ function parseQuery(rawQueryString: string): Record<string, string | string[]> {
664
+ const query = new Map<string, string | string[]>();
665
+ for (const [key, value] of new URLSearchParams(rawQueryString)) {
666
+ const given = query.get(key);
667
+ query.set(key, given === undefined ? value : [given, value].flat());
668
+ }
669
+ return Object.fromEntries(query);
670
+ }
671
+
672
+ /** The JSON body of an event, none when it carries none, parsed as Fastify parses it */
673
+ function parseBody(event: HttpApiEvent, contentType: string | undefined): unknown {
674
+ if (!event.body) return undefined;
675
+ if (contentType?.split(';')[0].trim().toLowerCase() !== 'application/json') {
676
+ throw httpError(415, 'Unsupported Media Type');
677
+ }
678
+ const text = event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString('utf-8') : event.body;
679
+ let forbidden = false;
680
+ let body: unknown;
681
+ try {
682
+ body = JSON.parse(text, (key, value: unknown) => {
683
+ // A property that would set an object's prototype is refused
684
+ if (key === '__proto__' || (key === 'constructor' && typeof value === 'object' && value !== null && 'prototype' in value)) {
685
+ forbidden = true;
686
+ }
687
+ return value;
688
+ });
689
+ } catch {
690
+ throw httpError(400, "Body is not valid JSON but content-type is set to 'application/json'");
691
+ }
692
+ if (forbidden) throw httpError(400, 'Object contains forbidden prototype property');
693
+ return body;
694
+ }
695
+
696
+ /** Validate a part of the request, coercing it to its schema in place: one that fails is answered with 400 */
697
+ function check(validate: ValidateFunction | undefined, data: unknown, part: string): void {
698
+ if (validate && !validate(data ?? null)) {
699
+ throw httpError(400, (validate.errors ?? []).map(error => \`\${part}\${error.instancePath} \${error.message}\`).join(', '));
700
+ }
701
+ }
702
+
703
+ /** Answer an event a route matched: read and validate the request as Fastify does, then run the route */
704
+ async function answer(route: Route, values: string[], event: HttpApiEvent): Promise<Answer> {
705
+ const headers = Object.fromEntries(
706
+ Object.entries(event.headers ?? {}).flatMap(([name, value]) => (value === undefined ? [] : [[name.toLowerCase(), value]])),
707
+ );
708
+ const cookies = parseCookies(event.cookies);
709
+ const request: RouteRequest = {
710
+ params: Object.fromEntries(route.names.map((name, index) => [name, decodeParam(values[index])])),
711
+ query: parseQuery(event.rawQueryString),
712
+ headers,
713
+ cookies,
714
+ cookieParams: Object.fromEntries(
715
+ (route.cookieNames ?? []).flatMap(name => {
716
+ const value = cookies.get(name);
717
+ return value === undefined ? [] : [[name, value]];
718
+ }),
719
+ ),
720
+ body: route.body ? parseBody(event, headers['content-type']) : undefined,
721
+ };
722
+ check(route.params, request.params, 'params');
723
+ check(route.body, request.body, 'body');
724
+ check(route.querystring, request.query, 'querystring');
725
+ check(route.headers, request.headers, 'headers');
726
+ check(route.cookies, request.cookieParams, 'cookies');
727
+ return route.handler(request, replyOf(route.response));
728
+ }
729
+
730
+ // ==========================================================================
731
+ // Routes
732
+ // ==========================================================================
733
+
734
+ /** Answer each event with its operation, and an error as the contract's error shape */
735
+ function createDispatcher(options: HandlerOptions): (event: HttpApiEvent) => Promise<Answer> {
736
+ // Fastify's default validator options, except removeAdditional (see the README, Validators)
737
+ const ajv = new Ajv({ coerceTypes: 'array', useDefaults: true, removeAdditional: false, addUsedSchema: false, allErrors: false });
738
+ ajvFormats.default(ajv);
739
+ for (const schema of allSchemas) ajv.addSchema(schema);
740
+ // The generated schemas are readonly literals; the serializer's option type declares mutable
741
+ // ones of a narrower shape, though it only reads them
742
+ const schemas = Object.fromEntries(allSchemas.map(schema => [schema.$id, schema])) as unknown as Record<string, fastJson.Schema>;
743
+ const serializers = new Map<string, Serialize>();
744
+ /** The serializer of a registered schema, built once */
745
+ const serializer = (name: string): Serialize => {
746
+ let serialize = serializers.get(name);
747
+ if (!serialize) {
748
+ serialize = fastJson({ $ref: \`\${name}#\` }, { schema: schemas });
749
+ serializers.set(name, serialize);
750
+ }
751
+ return serialize;
752
+ };
753
+
754
+ const { {{#each services}}{{key}}{{#unless @last}}, {{/unless}}{{/each}} } = options.services;
755
+ {{#if extensionInfo.length}}
756
+ const { overlays } = options;
757
+ {{/if}}
758
+
759
+ const routes: Route[] = [
760
+ {{#each routes}}
761
+ // {{httpMethod}} {{path}}{{#if isPublished}} [PUBLISHED]{{/if}}
762
+ routeOf({
763
+ method: '{{httpMethod}}',
764
+ path: '{{path}}',
765
+ {{#if parameterSchemas.path}}
766
+ params: ajv.compile({ $ref: '{{parameterSchemas.path}}#' }),
767
+ {{/if}}
768
+ {{#if requestBody}}
769
+ body: ajv.compile({ $ref: '{{requestBody.schemaName}}#' }),
770
+ {{/if}}
771
+ {{#if parameterSchemas.query}}
772
+ querystring: ajv.compile({ $ref: '{{parameterSchemas.query}}#' }),
773
+ {{/if}}
774
+ {{#if parameterSchemas.header}}
775
+ headers: ajv.compile({{parameterSchemas.header}}),
776
+ {{/if}}
777
+ {{#if parameterSchemas.cookie}}
778
+ cookies: ajv.compile({ $ref: '{{parameterSchemas.cookie}}#' }),
779
+ cookieNames: [{{#each cookieParams}}'{{name}}', {{/each~}} ],
780
+ {{/if}}
781
+ response: { {{#each responseSchemas}}'{{status}}': serializer('{{schemaName}}'), {{/each~}} },
782
+ handler: async (request, reply) => {
783
+ {{#if extensions.length}}
784
+ const result = await runOverlays('{{operationId}}', overlays, request);
785
+ if (!result.success) return reply.send(result.error.status, result.error);
786
+ {{/if}}
787
+ const input: types.{{inputType}} = {
788
+ {{#if pathParams.length}}
789
+ ...(request.params as unknown as types.{{typeNameBase}}Params),
790
+ {{/if}}
791
+ {{#if queryParams.length}}
792
+ ...(request.query as unknown as types.{{typeNameBase}}Params),
793
+ {{/if}}
794
+ {{#if cookieParams.length}}
795
+ ...(request.cookieParams as unknown as types.{{typeNameBase}}Params),
796
+ {{/if}}
797
+ {{#if requestBody}}
798
+ data: request.body as types.{{requestBody.schemaName}},
799
+ {{/if}}
800
+ };
801
+ {{#if stream}}
802
+ {{!-- A stream's first event is awaited before anything is answered: a service that fails at once is answered as an error --}}
803
+ const events = {{serviceKey}}.{{serviceMethod}}(input)[Symbol.asyncIterator]();
804
+ const first = await events.next();
805
+ const frames = encodeStream('{{stream.format}}', first, events, serializer('{{stream.eventType}}'), '{{stream.discriminator}}');
806
+ return reply.stream({{successStatus}}, '{{stream.mediaType}}', frames);
807
+ {{else if (eq responseType "void")}}
808
+ await {{serviceKey}}.{{serviceMethod}}(input);
809
+ return reply.send({{successStatus}});
810
+ {{else}}
811
+ const output = await {{serviceKey}}.{{serviceMethod}}(input);
812
+ return reply.send({{successStatus}}, output);
813
+ {{/if}}
814
+ },
815
+ }),
332
816
  {{/each}}
333
- OverlayRegistry,
334
- } from '{{config.contractPackage}}/overlays';
817
+ ].sort((a, b) => (a.rank < b.rank ? -1 : a.rank > b.rank ? 1 : 0));
818
+
819
+ return async (event) => {
820
+ let route: Route | undefined;
821
+ try {
822
+ const method = event.requestContext.http.method.toUpperCase();
823
+ const base = options.basePath ?? '';
824
+ const path = event.rawPath === base ? '/' : event.rawPath.startsWith(\`\${base}/\`) ? event.rawPath.slice(base.length) : undefined;
825
+ const matches = path === undefined ? [] : routes.flatMap(candidate => {
826
+ const match = candidate.pattern.exec(path);
827
+ return match ? [{ route: candidate, values: match.slice(1) }] : [];
828
+ });
829
+ const match = matches.find(candidate => candidate.route.method === method);
830
+ if (!match) {
831
+ if (matches.length === 0) throw httpError(404, \`Route \${method}:\${event.rawPath} not found\`);
832
+ throw Object.assign(httpError(405, \`Method \${method} is not allowed on \${event.rawPath}\`), {
833
+ headers: { allow: [...new Set(matches.map(candidate => candidate.route.method))].join(', ') },
834
+ });
835
+ }
836
+ route = match.route;
837
+ return await answer(match.route, match.values, event);
838
+ } catch (error) {
839
+ const problem = problemOf(error);
840
+ if (problem.status >= 500) console.error(error);
841
+ const answered = replyOf(route?.response ?? {}).send(problem.status, problem);
842
+ return { ...answered, headers: { ...answered.headers, ...headersOf(error) } };
843
+ }
844
+ };
845
+ }
846
+
847
+ // ==========================================================================
848
+ // Handlers
849
+ // ==========================================================================
335
850
 
336
- {{#each extensions}}
337
851
  /**
338
- * {{name}} overlay handler
339
- *
340
- * Called when an endpoint has x-middleware: [{{name}}]
341
- * Returns OverlayResult with success/error status
852
+ * The Lambda handler, answering each event once its response is complete. A
853
+ * stream operation's events are answered together when its stream ends; to
854
+ * send each as the service yields it, use createStreamHandler.
342
855
  */
343
- export async function {{camelCase name}}(
344
- input: {{pascalCase name}}OverlayInput
345
- ): Promise<OverlayResult> {
346
- // TODO: Implement {{name}} logic
347
- {{#if injectedParameters}}
348
- // Input parameters:
349
- {{#each injectedParameters}}
350
- // - {{name}}: {{schema.type}}{{#if required}} (required){{/if}}
351
- {{/each}}
856
+ export function createHandler(options: HandlerOptions): (event: HttpApiEvent) => Promise<HttpApiResult> {
857
+ const dispatch = createDispatcher(options);
858
+ return async (event) => {
859
+ const { statusCode, headers, body } = await dispatch(event);
860
+ {{#if streams}}
861
+ if (typeof body !== 'string') {
862
+ let text = '';
863
+ for await (const frame of body) text += frame;
864
+ return { statusCode, headers, body: text };
865
+ }
352
866
  {{/if}}
867
+ return { statusCode, headers, body };
868
+ };
869
+ }
870
+ {{#if streams}}
353
871
 
354
- // Example implementation:
355
- // if (!validateSomething(input)) {
356
- // return {
357
- // success: false,
358
- // error: { status: 4xx, message: 'Error message', code: 'ERROR_CODE' },
359
- // };
360
- // }
872
+ /** The response streaming of the Lambda Node.js runtime: a global there */
873
+ declare const awslambda: {
874
+ streamifyResponse<H>(handler: H): H;
875
+ HttpResponseStream: {
876
+ from(responseStream: Writable, prelude: { statusCode: number; headers: Record<string, string> }): Writable;
877
+ };
878
+ };
361
879
 
362
- return { success: true, context: { /* optional context for service */ } };
363
- }
880
+ /** A Lambda handler answering through the response stream */
881
+ export type StreamHandler = (event: HttpApiEvent, responseStream: Writable) => Promise<void>;
364
882
 
365
- {{/each}}
366
883
  /**
367
- * Registry of all overlay handlers
368
- * Register this with your server framework
884
+ * The Lambda handler for a function URL whose invoke mode is RESPONSE_STREAM:
885
+ * a stream operation sends each event as its service yields it. When the
886
+ * client goes away, the service's iterator is closed at its next yield: a
887
+ * service waiting between events keeps running until it yields again. Other
888
+ * operations are answered as createHandler answers them.
369
889
  */
370
- export const overlayHandlers: OverlayRegistry = {
371
- {{#each extensions}}
372
- {{camelCase name}}: {{camelCase name}},
373
- {{/each}}
374
- };
890
+ export function createStreamHandler(options: HandlerOptions): StreamHandler {
891
+ const dispatch = createDispatcher(options);
892
+ return awslambda.streamifyResponse<StreamHandler>(async (event, responseStream) => {
893
+ const { statusCode, headers, body } = await dispatch(event);
894
+ await pipeline(Readable.from(body), awslambda.HttpResponseStream.from(responseStream, { statusCode, headers }));
895
+ });
896
+ }
897
+ {{/if}}
375
898
  `;
376
899
  // =============================================================================
377
900
  // Screen Spec Templates
@@ -444,6 +967,14 @@ export function getStarterTemplates() {
444
967
  'overlay-stubs.hbs': STARTER_OVERLAY_STUBS_TEMPLATE,
445
968
  };
446
969
  }
970
+ /**
971
+ * Get the AWS Lambda starter templates (init --lambda)
972
+ */
973
+ export function getLambdaStarterTemplates() {
974
+ return {
975
+ 'lambda-routes.hbs': STARTER_LAMBDA_ROUTES_TEMPLATE,
976
+ };
977
+ }
447
978
  /**
448
979
  * Get screen spec starter templates
449
980
  */