micro-contracts 0.20.0 → 0.20.2

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 (46) hide show
  1. package/README.md +111 -9
  2. package/cli-contract.yaml +10 -1
  3. package/dist/cli/templates.d.ts +4 -0
  4. package/dist/cli/templates.d.ts.map +1 -1
  5. package/dist/cli/templates.js +497 -48
  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 +149 -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 +11 -6
  26. package/dist/generator/linter.js.map +1 -1
  27. package/dist/generator/serviceGenerator.d.ts +6 -0
  28. package/dist/generator/serviceGenerator.d.ts.map +1 -1
  29. package/dist/generator/serviceGenerator.js +9 -7
  30. package/dist/generator/serviceGenerator.js.map +1 -1
  31. package/dist/generator/templateProcessor.d.ts +17 -2
  32. package/dist/generator/templateProcessor.d.ts.map +1 -1
  33. package/dist/generator/templateProcessor.js +16 -3
  34. package/dist/generator/templateProcessor.js.map +1 -1
  35. package/dist/generator/typeGenerator.d.ts +3 -1
  36. package/dist/generator/typeGenerator.d.ts.map +1 -1
  37. package/dist/generator/typeGenerator.js +12 -10
  38. package/dist/generator/typeGenerator.js.map +1 -1
  39. package/dist/micro-contracts.bundle.mjs +1235 -670
  40. package/dist/micro-contracts.bundle.mjs.map +4 -4
  41. package/dist/types.d.ts +31 -10
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/types.js +52 -27
  44. package/dist/types.js.map +1 -1
  45. package/docs/cli-reference.md +5 -1
  46. package/package.json +21 -21
@@ -17,31 +17,14 @@ import * as types from '{{contractPackage}}/schemas/types.js';
17
17
  {{!-- A header schema is given inline: Fastify matches header names case-insensitively only in an inline schema --}}
