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
package/README.md CHANGED
@@ -172,11 +172,15 @@ project/
172
172
  │ │ ├── schemas/ # Types, validators
173
173
  │ │ ├── services/ # Service interfaces
174
174
  │ │ ├── overlays/ # Overlay handler interfaces
175
+ │ │ ├── errors/ # Error shape (ProblemDetails, ApiError)
176
+ │ │ ├── http/ # Request reading the server templates share (cookies)
177
+ │ │ ├── streams/ # Stream framing (modules with stream responses)
175
178
  │ │ └── deps/ # Re-exports from dependencies
176
179
  │ └── contract-published/{module}/ # Public API subset
177
180
  │
178
181
  ├── server/src/{module}/
179
182
  │ ├── routes.generated.ts # ❌ Auto-generated (template: fastify-routes.hbs)
183
+ │ ├── lambda.generated.ts # ❌ Auto-generated (template: lambda-routes.hbs, init --lambda)
180
184
  │ ├── services/ # ✅ Human-edited (service implementations)
181
185
  │ └── overlays/ # ✅ Human-edited (overlay implementations)
182
186
  │
@@ -299,7 +303,7 @@ Create `micro-contracts.config.yaml`. All paths support `{module}` placeholder.
299
303
  | `outputs.<id>.output` | string | yes | Output file path |
300
304
  | `outputs.<id>.template` | string | yes | Handlebars template file path, used as written (resolved from the working directory) |
301
305
  | `outputs.<id>.overwrite` | boolean | no | Overwrite existing files (default: `true`) |
302
- | `outputs.<id>.condition` | string | no | `hasPublicEndpoints` \| `hasOverlays` \| `always` (default: `always`) |
306
+ | `outputs.<id>.condition` | string | no | `hasPublicEndpoints` \| `hasOverlays` \| `always` (default: `always`). An output under `hasPublicEndpoints` is generated for a module with published operations, and rendered over what `contract-published` carries: those operations and their schemas |
303
307
  | `outputs.<id>.enabled` | boolean | no | Enable/disable this output (default: `true`) |
304
308
  | `outputs.<id>.config` | object | no | Template-specific configuration passed to context |
305
309
 
@@ -421,6 +425,7 @@ Initialize a new module structure with starter templates.
421
425
  | `-o, --output <path>` | Output path for processed OpenAPI |
422
426
  | `--skip-templates` | Skip creating starter templates |
423
427
  | `--screens` | Initialize as screen spec module (generates screen templates and starter spec) |
