@bidirekt/typescript-sdk-cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,7 +20,7 @@ With decorators, your app imports them at runtime, so install them as a regular
20
20
  npm install @bidirekt/typescript-sdk
21
21
  ```
22
22
 
23
- Their types need TypeScript 5.0 or later. GraphQL contracts need the Bidirekt CLI and broker 0.4.0 or later.
23
+ Their types need TypeScript 5.0 or later. GraphQL contracts need the Bidirekt CLI and broker 0.4.0 or later, and `__typename` the broker 0.5.0. `bidirekt validate` and `bidirekt publish` without file arguments need the CLI 0.5.0.
24
24
 
25
25
  ## Quickstart
26
26
 
@@ -147,7 +147,10 @@ export class PetsController {
147
147
  if (typeof body.name !== 'string') {
148
148
  throw new BadRequestException()
149
149
  }
150
- const pet = Object.assign(new Pet(), { petId: this.pets.size + 1, ...body })
150
+ const pet = Object.assign(new Pet(), {
151
+ petId: this.pets.size + 1,
152
+ ...body,
153
+ })
151
154
  this.pets.set(pet.petId, pet)
152
155
  return pet
153
156
  }
@@ -170,7 +173,8 @@ export class RatingsClient {
170
173
  })
171
174
  async find(petId: number): Promise<Rating | null> {
172
175
  const response = await fetch(`http://petstore-reviews/ratings/${petId}`)
173
- return response.status === 404 ? null : ((await response.json()) as Rating)
176
+ if (response.status === 404) return null
177
+ return (await response.json()) as Rating
174
178
  }
175
179
  }
176
180
  ```
@@ -299,7 +303,8 @@ import type { Rating } from './pet.ts'
299
303
  */
300
304
  export async function findRating(petId: number): Promise<Rating | null> {
301
305
  const response = await fetch(`http://petstore-reviews/ratings/${petId}`)
302
- return response.status === 404 ? null : ((await response.json()) as Rating)
306
+ if (response.status === 404) return null
307
+ return (await response.json()) as Rating
303
308
  }
304
309
  ```
305
310
 
@@ -517,17 +522,17 @@ You never edit `contracts/generated.yaml` by hand: the next `generate` writes ov
517
522
 
518
523
  ```sh
519
524
  npx @bidirekt/typescript-sdk-cli generate
520
- bidirekt validate contracts/generated.yaml
521
- bidirekt validate contracts/generated.yaml --participant petstore_ts --environment production
522
- bidirekt publish contracts/generated.yaml --participant petstore_ts --version 1.4.0
525
+ bidirekt validate
526
+ bidirekt validate --participant petstore_ts --environment production
527
+ bidirekt publish --participant petstore_ts --version 1.4.0
523
528
  bidirekt can-i-deploy petstore_ts --version 1.4.0 --environment production
524
529
  # deploy
525
530
  bidirekt record-deployment petstore_ts --version 1.4.0 --environment production