18
18
  import { {{#each routes}}{{#if parameterSchemas.header}}{{parameterSchemas.header}}, {{/if}}{{/each~}} } from '{{contractPackage}}/schemas/validators.js';
19
19
  {{#if extensionInfo.length}}
20
- import { runOverlays, sendError, type HttpRequest } 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';
21
25
  {{/if}}
22
26
  {{#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
- }
27
+ import { parseCookies } from '{{contractPackage}}/http/index.js';
45
28
  {{/if}}
46
29
  {{#if extensionInfo.length}}
47
30
 
@@ -55,6 +38,11 @@ function toHttpRequest(req: FastifyRequest, cookies: ReadonlyMap<string, string>
55
38
  body: req.body,
56
39
  };
57
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
+ }
58
46
  {{/if}}
59
47
 
60
48
  export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
@@ -80,6 +68,10 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
80
68
  {{#if parameterSchemas.cookie}}
81
69
  {{!-- Fastify parses no cookies: the route validates them, with the validator Fastify validates the rest with --}}
82
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}}#' };
83
75
  {{/if}}
84
76
  fastify.{{method}}('{{fastifyPath}}', {
85
77
  schema: {
@@ -138,7 +130,14 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
138
130
  {{/if}}
139
131
  };
140
132
  {{!-- The success status is set once the service has returned: an error it throws keeps its own status. --}}
141
- {{#if (eq responseType "void")}}
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")}}
142
141
  await {{serviceKey}}.{{serviceMethod}}(input);
143
142
  return reply.code({{successStatus}}).send();
144
143
  {{else}}
@@ -172,6 +171,9 @@ import type {
172
171
  {{/each}}
173
172
  } from '{{contractPackage}}/schemas';
174
173
  import { ApiError } from '{{contractPackage}}/errors';
174
+ {{#if streams}}
175
+ import { decodeStream } from '{{contractPackage}}/streams';
176
+ {{/if}}
175
177
 
176
178
  // BASE_URL derived from OpenAPI servers[0].url: {{baseUrl}}
177
179
  // Can be overridden via environment variable (Vite: VITE_API_BASE_URL)
@@ -195,6 +197,26 @@ async function handleResponse<T>(res: Response): Promise<T> {
195
197
  }
196
198
  return res.json();
197
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}}
198
220
 
199
221
  {{#each services}}
200
222
  // ==========================================================================
@@ -208,7 +230,7 @@ export const {{key}}Api = {
208
230
  {{#if summary}}* {{summary}}{{/if}}
209
231
  {{#if isPublished}}* @published{{/if}}
210
232
  */
211
- async {{serviceMethod}}(input: {{clientInputType}}): Promise<{{responseType}}> {
233
+ async {{#if stream}}*{{/if}}{{serviceMethod}}(input: {{clientInputType}}): {{#if stream}}AsyncGenerator<{{stream.eventType}}>{{else}}Promise<{{responseType}}>{{/if}} {
212
234
  {{#if queryParams.length}}
213
235
  const searchParams = new URLSearchParams();
214
236
  {{#each queryParams}}
@@ -231,7 +253,10 @@ export const {{key}}Api = {
231
253
  {{else}}
232
254
  const res = await fetch(url, { method: '{{httpMethod}}' });
233
255
  {{/if}}
234
- {{#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")}}
235
260
  await handleResponse<void>(res);
236
261
  {{else}}
237
262
  return handleResponse<{{responseType}}>(res);
@@ -262,7 +287,7 @@ export class {{name}}Service implements {{name}}ServiceApi {
262
287
  /**
263
288
  * {{httpMethod}} {{path}}{{#if summary}}: {{summary}}{{/if}}
264
289
  */
265
- async {{serviceMethod}}(input: types.{{inputType}}): Promise<{{#if (eq responseType "void")}}void{{else}}types.{{responseType}}{{/if}}> {
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}} {
266
291
  // TODO: Implement {{serviceMethod}}
267
292
  throw new Error('Not implemented: {{service}}.{{serviceMethod}}');
268
293
  }
@@ -279,9 +304,9 @@ const STARTER_OVERLAY_ADAPTER_TEMPLATE = `/**
279
304
  * DO NOT EDIT MANUALLY
280
305
  */
281
306
 
282
- import type { FastifyReply } from 'fastify';
283
307
  import type { OverlayResult, OverlayRegistry } from '{{contractPackage}}/overlays/index.js';
284
308
  import type { ProblemDetails } from '{{contractPackage}}/schemas/types.js';
309
+ import { toProblemDetails } from '{{contractPackage}}/errors/index.js';
285
310
 
286
311
  // ==========================================================================
287
312
  // Types
@@ -367,7 +392,7 @@ export async function runOverlays(
367
392
  if (!handler) {
368
393
  throw new Error(
369
394
  \`[SECURITY] Overlay handler "\${name}" is required for operation "\${operationId}" but not registered. \` +
370
- \`Register it in server.ts: fastify.decorate('overlayHandlers', { \${name}: ... })\`
395
+ \`Register it in the overlay registry the routes are given: { \${name}: ... }\`
371
396
  );
372
397
  }
373
398
  if (!extract) {
@@ -383,24 +408,17 @@ export async function runOverlays(
383
408
  if (missing.length > 0) {
384
409
  return {
385
410
  success: false,
386
- error: {
387
- type: '/errors/missing_parameter',
388
- title: \`Missing required parameter: \${missing.join(', ')}\`,
411
+ error: toProblemDetails({
389
412
  status: 400,
390
- },
413
+ message: \`Missing required parameter: \${missing.join(', ')}\`,
414
+ code: 'MISSING_PARAMETER',
415
+ }),
391
416
  };
392
417
  }
393
418
  const result = await (handler as unknown as (input: Record<string, unknown>) => Promise<OverlayResult<unknown>>)(input);
394
419
 
395
420
  if (!result.success) {
396
- return {
397
- success: false,
398
- error: {
399
- type: \`/errors/\${result.error?.code?.toLowerCase() ?? 'error'}\`,
400
- title: result.error?.message ?? 'Error',
401
- status: result.error?.status ?? 500,
402
- },
403
- };
421
+ return { success: false, error: toProblemDetails(result.error ?? { status: 500, message: 'Error' }) };
404
422
  }
405
423
 
406
424
  if (result.context) {
@@ -410,13 +428,6 @@ export async function runOverlays(
410
428
 
411
429
  return { success: true, context };
412
430
  }
413
-
414
- /**
415
- * Send error response
416
- */
417
- export function sendError(reply: FastifyReply, error: ProblemDetails): void {
418
- reply.status(error.status).send(error);
419
- }
420
431
  `;
421
432
  const STARTER_OVERLAY_STUBS_TEMPLATE = `{{!-- Overlay handler stubs: a handler per overlay, in the OverlayRegistry --}}
422
433
  // Auto-generated overlay handler stubs - Edit to implement overlay logic
@@ -456,6 +467,436 @@ export const overlayHandlers: OverlayRegistry = {
456
467
  };
457
468
  `;
458
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 {
608
+ return {
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}}
616
+ };
617
+ }
618
+
619
+ /**
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.
622
+ */
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
+ });
630
+ }
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
+ }),
816
+ {{/each}}
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
+ // ==========================================================================
850
+
851
+ /**
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.
855
+ */
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
+ }
866
+ {{/if}}
867
+ return { statusCode, headers, body };
868
+ };
869
+ }
870
+ {{#if streams}}
871
+
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
+ };
879
+
880
+ /** A Lambda handler answering through the response stream */
881
+ export type StreamHandler = (event: HttpApiEvent, responseStream: Writable) => Promise<void>;
882
+
883
+ /**
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.
889
+ */
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}}
898
+ `;
899
+ // =============================================================================
459
900
  // Screen Spec Templates
460
901
  // =============================================================================
461
902
  const STARTER_SCREEN_NAVIGATION_TEMPLATE = `/**
@@ -526,6 +967,14 @@ export function getStarterTemplates() {
526
967
  'overlay-stubs.hbs': STARTER_OVERLAY_STUBS_TEMPLATE,
527
968
  };
528
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
+ }
529
978
  /**
530
979
  * Get screen spec starter templates
531
980
  */
@@ -1 +1 @@
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;;G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