428
+ | `--lambda` | Also create the AWS Lambda handler template (`lambda-routes.hbs`), and configure it as the server output in place of the Fastify routes (see [AWS Lambda](#aws-lambda)) |
424
429
 
425
430
  ### lint \<input\>
426
431
 
@@ -438,6 +443,19 @@ would be dropped from every artifact, so they are errors (`MISSING_X_SERVICE`,
438
443
  (`screen: true`) operations are consumed via `TemplateContext.screens` and these rules
439
444
  do not apply.
440
445
 
446
+ An operation's success response is its lowest 2xx status code, else its `2XX` range, else
447
+ `default`: the service returns that response's body and the generated route answers with
448
+ that status (200 for `2XX` and `default`). An operation that declares none of them is an
449
+ error: declare the response a successful call returns. Its request body must be
450
+ `application/json`, and its success response `application/json` or a stream —
451
+ `text/event-stream`, `application/x-ndjson` or `application/jsonl` — since a body in any other
452
+ media type would be dropped from every generated artifact; one declared otherwise is an
453
+ error: remove that media type, and declare the body in one of them. A stream declares the
454
+ schema of one event under `x-stream-event`, as a `oneOf` with `discriminator.propertyName`:
455
+ a stream without `x-stream-event`, or whose events have no discriminator, is an error. A
456
+ response of any other status, which documents an error, may use any media type; generated
457
+ code has a schema only for an `application/json` one.
458
+
441
459
  `<input>` is linted under the rules of the module in `micro-contracts.config.yaml` whose
442
460
  `openapi` it is — the rules `generate` applies to it — and as a service API spec when no
443
461
  module declares it.
@@ -609,23 +627,115 @@ export class UserService implements UserServiceApi {
609
627
  }
610
628
  ```
611
629
 
630
+ ### Stream Responses
631
+
632
+ An operation whose success response is `text/event-stream` (server-sent events) or
633
+ `application/x-ndjson` / `application/jsonl` (one JSON value per line) streams events. The
634
+ schema of one event is declared under `x-stream-event`: a `oneOf` whose `discriminator`
635
+ names each event's type.
636
+
637
+ ```yaml
638
+ responses:
639
+ '200':
640
+ description: Reply, as it is written
641
+ content:
642
+ text/event-stream:
643
+ x-stream-event:
644
+ oneOf:
645
+ - $ref: '#/components/schemas/TextDelta'
646
+ - $ref: '#/components/schemas/StreamEnd'
647
+ discriminator: { propertyName: type }
648
+ ```
649
+
650
+ The event type is the referenced component, or `<Service>_<method>Event` for an inline schema,
651
+ in `schemas/types.ts` and among the validators. The service returns its events as an
652
+ `AsyncIterable`:
653
+
654
+ ```typescript
655
+ export interface ChatServiceApi {
656
+ reply(input: Chat_replyInput): AsyncIterable<Chat_replyEvent>;
657
+ }
658
+ ```
659
+
660
+ The contract package carries the framing, `streams/index.ts`: routes encode events with
661
+ `encodeStream` and clients decode them with `decodeStream`. A server-sent event is
662
+ `event: <discriminator value>`, `data: <the event as JSON>` and a blank line; NDJSON is one
663
+ event per line.
664
+
665
+ The starter Fastify route awaits the service's first event before sending anything, so a
666
+ service that fails at once answers through the error handler, as a JSON operation does. It
667
+ then sends the success status with the declared media type, and each event as the service
668
+ yields it, serialized by the event schema as a JSON response is: a property the schema does
669
+ not declare is not sent, and an event no member of the schema accepts ends the stream. When
670
+ the client goes away, the service's iterator is closed at its next yield: a service waiting
671
+ between events keeps running until it yields again. The starter fetch client returns the
672
+ events as an `AsyncIterable` to read with `for await`.
673
+
612
674
  ### Validators
613
675
 
614
676
  `schemas/validators.ts` holds every schema as the JSON Schema Fastify validates requests and
615
- serializes responses with, plus the path, query and inline request body schemas of each
616
- operation (`<Service>_<method>PathParams`, `…QueryParams`, `…Body`). Every validation keyword
617
- of the contract is kept. Only what JSON Schema spells differently is translated (`$ref`,
618
- `nullable`, OpenAPI 3.0's boolean `exclusiveMinimum` / `exclusiveMaximum`), and what never
619
- validates is left out: `x-*` extensions, the annotations `example`, `examples`, `xml`,
620
- `externalDocs` and `discriminator`, and `$id` / `$schema` (each schema is named by its
621
- component name).
677
+ serializes responses with, plus the path, query, header and cookie parameter schemas of each
678
+ operation (`<Service>_<method>PathParams`, `…QueryParams`, `…HeaderParams`, `…CookieParams`)
679
+ and its inline request body, response and stream event schemas (`…Body`; `…Response` for the
680
+ success response, and `…404Response`, `…4XXResponse` or `…DefaultResponse` for another;
681
+ `…Event`).
682
+ `schemas/types.ts` names the inline body types the same way. A header parameter schema names headers in lower case, as a
683
+ request delivers them, and is not in `allSchemas`: the starter routes give it to Fastify
684
+ inline (`schema.headers`), since Fastify matches header names case-insensitively only in an
685
+ inline schema. Fastify does not parse cookies, so a starter route reads the cookie parameters
686
+ from the Cookie header and validates them against `…CookieParams` with the validator Fastify
687
+ validates the rest with (`request.compileValidationSchema`). A request missing a required
688
+ header or cookie, or carrying one that does not match its schema, is answered with 400 before
689
+ the service runs. The service's input holds the path, query and cookie parameters; headers
690
+ are validated only. A client is called without cookies, which the browser sends: an operation
691
+ with cookie parameters gets a client input (`<Service>_<method>ClientInput`) — its input with
692
+ the cookie parameters optional — which the starter fetch client takes. Being wider than the
693
+ service's input, it lets the client still satisfy the service interface.
694
+
695
+ The starter fetch client calls `fetch` without a `credentials` option and takes no fetch
696
+ options, so the browser sends cookies under fetch's default, `same-origin`: with a request to
697
+ the page's own origin — directly, or through a dev-server proxy — and with no other. For an
698
+ API on another origin, set `credentials: 'include'` on the `fetch` calls in your copy of
699
+ `fetch-client.hbs`, and have the server allow credentialed CORS: an explicit allowed origin and
700
+ `Access-Control-Allow-Credentials: true` (with `@fastify/cors`, `credentials: true`). A cookie
701
+ sent to another site must also be `SameSite=None; Secure`.
702
+
703
+ Every validation keyword of the contract is kept. Only what JSON Schema spells differently is
704
+ translated (`$ref`, `nullable`, OpenAPI 3.0's boolean `exclusiveMinimum` /
705
+ `exclusiveMaximum`), and what never validates is left out: `x-*` extensions, the annotations
706
+ `example`, `examples`, `xml`, `externalDocs` and `discriminator`, and `$id` / `$schema` (each
707
+ schema is named by its component name). A `oneOf` selects its member by validating each one,
708
+ so a member is chosen by its `discriminator` tag when each member fixes the tag with `enum` or
709
+ `const`.
710
+
711
+ The starter routes (`fastify-routes.hbs`) register, for each operation, the schema of every
712
+ declared response whose body is `application/json`: the success response's under the status
713
+ the route answers with, any other under its status code — a range as Fastify reads it (`4XX`
714
+ as `4xx`), and `default`. Fastify serializes every response with the schema of its status, an
715
+ error included, so a property the contract does not declare for that status is not sent. The
716
+ server's error handler must therefore send the shape the contract declares for the error's
717
+ status — as the example's ProblemDetails handler (`examples/server/src/server.ts`) does: a body
718
+ missing a required property fails serialization and is answered with 500, which is what
719
+ Fastify's default error handler does for a `ProblemDetails` response.
720
+
721
+ Validate with Fastify's default validator options except `removeAdditional`, set to `false`.
722
+ Ajv validates each member of a `oneOf` or `anyOf` against the value itself, and with
723
+ `removeAdditional: true` — Fastify's default — validating a member removes every property that
724
+ member's `additionalProperties: false` does not allow, whether or not the member matches: a
725
+ valid value is rejected, or reaches the service with properties missing. With `false`, a
726
+ property a schema does not allow is rejected rather than removed — and a property a schema
727
+ without `additionalProperties: false` does not declare reaches the service, so a service reads
728
+ the fields its input declares rather than storing the value it receives as a whole.
729
+
730
+ ```typescript
731
+ const fastify = Fastify({ ajv: { customOptions: { removeAdditional: false } } });
732
+ ```
622
733
 
623
734
  Fastify validates with Ajv on JSON Schema draft-07. A contract using the keywords JSON Schema
624
735
  2019-09 / 2020-12 added — `prefixItems`, `dependentRequired`, `dependentSchemas`,
625
736
  `minContains` / `maxContains`, `unevaluatedProperties` / `unevaluatedItems` — stops Fastify
626
737
  from starting (`strict mode: unknown keyword`). To use them, validate with Ajv on the 2020-12
627
- dialect, with the options Fastify validates with by default (add `ajv` and `ajv-formats` to
628
- your dependencies). A validator set this way does not read `fastify.addSchema`, so it is given
738
+ 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
739
  the generated schemas itself; the generated routes still register them with Fastify, which
630
740
  serializes responses with them.
631
741
 
@@ -635,8 +745,8 @@ import { Ajv2020 } from 'ajv/dist/2020.js';
635
745
  import ajvFormats from 'ajv-formats';
636
746
  import { allSchemas } from '@project/contract/core/schemas/index.js';
637
747
 
638
- // The options Fastify validates with by default, on the 2020-12 dialect.
639
- const ajv = new Ajv2020({ coerceTypes: 'array', useDefaults: true, removeAdditional: true, allErrors: false });
748
+ // Fastify's default validator options with removeAdditional: false, on the 2020-12 dialect.
749
+ const ajv = new Ajv2020({ coerceTypes: 'array', useDefaults: true, removeAdditional: false, allErrors: false });
640
750
  ajvFormats.default(ajv);
641
751
  // A custom validator does not read fastify.addSchema: give it every module's schemas, once each.
642
752
  for (const schema of allSchemas) {
@@ -647,6 +757,55 @@ const fastify = Fastify();
647
757
  fastify.setValidatorCompiler(({ schema }) => ajv.compile(schema));
648
758
  ```
649
759
 
760
+ ### AWS Lambda
761
+
762
+ `init --lambda` also writes `lambda-routes.hbs`, a handler for the events of an API Gateway
763
+ HTTP API (payload format 2.0) and of a Lambda function URL, and configures it as the server
764
+ output (`server/src/{module}/lambda.generated.ts`) in place of the Fastify routes. It runs a
765
+ module's operations without Fastify — one Lambda function per module — and needs `ajv`,
766
+ `ajv-formats` and `fast-json-stringify` in your dependencies.
767
+
768
+ ```typescript
769
+ import { createHandler } from './billing/lambda.generated.js';
770
+ import { BillingService } from './billing/services/index.js';
771
+ import { requireAuth, tenantIsolation } from './billing/overlays/index.js';
772
+
773
+ export const handler = createHandler({
774
+ services: { billing: new BillingService() },
775
+ overlays: { requireAuth, tenantIsolation },
776
+ basePath: '/prod', // what the event's path carries before the spec's paths, if anything
777
+ });
778
+ ```
779
+
780
+ The handler answers as the starter Fastify routes do:
781
+
782
+ - It routes an event by `rawPath` and `requestContext.http.method`, a literal path segment
783
+ before a parameter. A path no operation has is answered with 404, and another method of an
784
+ operation's path with 405 and `Allow`.
785
+ - It validates the path, query, header and cookie parameters and the body against the
786
+ schemas the Fastify routes use, with Fastify's default validator options except
787
+ `removeAdditional: false` (see [Validators](#validators)), and words a refusal (400) as
788
+ Fastify does (`querystring/limit must be integer`). The query is read from
789
+ `rawQueryString`, a key given more than once being an array; headers in lower case; cookies
790
+ from the event's `cookies`. A body is JSON — decoded first when `isBase64Encoded` — and
791
+ another content type is answered with 415.
792
+ - It runs the operation's overlays (`overlayAdapter.generated.ts`), then the service, and
793
+ answers with the success status and the body serialized by the schema declared for it.
794
+
795
+ An error — a refused request, an overlay's refusal, a service's throw — is answered as the
796
+ contract's `ProblemDetails`, with `toProblemDetails` from the contract's `errors/`: a thrown
797
+ error's `status` or `statusCode` (400–599) is the response's status, any other error is 500
798
+ and logged, and its message is the title. The body is serialized by the schema declared for
799
+ that status, as Fastify serializes an error.
800
+
801
+ A [stream operation](#stream-responses) needs the response streaming of a function URL whose
802
+ invoke mode is `RESPONSE_STREAM`. For one, the template exports `createStreamHandler` too, a
803
+ handler wrapped in `awslambda.streamifyResponse` that sends each event as the service yields
804
+ it. When the response stream closes, the service's iterator is closed at its next yield: a
805
+ service waiting between events keeps running until it yields again. It answers the other
806
+ operations as `createHandler` does. `createHandler` answers a stream operation with all its
807
+ events at once, when the stream ends.
808
+
650
809
  ---
651
810
 
652
811
  ## Related Documentation
package/cli-contract.yaml CHANGED
@@ -3,7 +3,7 @@ cli_contracts: 0.1.0
3
3
 
4
4
  info:
5
5
  title: micro-contracts CLI
6
- version: 0.19.0
6
+ version: 0.20.1
7
7
  description: >-
8
8
  Contract-first OpenAPI toolchain for TypeScript Web/API systems.
9
9
  Generates contract packages, server routes, and frontend clients
@@ -248,6 +248,7 @@ command_sets:
248
248
  - micro-contracts init core
249
249
  - micro-contracts init core --openapi path/to/spec.yaml
250
250
  - micro-contracts init myScreens --screens
251
+ - micro-contracts init billing --lambda
251
252
  - micro-contracts init users --skip-templates
252
253
 
253
254
  arguments:
@@ -298,6 +299,14 @@ command_sets:
298
299
  type: boolean
299
300
  default: false
300
301
 
302
+ - name: lambda
303
+ description: >-
304
+ Also create the AWS Lambda handler template (lambda-routes.hbs), and configure it as
305
+ the server output in place of the Fastify routes.
306
+ schema:
307
+ type: boolean
308
+ default: false
309
+
301
310
  exits:
302
311
  '0':
303
312
  description: Module initialized successfully.
@@ -2,12 +2,17 @@
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
  /**
8
9
  * Get all starter templates
9
10
  */
10
11
  export declare function getStarterTemplates(): Record<string, string>;
12
+ /**
13
+ * Get the AWS Lambda starter templates (init --lambda)
14
+ */
15
+ export declare function getLambdaStarterTemplates(): Record<string, string>;
11
16
  /**
12
17
  * Get screen spec starter templates
13
18
  */
@@ -1 +1 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAsbH;;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"}
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAk8BH;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ5D;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAIlE;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKlE"}