526
531
  ```
527
532
 
528
- `validate` without `--participant` and `--environment` checks only the file; with them, it also compares the file with what is deployed in that environment. When `can-i-deploy` reports a break, fix the annotation or the type in the code and generate again.
533
+ Without file arguments, `validate` and `publish` read the `contracts/` folder of the current directory. `validate` without `--participant` and `--environment` checks only the file; with them, it also compares the file with what is deployed in that environment. When `can-i-deploy` reports a break, fix the annotation or the type in the code and generate again.
529
534
 
530
- A subgraph, a service that declares its graph with `@BidirektGraph` or `@bidirekt graph`, validates and publishes its own GraphQL schema together with the contract: `bidirekt validate contracts/generated.yaml src/schema.graphql`, and the same two files in `publish`. `contracts/generated.yaml` alone fails with `graph "petstore_graph" without a GraphQL schema`.
535
+ A subgraph, a service that declares its graph with `@BidirektGraph` or `@bidirekt graph`, validates and publishes its own GraphQL schema together with the contract: `bidirekt validate contracts/ src/schema.graphql`, and the same in `publish`. `contracts/` alone fails with `graph "petstore_graph" without a GraphQL schema`.
531
536
 
532
537
  A package of your workspace, which npm links into `node_modules`, is read as your code when its `types` or `exports` point at its source. A class, interface or type reached through its built `.d.ts` stops `generate`.
533
538
 
@@ -537,7 +542,7 @@ A package of your workspace, which npm links into `node_modules`, is read as you
537
542
 
538
543
  | Decorator | Goes on | Options |
539
544
  | ----------------------------------- | ---------- | ------------------------------------------------------------------------------ |
540
- | `@BidirektSchema(options?)` | a class | `name`, `union` |
545
+ | `@BidirektSchema(options?)` | a class | `name`, `union`, `graphqlType` |
541
546
  | `@BidirektField(options?)` | a property | `type`, `name`, `optional`, `nullable`, `description`, `union`, see Fields |
542
547
  | `@BidirektRestProvider(options)` | a method | `method`, `path`, `request`, `responses` |
543
548
  | `@BidirektRestConsumer(options)` | a method | `provider`, `method`, `path`, `request`, `responses` |
@@ -551,18 +556,18 @@ With `emitDecoratorMetadata` on (NestJS, TypeORM), TypeScript keeps the imports
551
556
 
552
557
  ### Tags
553
558
 
554
- | Tag | Goes above |
555
- | -------------------------------------------------------------- | ------------------------------------------------------------------------------ |
556
- | `@bidirekt schema [name=<Name>] [union={...}]` | a class, an `interface`, an object `type` or a string `enum` |
557
- | `@bidirekt field [key=value ...]` | a property of a schema |
558
- | `@bidirekt rest provides <METHOD> <path>` | a function, an exported arrow function, a method or a statement (`router.get`) |
559
- | `@bidirekt rest consumes <provider> <METHOD> <path>` | the same |
560
- | `@bidirekt request [body]` | follows `rest provides` or `rest consumes` |
561
- | `@bidirekt response <status> [body]` | follows `rest provides` or `rest consumes`, once per status |
562
- | `@bidirekt graphql consumes <provider> query\|mutation <name>` | the same as `rest provides` |
563
- | `@bidirekt arguments <schema>`, `@bidirekt returns <type>` | follow `graphql consumes`, see GraphQL returns |
564
- | `@bidirekt graphql field [key=value ...]` | a property of a schema, in place of `field`, see Fields |
565
- | `@bidirekt graph <name>` | a class or any other element: `name` is the graph the service is a subgraph of |
559
+ | Tag | Goes above |
560
+ | ------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
561
+ | `@bidirekt schema [name=<Name>] [union={...}] [graphqlType=<Type>]` | a class, an `interface`, an object `type` or a string `enum` |
562
+ | `@bidirekt field [key=value ...]` | a property of a schema |
563
+ | `@bidirekt rest provides <METHOD> <path>` | a function, an exported arrow function, a method or a statement (`router.get`) |
564
+ | `@bidirekt rest consumes <provider> <METHOD> <path>` | the same |
565
+ | `@bidirekt request [body]` | follows `rest provides` or `rest consumes` |
566
+ | `@bidirekt response <status> [body]` | follows `rest provides` or `rest consumes`, once per status |
567
+ | `@bidirekt graphql consumes <provider> query\|mutation <name>` | the same as `rest provides` |
568
+ | `@bidirekt arguments <schema>`, `@bidirekt returns <type>` | follow `graphql consumes`, see GraphQL returns |
569
+ | `@bidirekt graphql field [key=value ...]` | a property of a schema, in place of `field`, see Fields |
570
+ | `@bidirekt graph <name>` | a class or any other element: `name` is the graph the service is a subgraph of |
566
571
 
567
572
  - A handler's comment can also declare schemas, see [Schemas in a handler's comment](#schemas-in-a-handlers-comment).
568
573
  - A tag starts a line of a `/** */` comment, and its arguments are separated by spaces. Only a `description` value is quoted (`description="Shown on the card"`), and inside the quotes it holds only ASCII letters and digits, with single spaces between words. Only a `union=` value is grouped in `{...}`, with optional spaces inside; quotes or braces anywhere else stop `generate`.
@@ -596,11 +601,24 @@ Without a request (no `request` option, no `@bidirekt request` tag), the resourc
596
601
  | a list or null | `{ list: Pet, nullable: true }` | `Pet[]?` | `PetListOrNull` |
597
602
  | a list of items or null | `{ list: Pet, nullableItems: true }` | `Pet?[]` | `PetOrNullList` |
598
603
  | a primitive | `'boolean'` | `boolean` | `Boolean` |
599
- | a custom scalar | `{ scalar: 'DateTime' }` | `scalar:DateTime` | `DateTime` |
604
+ | a named primitive | `{ type: 'boolean', name: 'Flag' }` | `boolean as Flag` | `Flag` |
605
+ | a scalar | `{ scalar: 'DateTime' }` | `scalar:DateTime` | `DateTime` |
600
606
  | an enum | `{ enum: ['AVAILABLE', 'SOLD'], name: 'Status' }` | `enum:AVAILABLE\|SOLD as Status` | `Status` |
601
607
  | a union | `{ union: { Pet: Pet, Owner: Owner }, name: 'SearchResult' }` | `union={Pet: Pet, Owner: Owner} as SearchResult` | `SearchResult` |
602
608
 
603
- A primitive, a scalar, an enum or a union also takes the place of the schema in a nullable or a list (`{ nullable: 'integer' }`, `'string[]'`, `scalar:DateTime?[]`). Each key of a union is the name of one of its types in the provider's GraphQL schema, and its value the schema the call reads from that type. Each form but a schema returned as it is becomes a schema of the contract, with the name above, and `name` in the decorator or `as <name>` in the tag gives it another one (`{ nullable: Pet, name: 'MaybePet' }`, `Pet? as MaybePet`). They name only a schema `generate` creates: a schema returned as it is is not copied, the call references it by its own name, so `@bidirekt returns Pet as MyPet` stops `generate`. To call it `MyPet`, name the schema itself, with `@BidirektSchema({ name })` or `@bidirekt schema name=<Name>`. A primitive returned as it is takes another name only in the tag (`boolean as Flag`): in the decorator it is a bare string, `'boolean'`, always written as `Boolean`. An enum or a union in a nullable or a list is a schema of its own, under the name it declares, and the nullable or the list references it under the name above: `{ nullable: { enum: ['AVAILABLE', 'SOLD'], name: 'Status' } }` and `enum:AVAILABLE|SOLD? as Status` both write `Status` and `StatusOrNull: {ref: Status, nullable: true}`. In the tag, that `as` names the enum or the union, never the nullable or the list around it. A scalar in a nullable or a list takes no name of its own: the name goes on the nullable or the list, and in the tag `as` names them.
609
+ A primitive, a scalar, an enum or a union also takes the place of the schema in a nullable or a list (`{ nullable: 'integer' }`, `'string[]'`, `scalar:DateTime?[]`). Each key of a union is the name of one of its types in the provider's GraphQL schema, and its value the schema the call reads from that type. Each form but a schema returned as it is becomes a schema of the contract, with the name above, and `name` in the decorator or `as <name>` in the tag gives it another one (`{ nullable: Pet, name: 'MaybePet' }`, `Pet? as MaybePet`). They name only a schema `generate` creates: a schema returned as it is is not copied, the call references it by its own name, so `@bidirekt returns Pet as MyPet` stops `generate`. To call it `MyPet`, name the schema itself, with `@BidirektSchema({ name })` or `@bidirekt schema name=<Name>`. A primitive returned as a bare string, `'boolean'`, is always written as `Boolean`; to name it, write `{ type: 'boolean', name: 'Flag' }` in the decorator or `boolean as Flag` in the tag, and both write `Flag: {type: boolean}`. An enum or a union in a nullable or a list is a schema of its own, under the name it declares, and the nullable or the list references it under the name above: `{ nullable: { enum: ['AVAILABLE', 'SOLD'], name: 'Status' } }` and `enum:AVAILABLE|SOLD? as Status` both write `Status` and `StatusOrNull: {ref: Status, nullable: true}`. In the tag, that `as` names the enum or the union, never the nullable or the list around it. A scalar in a nullable or a list takes no name of its own: the name goes on the nullable or the list, and in the tag `as` names them.
610
+
611
+ A scalar is a custom one, `DateTime`, or one of GraphQL's built-in names, `ID`, `String`, `Int`, `Float` and `Boolean`, all written as `type: scalar` with that `name`. A built-in scalar declares the exact GraphQL type the call sends or reads: `{ scalar: 'ID' }` writes `ID: {type: scalar, name: ID}`, which accepts the provider's `ID` and breaks on its `String`, while the primitive `'string'` accepts both.
612
+
613
+ Several handlers can call the same query or mutation of one provider and read different fields of it, or pass different arguments. They are joined into one field of the contract, whose `returns` and `arguments` list every distinct schema the handlers declare, de-duplicated and sorted, with `~` for a handler that passes no arguments. A field with one schema is still written as a plain value. Two handlers reading `pet`, one as `PetName` with `PetArgs` and the other as `PetSummary` with no arguments, write:
614
+
615
+ ```yaml
616
+ pet:
617
+ arguments: [~, PetArgs]
618
+ returns: [PetName, PetSummary]
619
+ ```
620
+
621
+ Each entry is checked as if it were its own handler, so a provider that drops a field only one of them reads breaks on that field.
604
622
 
605
623
  A call that reads a GraphQL interface both on the interface and on the types that implement it, as `node(id: $id) { id ... on User { name } ... on Pet { species } }`, returns a schema with a `union`: its fields are the ones read on the interface, and `union` maps each type read with `... on` to the schema the call reads from it. `@BidirektSchema({ union: { User: UserName, Pet: PetSpecies } })` on a class `Node` with `@BidirektField() id`, or `@bidirekt schema union={User: UserName, Pet: PetSpecies}` above `interface Node` with a `@bidirekt field` on `id`, writes `Node` as `type: union`, with `id` in its `properties` and `User` and `Pet` in its `members`. A member's schema holds only the fields read on its own type: a member class that extends `Node` would repeat `id`. A schema with a `union` and no field writes only the `members`, a named union like `{ union: {...}, name }`. `union=` goes above a class, an interface or an object type, never above an enum.
606
624
 
@@ -617,7 +635,9 @@ A call that reads a GraphQL interface both on the interface and on the types tha
617
635
 
618
636
  A `union` names each schema of the field's union once, by one key, and nothing else; a tag names each member by its name in the contract, never a list or a map. It applies to the union of the field, of its items or of its values (`Array<Card | Pix>`), and `null` and `undefined` in the type still make them `nullable` or `optional`.
619
637
 
620
- In a GraphQL contract, `@BidirektGraphqlField` takes the place of `@BidirektField` on a field that needs GraphQL's own options, and `@bidirekt graphql field` that of `@bidirekt field`. They take the options above, plus `scalar: 'DateTime'`, a custom scalar that replaces the field's type and is written as `type: scalar, name: DateTime`, and `arguments: ReviewsArgs`, the schema of the arguments the call passes to the field, as `first` in `reviews(first: 10)`. In a tag, `scalar=DateTime` and `arguments=ReviewsArgs`. A field takes one of the two, never both.
638
+ In a GraphQL contract, `@BidirektGraphqlField` takes the place of `@BidirektField` on a field that needs GraphQL's own options, and `@bidirekt graphql field` that of `@bidirekt field`. They take the options above, plus `scalar: 'DateTime'`, a scalar that replaces the field's type and is written as `type: scalar, name: DateTime`, a custom one or a built-in `ID`, `String`, `Int`, `Float` or `Boolean`, and `arguments: ReviewsArgs`, the schema of the arguments the call passes to the field, as `first` in `reviews(first: 10)`. In a tag, `scalar=DateTime` and `arguments=ReviewsArgs`. A field takes one of the two, never both.
639
+
640
+ A call that reads the type name declares a field `__typename` with the names it reads as a string literal type, `__typename: 'Pet'` or `__typename: 'Pet' | 'Toy'`, with `@BidirektField` or `@bidirekt field`. It is written as `type: enum` with `members: ["Pet", "Toy"]`, and breaks when the provider renames a type the call reads.
621
641
 
622
642
  ### Types
623
643
 
@@ -647,6 +667,7 @@ A declared `type` is the whole type of the field, whatever TypeScript says: a pr
647
667
  - A schema is named after its class, interface or object type; `name` gives it another name in the contract. An anonymous class (`export default class`) needs a `name`.
648
668
  - Every schema is written, even one no handler references. Two schemas with the same name in the contract stop `generate`; give one of them a `name`.
649
669
  - A schema without a field or a `union` stops `generate`, and so does `@bidirekt schema` above an object type that is only an index signature: that is a map, used as a field's type.
670
+ - In a GraphQL contract, `graphqlType` names the GraphQL type a schema stands for, when the call depends on it, as the type of a variable does: `@BidirektSchema({ graphqlType: 'Pet' })`, or `graphqlType=Pet` in `@bidirekt schema` above a class, an interface, an object type or a string enum, writes `name: Pet` on the schema, and the call then breaks when the provider renames that type. Without it, a type renamed with the same shape breaks nothing.
650
671
  - A string enum used by a field is written as a schema named after it. `@bidirekt schema` above the enum gives it another name with `name=`, and writes it even when no field uses it, so tags can reference it (`@bidirekt response 200 PetStatus`). An enum without string members can't be a schema, and `generate` warns.
651
672
  - A schema class takes the annotated fields of its parent classes, whether or not they are schemas; a schema interface takes those of the interfaces it extends, and of all its blocks. A parent `generate` can't read, like a mixin or a utility type (`Omit<Pet, 'secret'>`), stops it: declare the fields in the schema.
652
673
 
@@ -1,6 +1,6 @@
1
1
  export function blockToReferences(block) {
2
- return block.operations.flatMap((operation) => [operation.arguments, operation.returns].flatMap((use) => {
3
- if (use === undefined) {
2
+ return block.operations.flatMap((operation) => [...operation.arguments, ...operation.returns].flatMap((use) => {
3
+ if (use === null) {
4
4
  return [];
5
5
  }
6
6
  return [{ schema: use.schema, location: use.location }];
@@ -16,7 +16,7 @@ export function sideBlocksToMerged(sideBlocks) {
16
16
  block.graph = graphsToMerged(blocks.flatMap(({ graph }) => graph ?? []), addConflict);
17
17
  }
18
18
  else {
19
- block.operations = operationsToMerged(blocks.flatMap(({ operations }) => operations), provider, addConflict);
19
+ block.operations = operationsToMerged(blocks.flatMap(({ operations }) => operations));
20
20
  }
21
21
  return { block, errors: [...errors.values()] };
22
22
  }
@@ -33,44 +33,15 @@ function graphsToMerged(graphs, addConflict) {
33
33
  }
34
34
  return first;
35
35
  }
36
- function operationsToMerged(operations, provider, addConflict) {
37
- const merged = [];
38
- for (const group of Map.groupBy(operations, operationToKey).values()) {
39
- const [first, ...others] = group;
40
- const operation = `${first.kind} ${first.name} consumed from "${provider}"`;
41
- for (const other of others) {
42
- const conflicts = [
43
- usesToConflict('arguments', first, other, operation),
44
- usesToConflict('returns', first, other, operation),
45
- ];
46
- for (const conflict of conflicts) {
47
- if (conflict !== undefined) {
48
- addConflict(conflict);
49
- }
50
- }
51
- }
52
- merged.push(first);
53
- }
54
- return merged;
36
+ function operationsToMerged(operations) {
37
+ return [...Map.groupBy(operations, operationToKey).values()].map((group) => ({
38
+ ...group[0],
39
+ arguments: usesToDistinct(group.flatMap((operation) => operation.arguments)),
40
+ returns: usesToDistinct(group.flatMap(({ returns }) => returns)),
41
+ }));
55
42
  }
56
- function usesToConflict(use, first, other, operation) {
57
- const firstUse = first[use];
58
- const otherUse = other[use];
59
- if (firstUse?.schema === otherUse?.schema) {
60
- return undefined;
61
- }
62
- if (firstUse === undefined || otherUse === undefined) {
63
- return {
64
- message: `${use} of ${operation} is declared in one handler and not in another: declare the same ${use} in every handler`,
65
- first: firstUse?.location ?? first.location,
66
- other: otherUse?.location ?? other.location,
67
- };
68
- }
69
- return {
70
- message: `${use} of ${operation} is declared as ${firstUse.schema} and ${otherUse.schema}: declare the same ${use} in every handler`,
71
- first: firstUse.location,
72
- other: otherUse.location,
73
- };
43
+ function usesToDistinct(uses) {
44
+ return [...Map.groupBy(uses, (use) => use?.schema).values()].map(([first]) => first);
74
45
  }
75
46
  function operationToKey(operation) {
76
47
  return JSON.stringify([operation.kind, operation.name]);
@@ -27,6 +27,7 @@ const consumerOptions = [
27
27
  const listKeys = ['list', 'nullable', 'nullableItems', 'name'];
28
28
  const nullableKeys = ['nullable', 'name'];
29
29
  const scalarKeys = ['scalar', 'name'];
30
+ const primitiveKeys = ['type', 'name'];
30
31
  const enumKeys = ['enum', 'name'];
31
32
  const unionKeys = ['union', 'name'];
32
33
  const wrapperPlaces = {
@@ -106,12 +107,10 @@ export function consumedToRead({ provider, kind, name, arguments: argumentsUse,
106
107
  const operation = {
107
108
  kind,
108
109
  name,
109
- returns: { schema, location: returnsLocation },
110
+ arguments: [argumentsUse ?? null],
111
+ returns: [{ schema, location: returnsLocation }],
110
112
  location,
111
113
  };
112
- if (argumentsUse !== undefined) {
113
- operation.arguments = argumentsUse;
114
- }
115
114
  read.blocks.push({ provider, block: { operations: [operation] } });
116
115
  }
117
116
  function optionsToOperation(options, what, call) {
@@ -199,7 +198,10 @@ function expressionToReturns(expression, context) {
199
198
  return optionsToNullable(options, expression, context);
200
199
  }
201
200
  if (options.has('scalar') && hasOnlyKeys(options, scalarKeys)) {
202
- return optionsToScalarReturns(options, expression);
201
+ return optionsToNamedTypeReturns(options, expression, optionsToScalar);
202
+ }
203
+ if (options.has('type') && hasOnlyKeys(options, primitiveKeys)) {
204
+ return optionsToNamedTypeReturns(options, expression, optionsToPrimitive);
203
205
  }
204
206
  }
205
207
  const type = expressionToReturnedType(expression, context);
@@ -259,8 +261,8 @@ function optionsToNullable(options, expression, context) {
259
261
  }
260
262
  return returns;
261
263
  }
262
- function optionsToScalarReturns(options, expression) {
263
- const type = optionsToScalar(options, expression);
264
+ function optionsToNamedTypeReturns(options, expression, readType) {
265
+ const type = readType(options, expression);
264
266
  if (isDiagnostic(type)) {
265
267
  return type;
266
268
  }
@@ -274,6 +276,13 @@ function optionsToScalarReturns(options, expression) {
274
276
  }
275
277
  return returns;
276
278
  }
279
+ function optionsToPrimitive(options, expression) {
280
+ const written = options.get('type');
281
+ if (written === undefined || !ts.isStringLiteralLike(written)) {
282
+ return unreadableReturns(expression);
283
+ }
284
+ return textToReturnedPrimitive(written.text) ?? unreadableReturns(expression);
285
+ }
277
286
  function expressionToReturnedType(expression, context, wrapper) {
278
287
  if (ts.isIdentifier(expression) ||
279
288
  ts.isPropertyAccessExpression(expression)) {
@@ -395,7 +404,7 @@ function hasOnlyKeys(options, keys) {
395
404
  }
396
405
  function unreadableReturns(expression) {
397
406
  return {
398
- message: `cannot read "${expression.getText()}" as returns: write a @BidirektSchema class, a primitive such as 'boolean', [Schema], { list: Schema }, { nullable: Schema }, { scalar: '<name>' }, { enum: [...], name: '<name>' } or { union: {...}, name: '<name>' }`,
407
+ message: `cannot read "${expression.getText()}" as returns: write a @BidirektSchema class, a primitive such as 'boolean', { type: '<primitive>', name: '<name>' }, [Schema], { list: Schema }, { nullable: Schema }, { scalar: '<name>' }, { enum: [...], name: '<name>' } or { union: {...}, name: '<name>' }`,
399
408
  location: nodeToLocation(expression),
400
409
  };
401
410
  }
@@ -6,7 +6,7 @@ import { nodeToLocation } from "./location.js";
6
6
  import { builtDeclarationToDiagnostic, fieldDecoratorHints, isLibrarySymbol, isObjectDeclaration, javaScriptTagHints, memberToOwner, nodeToSymbol, symbolToClass, tagHints, unreadClassToDiagnostic, } from "./schema-context.js";
7
7
  import { typeTextToSchemaNode, typeTextUsage, } from "./type-text-to-schema-node.js";
8
8
  import { typeNodeToDeclaredUnion, typeNodeToFlags, typeNodeToShapedLeaf, typeNodeToTranslatedType, } from "./type-to-schema-node.js";
9
- const schemaOptionKeys = ['name', 'union'];
9
+ const schemaOptionKeys = ['name', 'union', 'graphqlType'];
10
10
  const fieldOptionKeys = [
11
11
  'name',
12
12
  'description',
@@ -62,6 +62,7 @@ export function sdkReferencesToSchemas(references, tags, context, protocols) {
62
62
  }
63
63
  const unreadOptions = new Set();
64
64
  const unionOptions = new Map();
65
+ const graphqlTypes = new Map(tags.graphqlTypes);
65
66
  for (const [declaration, call] of schemaDecorators) {
66
67
  if (tags.schemas.has(declaration)) {
67
68
  errors.add({
@@ -79,6 +80,9 @@ export function sdkReferencesToSchemas(references, tags, context, protocols) {
79
80
  else {
80
81
  name = declared.name;
81
82
  unionOptions.set(declaration, declared.union);
83
+ if (declared.graphqlType !== undefined) {
84
+ graphqlTypes.set(declaration, declared.graphqlType);
85
+ }
82
86
  }
83
87
  if (name !== undefined) {
84
88
  context.schemaDeclarations.set(declaration, name);
@@ -136,11 +140,16 @@ export function sdkReferencesToSchemas(references, tags, context, protocols) {
136
140
  if (selfMember !== undefined) {
137
141
  errors.add(selfMember);
138
142
  }
139
- schemas.push({
143
+ const schema = {
140
144
  name,
141
145
  node: propertiesToSchemaNode(properties, union),
142
146
  location: nodeToLocation(declaration.name ?? declaration),
143
- });
147
+ };
148
+ const graphqlType = graphqlTypes.get(declaration);
149
+ if (graphqlType !== undefined) {
150
+ schema.graphqlType = graphqlType;
151
+ }
152
+ schemas.push(schema);
144
153
  }
145
154
  return {
146
155
  schemas: [...schemas, ...context.namedSchemas.values()],
@@ -248,6 +257,10 @@ function schemaClassToOptions(declaration, call) {
248
257
  if (isDiagnostic(name)) {
249
258
  return name;
250
259
  }
260
+ const graphqlType = literalOptionToName(options, 'graphqlType');
261
+ if (isDiagnostic(graphqlType)) {
262
+ return graphqlType;
263
+ }
251
264
  const resolved = name ?? declaration.name?.text;
252
265
  if (resolved === undefined) {
253
266
  return {
@@ -255,7 +268,7 @@ function schemaClassToOptions(declaration, call) {
255
268
  location: nodeToLocation(declaration),
256
269
  };
257
270
  }
258
- return { name: resolved, union: options.get('union') };
271
+ return { name: resolved, union: options.get('union'), graphqlType };
259
272
  }
260
273
  function declarationToFields(declaration, reading, visited = new Set()) {
261
274
  const fields = [];
@@ -18,14 +18,15 @@ const optionUsages = {
18
18
  };
19
19
  const fieldKeys = Object.keys(optionUsages);
20
20
  export const blockFieldKeys = fieldKeys.filter((key) => key !== 'name');
21
- const schemaKeys = ['name', 'union'];
22
- const enumSchemaKeys = ['name'];
21
+ const schemaKeys = ['name', 'union', 'graphqlType'];
22
+ const enumSchemaKeys = ['name', 'graphqlType'];
23
23
  const unionPattern = /^\{([^{}]*)\}$/;
24
24
  const unionMemberPattern = /^([^\s:,]+)\s*:\s*([^\s:,]+)$/;
25
25
  export function taggedCommentsToSchemaTags(comments, context, protocols) {
26
26
  const read = {
27
27
  schemas: new Set(),
28
28
  unions: new Map(),
29
+ graphqlTypes: new Map(),
29
30
  fields: new Map(),
30
31
  malformedFields: new Set(),
31
32
  errors: [],
@@ -104,7 +105,7 @@ function schemaTagToName(tag, element, context, read, taggedSchemas, hasUnknownT
104
105
  return;
105
106
  }
106
107
  if (ts.isEnumDeclaration(element)) {
107
- enumTagToSchema(tag, element, options.name, context, read, taggedSchemas);
108
+ enumTagToSchema(tag, element, options, context, read, taggedSchemas);
108
109
  return;
109
110
  }
110
111
  const name = options.name ?? element.name?.text;
@@ -116,6 +117,9 @@ function schemaTagToName(tag, element, context, read, taggedSchemas, hasUnknownT
116
117
  return;
117
118
  }
118
119
  context.schemaDeclarations.set(element, name);
120
+ if (options.graphqlType !== undefined) {
121
+ read.graphqlTypes.set(element, options.graphqlType);
122
+ }
119
123
  if (options.declared?.type === 'union') {
120
124
  read.unions.set(element, {
121
125
  members: options.declared.members,
@@ -129,7 +133,7 @@ function elementToSchemaKeys(element) {
129
133
  }
130
134
  return schemaKeys;
131
135
  }
132
- function enumTagToSchema(tag, element, declared, context, read, taggedSchemas) {
136
+ function enumTagToSchema(tag, element, { name, graphqlType }, context, read, taggedSchemas) {
133
137
  const symbol = context.checker.getSymbolAtLocation(element.name);
134
138
  if (symbol === undefined) {
135
139
  return;
@@ -142,7 +146,7 @@ function enumTagToSchema(tag, element, declared, context, read, taggedSchemas) {
142
146
  return;
143
147
  }
144
148
  taggedSchemas.add(symbol);
145
- const schema = enumToNamedSchema(symbol, declared ?? symbol.name, context);
149
+ const schema = enumToNamedSchema(symbol, name ?? symbol.name, context);
146
150
  if (isDiagnostic(schema)) {
147
151
  read.errors.push({ ...schema, location: tag.location });
148
152
  }
@@ -152,6 +156,9 @@ function enumTagToSchema(tag, element, declared, context, read, taggedSchemas) {
152
156
  location: tag.location,
153
157
  });
154
158
  }
159
+ else if (graphqlType !== undefined) {
160
+ schema.graphqlType = graphqlType;
161
+ }
155
162
  }
156
163
  // An unknown tag can be the handler of its comment, whose schema and field tags are then the handler's.
157
164
  function warnMisplaced(read, hasUnknownTag, message, tag) {
@@ -261,11 +268,12 @@ export function argumentsToOptions(tagArguments, tag, keys, protocols = []) {
261
268
  options[key] = value === 'true';
262
269
  break;
263
270
  }
264
- case 'name': {
271
+ case 'name':
272
+ case 'graphqlType': {
265
273
  if (value === '') {
266
274
  return usage;
267
275
  }
268
- options.name = value;
276
+ options[key] = value;
269
277
  break;
270
278
  }
271
279
  case 'description': {
@@ -47,7 +47,11 @@ function schemasToYaml(schemas) {
47
47
  const named = new YAMLMap();
48
48
  const sorted = [...schemas].sort((a, b) => compareBytes(a.name, b.name));
49
49
  for (const schema of sorted) {
50
- named.add(new Pair(schema.name, nodeToYaml(schema.node, schema.vocabulary)));
50
+ const fields = nodeToYaml(schema.node, schema.vocabulary);
51
+ if (schema.graphqlType !== undefined) {
52
+ fields.items.splice(1, 0, new Pair('name', schema.graphqlType));
53
+ }
54
+ named.add(new Pair(schema.name, fields));
51
55
  }
52
56
  return named;
53
57
  }
@@ -1,4 +1,4 @@
1
- import { Pair, YAMLMap } from 'yaml';
1
+ import { Pair, Scalar, YAMLMap, YAMLSeq } from 'yaml';
2
2
  import { compareBytes } from "../../contract-to-yaml.js";
3
3
  const operationKinds = ['query', 'mutation'];
4
4
  export function blockToYaml(block) {
@@ -23,9 +23,24 @@ export function blockToYaml(block) {
23
23
  }
24
24
  function operationToYaml(operation) {
25
25
  const field = new YAMLMap();
26
- if (operation.arguments !== undefined) {
27
- field.add(new Pair('arguments', operation.arguments.schema));
26
+ if (operation.arguments.some((use) => use !== null)) {
27
+ field.add(new Pair('arguments', usesToYaml(operation.arguments)));
28
28
  }
29
- field.add(new Pair('returns', operation.returns.schema));
29
+ field.add(new Pair('returns', usesToYaml(operation.returns)));
30
30
  return field;
31
31
  }
32
+ function usesToYaml(uses) {
33
+ const schemas = uses
34
+ .flatMap((use) => use?.schema ?? [])
35
+ .sort(compareBytes);
36
+ if (uses.includes(null)) {
37
+ schemas.unshift(null);
38
+ }
39
+ if (schemas.length === 1) {
40
+ return new Scalar(schemas[0]);
41
+ }
42
+ const list = new YAMLSeq();
43
+ list.flow = true;
44
+ list.items = schemas.map((schema) => new Scalar(schema));
45
+ return list;
46
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bidirekt/typescript-sdk-cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "prepublishOnly": "npm run build"
26
26
  },
27
27
  "dependencies": {
28
- "@bidirekt/typescript-sdk": "0.3.0",
28
+ "@bidirekt/typescript-sdk": "0.5.0",
29
29
  "typescript": "~6.0.3",
30
30
  "yaml": "^2.9.1"
31
31
  }