@bidirekt/typescript-sdk-cli 0.2.0 → 0.4.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.
Files changed (36) hide show
  1. package/README.md +77 -37
  2. package/dist/command.js +14 -13
  3. package/dist/model/contract.js +7 -1
  4. package/dist/model/declarations-to-contract.js +97 -37
  5. package/dist/model/protocols/graphql/block-to-references.js +8 -0
  6. package/dist/model/protocols/graphql/blocks-to-merged.js +77 -0
  7. package/dist/model/protocols/graphql/contract.js +1 -0
  8. package/dist/model/protocols/graphql/field-extra.js +46 -0
  9. package/dist/model/protocols/graphql/returns-to-schema.js +77 -0
  10. package/dist/model/protocols/rest/contract.js +1 -0
  11. package/dist/model/{resources-to-merged.js → protocols/rest/resources-to-merged.js} +15 -10
  12. package/dist/model/protocols/rest/resources-to-references.js +10 -0
  13. package/dist/protocols.js +49 -0
  14. package/dist/reader/comment-tags.js +77 -37
  15. package/dist/reader/literal-options.js +8 -2
  16. package/dist/reader/program.js +1 -1
  17. package/dist/reader/project-to-contract.js +51 -23
  18. package/dist/reader/protocols/graphql/decorators-to-blocks.js +412 -0
  19. package/dist/reader/protocols/graphql/protocol-input-to-blocks.js +11 -0
  20. package/dist/reader/protocols/graphql/tags-to-blocks.js +239 -0
  21. package/dist/reader/{handler-methods.js → protocols/rest/handler-methods.js} +36 -26
  22. package/dist/reader/protocols/rest/protocol-input-to-resources.js +11 -0
  23. package/dist/reader/protocols/rest/tag-handlers.js +152 -0
  24. package/dist/reader/schema-classes.js +191 -29
  25. package/dist/reader/schema-context.js +10 -5
  26. package/dist/reader/sdk-references.js +149 -39
  27. package/dist/reader/tag-handlers.js +36 -146
  28. package/dist/reader/tag-schemas.js +82 -40
  29. package/dist/reader/type-text-to-schema-node.js +4 -1
  30. package/dist/reader/type-to-schema-node.js +60 -10
  31. package/dist/writer/contract-to-yaml.js +38 -59
  32. package/dist/writer/protocols/graphql/block-to-yaml.js +31 -0
  33. package/dist/writer/protocols/graphql/field-extra-to-yaml.js +13 -0
  34. package/dist/writer/protocols/rest/resources-to-yaml.js +36 -0
  35. package/package.json +2 -2
  36. /package/dist/model/{schema-names.js → protocols/rest/schema-names.js} +0 -0
@@ -0,0 +1,46 @@
1
+ export const fieldOptions = ['scalar', 'arguments'];
2
+ export const primitiveNames = new Map([
3
+ ['Int', 'integer'],
4
+ ['Float', 'float'],
5
+ ['Boolean', 'boolean'],
6
+ ['String', 'string'],
7
+ ['ID', 'string'],
8
+ ]);
9
+ export function scalarToNode(scalar) {
10
+ return withExtra({ type: 'string' }, { scalar });
11
+ }
12
+ export function nodeToScalar(node) {
13
+ return nodeToExtraText(node, 'scalar');
14
+ }
15
+ export function nodeToArguments(node) {
16
+ return nodeToExtraText(node, 'arguments');
17
+ }
18
+ export function fieldOptionsToLeaf(options) {
19
+ if (!Object.hasOwn(options, 'scalar')) {
20
+ return undefined;
21
+ }
22
+ return scalarToNode(options.scalar);
23
+ }
24
+ export function fieldOptionsToNode(options, node) {
25
+ if (!Object.hasOwn(options, 'arguments')) {
26
+ return node;
27
+ }
28
+ return withExtra(node, { arguments: options.arguments });
29
+ }
30
+ export function nodeToArgumentsSchemas(node) {
31
+ const schema = nodeToArguments(node);
32
+ if (schema === undefined) {
33
+ return [];
34
+ }
35
+ return [schema];
36
+ }
37
+ function nodeToExtraText(node, key) {
38
+ const text = node.extra?.[key];
39
+ if (typeof text !== 'string') {
40
+ return undefined;
41
+ }
42
+ return text;
43
+ }
44
+ function withExtra(node, extra) {
45
+ return { ...node, extra: { ...node.extra, ...extra } };
46
+ }
@@ -0,0 +1,77 @@
1
+ import { scalarToNode } from "./field-extra.js";
2
+ export function returnsToSchema(returns, location) {
3
+ const { type } = returns;
4
+ const declared = typeToDeclaredSchemas(type, location);
5
+ if (returns.form === 'type' && type.kind === 'schema') {
6
+ return { schema: type.schema, derived: declared };
7
+ }
8
+ const derived = {
9
+ name: returns.name ?? returnsToDefaultName(returns),
10
+ node: returnsToNode(returns),
11
+ location,
12
+ derived: true,
13
+ };
14
+ return { schema: derived.name, derived: [...declared, derived] };
15
+ }
16
+ function typeToDeclaredSchemas(type, location) {
17
+ if (type.kind !== 'schema' || type.declared === undefined) {
18
+ return [];
19
+ }
20
+ return [{ name: type.schema, node: type.declared, location, derived: true }];
21
+ }
22
+ function returnsToDefaultName(returns) {
23
+ const name = typeToName(returns.type);
24
+ switch (returns.form) {
25
+ case 'type':
26
+ return name;
27
+ case 'nullable':
28
+ return orNull(name, true);
29
+ case 'list':
30
+ return orNull(`${orNull(name, returns.nullableItems)}List`, returns.nullable);
31
+ }
32
+ }
33
+ function returnsToNode(returns) {
34
+ const node = typeToNode(returns.type);
35
+ switch (returns.form) {
36
+ case 'type':
37
+ return node;
38
+ case 'nullable':
39
+ return { ...node, nullable: true };
40
+ case 'list': {
41
+ const list = { type: 'array', items: node };
42
+ if (returns.nullableItems) {
43
+ list.items = { ...node, nullable: true };
44
+ }
45
+ if (returns.nullable) {
46
+ list.nullable = true;
47
+ }
48
+ return list;
49
+ }
50
+ }
51
+ }
52
+ function typeToName(type) {
53
+ switch (type.kind) {
54
+ case 'schema':
55
+ return type.schema;
56
+ case 'primitive':
57
+ return `${type.type.charAt(0).toUpperCase()}${type.type.slice(1)}`;
58
+ case 'scalar':
59
+ return type.scalar;
60
+ }
61
+ }
62
+ function typeToNode(type) {
63
+ switch (type.kind) {
64
+ case 'schema':
65
+ return { type: 'ref', schema: type.schema };
66
+ case 'primitive':
67
+ return { type: type.type };
68
+ case 'scalar':
69
+ return scalarToNode(type.scalar);
70
+ }
71
+ }
72
+ function orNull(name, nullable) {
73
+ if (!nullable) {
74
+ return name;
75
+ }
76
+ return `${name}OrNull`;
77
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,15 @@
1
+ export function sideBlocksToMerged(sideBlocks) {
2
+ const [{ provider }] = sideBlocks;
3
+ const resources = sideBlocks.flatMap(({ block }) => block);
4
+ if (provider === undefined) {
5
+ return providedToMerged(resources);
6
+ }
7
+ return consumedToMerged(resources, provider);
8
+ }
1
9
  export function providedToMerged(provides) {
2
10
  const resources = [];
3
11
  const errors = [];
4
- for (const group of Map.groupBy(provides, providedToKey).values()) {
12
+ for (const group of Map.groupBy(provides, resourceToKey).values()) {
5
13
  const [first] = group;
6
14
  resources.push(first);
7
15
  if (group.length === 1) {
@@ -12,9 +20,9 @@ export function providedToMerged(provides) {
12
20
  errors.push({ message, location });
13
21
  }
14
22
  }
15
- return { resources, errors };
23
+ return { block: resources, errors };
16
24
  }
17
- export function consumedToMerged(consumes) {
25
+ export function consumedToMerged(consumes, provider) {
18
26
  const resources = [];
19
27
  const errors = new Map();
20
28
  const addError = (message, location) => {
@@ -23,9 +31,9 @@ export function consumedToMerged(consumes) {
23
31
  location,
24
32
  });
25
33
  };
26
- for (const group of Map.groupBy(consumes, consumedToKey).values()) {
34
+ for (const group of Map.groupBy(consumes, resourceToKey).values()) {
27
35
  const [first, ...others] = group;
28
- const resource = `"${first.method} ${first.path}" consumed from "${first.provider}"`;
36
+ const resource = `"${first.method} ${first.path}" consumed from "${provider}"`;
29
37
  for (const other of others) {
30
38
  const conflict = requestsToConflict(first, other, resource);
31
39
  if (conflict !== undefined) {
@@ -47,7 +55,7 @@ export function consumedToMerged(consumes) {
47
55
  }
48
56
  resources.push({ ...first, responses: [...responses.values()] });
49
57
  }
50
- return { resources, errors: [...errors.values()] };
58
+ return { block: resources, errors: [...errors.values()] };
51
59
  }
52
60
  function requestsToConflict(first, other, resource) {
53
61
  if (first.request === undefined && other.request === undefined) {
@@ -78,9 +86,6 @@ function schemaToText(schema) {
78
86
  }
79
87
  return `"${schema}"`;
80
88
  }
81
- function providedToKey(resource) {
89
+ function resourceToKey(resource) {
82
90
  return JSON.stringify([resource.method, resource.path]);
83
91
  }
84
- function consumedToKey(resource) {
85
- return JSON.stringify([resource.provider, resource.method, resource.path]);
86
- }
@@ -0,0 +1,10 @@
1
+ export function resourcesToReferences(resources) {
2
+ return resources
3
+ .flatMap((resource) => [resource.request, ...resource.responses])
4
+ .flatMap((body) => {
5
+ if (body === undefined || body.schema === null) {
6
+ return [];
7
+ }
8
+ return [{ schema: body.schema, location: body.location }];
9
+ });
10
+ }
@@ -0,0 +1,49 @@
1
+ import { blockToReferences } from "./model/protocols/graphql/block-to-references.js";
2
+ import { sideBlocksToMerged as graphqlSideBlocksToMerged } from "./model/protocols/graphql/blocks-to-merged.js";
3
+ import { fieldOptions, fieldOptionsToLeaf, fieldOptionsToNode, nodeToArgumentsSchemas, primitiveNames, } from "./model/protocols/graphql/field-extra.js";
4
+ import { resourcesToReferences } from "./model/protocols/rest/resources-to-references.js";
5
+ import { sideBlocksToMerged } from "./model/protocols/rest/resources-to-merged.js";
6
+ import { graphqlDecoratorTargets } from "./reader/protocols/graphql/decorators-to-blocks.js";
7
+ import { protocolInputToBlocks } from "./reader/protocols/graphql/protocol-input-to-blocks.js";
8
+ import { restDecoratorTargets, restRenamedExports, } from "./reader/protocols/rest/handler-methods.js";
9
+ import { protocolInputToResources } from "./reader/protocols/rest/protocol-input-to-resources.js";
10
+ import { restRenamedTags } from "./reader/protocols/rest/tag-handlers.js";
11
+ import { blockToYaml } from "./writer/protocols/graphql/block-to-yaml.js";
12
+ import { fieldExtraToYaml } from "./writer/protocols/graphql/field-extra-to-yaml.js";
13
+ import { resourcesToYaml } from "./writer/protocols/rest/resources-to-yaml.js";
14
+ const restProtocol = {
15
+ name: 'rest',
16
+ exports: restDecoratorTargets,
17
+ renamedExports: restRenamedExports,
18
+ tagKeywords: ['request', 'response'],
19
+ renamedTags: restRenamedTags,
20
+ read: protocolInputToResources,
21
+ merge: sideBlocksToMerged,
22
+ references: resourcesToReferences,
23
+ isEmpty: (resources) => resources.length === 0,
24
+ toYaml: resourcesToYaml,
25
+ };
26
+ const graphqlProtocol = {
27
+ name: 'graphql',
28
+ exports: graphqlDecoratorTargets,
29
+ tagKeywords: ['arguments', 'returns', 'graph'],
30
+ read: protocolInputToBlocks,
31
+ merge: graphqlSideBlocksToMerged,
32
+ references: blockToReferences,
33
+ isEmpty: (block) => block.operations.length === 0 && block.graph === undefined,
34
+ toYaml: blockToYaml,
35
+ vocabulary: {
36
+ label: 'GraphQL',
37
+ fieldDecorator: 'BidirektGraphqlField',
38
+ fieldOptions,
39
+ primitiveNames,
40
+ toLeaf: fieldOptionsToLeaf,
41
+ toNode: fieldOptionsToNode,
42
+ toYaml: fieldExtraToYaml,
43
+ references: nodeToArgumentsSchemas,
44
+ },
45
+ };
46
+ export const defaultProtocols = [
47
+ restProtocol,
48
+ graphqlProtocol,
49
+ ];
@@ -3,30 +3,24 @@ import { namesToChoice } from "./literal-options.js";
3
3
  import { nodeToLocation } from "./location.js";
4
4
  import { programToUserFiles } from "./program.js";
5
5
  import { isObjectDeclaration, memberToOwner } from "./schema-context.js";
6
- import { isSdkExportName } from "./sdk-references.js";
6
+ import { protocolsToDecoratorTargets } from "./sdk-references.js";
7
7
  const tagName = 'bidirekt';
8
8
  const taggedCommentPattern = /\/\*\*(?:(?!\*\/)[\s\S])*?@bidirekt/i;
9
9
  const mentionPattern = /(?<![^\s*])(@bidirekt[^\s*]*)[ \t]*([^\s*]*)/gi;
10
10
  const argumentPattern = /description="[^"]*"(?=\s|$)|union=\{[^}]*\}\S*|\S+/g;
11
11
  const quotedValuePattern = /^"[^"]*"$/;
12
12
  const quotedDescriptionPattern = /^description="[^"]*"$/;
13
- const keywords = [
14
- 'provides',
15
- 'consumes',
16
- 'request',
17
- 'response',
18
- 'schema',
19
- 'field',
20
- ];
21
- const keywordList = namesToChoice(keywords);
22
- export function programToTaggedComments(projectProgram) {
13
+ const coreKeywords = ['schema', 'field'];
14
+ const vocabularyKeyword = 'field';
15
+ export function programToTaggedComments(projectProgram, protocols) {
23
16
  projectProgram.program.getTypeChecker();
17
+ const words = protocolsToTagWords(protocols);
24
18
  const read = { comments: [], errors: [], warnings: [] };
25
19
  for (const file of programToUserFiles(projectProgram)) {
26
20
  if (!taggedCommentPattern.test(file.text)) {
27
21
  continue;
28
22
  }
29
- const fileRead = fileToTaggedComments(file);
23
+ const fileRead = fileToTaggedComments(file, words);
30
24
  if (file.isDeclarationFile) {
31
25
  read.comments.push(...fileRead.comments.flatMap(typeDeclarationComment));
32
26
  continue;
@@ -37,7 +31,21 @@ export function programToTaggedComments(projectProgram) {
37
31
  }
38
32
  return read;
39
33
  }
40
- function fileToTaggedComments(file) {
34
+ function protocolsToTagWords(protocols) {
35
+ const owned = protocols.flatMap(({ name, tagKeywords }) => [name, ...tagKeywords].map((keyword) => [keyword, name]));
36
+ const keywords = [...owned.map(([keyword]) => keyword), ...coreKeywords];
37
+ return {
38
+ keywords,
39
+ keywordChoice: namesToChoice(keywords),
40
+ owners: new Map(owned),
41
+ renamed: new Map(protocols.flatMap(({ renamedTags }) => Object.entries(renamedTags ?? {}))),
42
+ vocabularies: new Set(protocols
43
+ .filter(({ vocabulary }) => vocabulary !== undefined)
44
+ .map(({ name }) => name)),
45
+ decorators: new Set(protocolsToDecoratorTargets(protocols).keys()),
46
+ };
47
+ }
48
+ function fileToTaggedComments(file, words) {
41
49
  const read = { comments: [], errors: [], warnings: [] };
42
50
  const attached = new Set();
43
51
  const comments = new Map();
@@ -56,7 +64,7 @@ function fileToTaggedComments(file) {
56
64
  if (ts.isJSDoc(child)) {
57
65
  if (!attached.has(child.pos)) {
58
66
  attached.add(child.pos);
59
- readComment(child, node, read);
67
+ readComment(child, node, read, words);
60
68
  }
61
69
  continue;
62
70
  }
@@ -75,7 +83,7 @@ function fileToTaggedComments(file) {
75
83
  }
76
84
  for (const range of comments.values()) {
77
85
  if (!attached.has(range.pos) && !isInside(jsxTexts, range.pos)) {
78
- warnUnreadComment(file, range, read);
86
+ warnUnreadComment(file, range, read, words);
79
87
  }
80
88
  }
81
89
  return read;
@@ -95,10 +103,16 @@ function isTypeDeclarationPart(element) {
95
103
  return isObjectDeclaration(owner) && !ts.isClassDeclaration(owner);
96
104
  }
97
105
  export function isHandlerTag(tag) {
98
- return tag.keyword === 'provides' || tag.keyword === 'consumes';
106
+ return tag.protocol !== undefined && tag.keyword === tag.protocol;
99
107
  }
100
108
  export function tagToText(tag) {
101
- return [`@${tagName}`, tag.keyword, ...tag.arguments].join(' ');
109
+ return [tagToLabel(tag), ...tag.arguments].join(' ');
110
+ }
111
+ export function tagToLabel(tag) {
112
+ if (tag.vocabulary === undefined) {
113
+ return `@${tagName} ${tag.keyword}`;
114
+ }
115
+ return `@${tagName} ${tag.vocabulary} ${tag.keyword}`;
102
116
  }
103
117
  export function argumentToOption(argument) {
104
118
  const separator = argument.indexOf('=');
@@ -112,11 +126,12 @@ export function argumentToOption(argument) {
112
126
  }
113
127
  return { key, value };
114
128
  }
115
- function readComment(comment, element, read) {
129
+ function readComment(comment, element, read, words) {
116
130
  const file = comment.getSourceFile();
117
131
  const fences = commentToFences(file, comment);
118
132
  const examples = [];
119
133
  const tags = [];
134
+ let hasUnknownTag = false;
120
135
  let exampleStart;
121
136
  for (const tag of comment.tags ?? []) {
122
137
  if (isInside(fences, tag.pos) || !startsItsLine(file, comment, tag.pos)) {
@@ -138,7 +153,7 @@ function readComment(comment, element, read) {
138
153
  continue;
139
154
  }
140
155
  const written = tagToWritten(tag);
141
- if (namesPackageOrDecorator(written)) {
156
+ if (namesPackageOrDecorator(written, words)) {
142
157
  continue;
143
158
  }
144
159
  if (name !== tagName || !isFollowedBySpace(tag)) {
@@ -149,21 +164,27 @@ function readComment(comment, element, read) {
149
164
  continue;
150
165
  }
151
166
  const location = nodeToLocation(tag);
152
- const words = textToArguments(tagToComment(tag));
153
- const [keyword, ...rest] = words;
154
- const known = keywords.find((candidate) => candidate === keyword);
155
- if (known !== undefined) {
156
- tags.push(argumentsToTag(known, rest, location));
167
+ const tagArguments = textToArguments(tagToComment(tag));
168
+ const [keyword, ...remaining] = tagArguments;
169
+ const [vocabularyField, ...fieldArguments] = remaining;
170
+ if (words.vocabularies.has(keyword) &&
171
+ vocabularyField === vocabularyKeyword) {
172
+ tags.push(argumentsToTag(vocabularyKeyword, { vocabulary: keyword }, fieldArguments, location));
173
+ }
174
+ else if (words.keywords.includes(keyword)) {
175
+ tags.push(argumentsToTag(keyword, keywordToOwner(keyword, words), remaining, location));
157
176
  }
158
- else if (words.length === 0) {
177
+ else if (tagArguments.length === 0) {
178
+ hasUnknownTag = true;
159
179
  read.errors.push({
160
- message: `"@${tagName}" needs a keyword: use ${keywordList}`,
180
+ message: `"@${tagName}" needs a keyword: use ${words.keywordChoice}`,
161
181
  location,
162
182
  });
163
183
  }
164
184
  else {
185
+ hasUnknownTag = true;
165
186
  read.errors.push({
166
- message: `unknown tag "@${tagName} ${keyword}": use ${keywordList}`,
187
+ message: unknownKeywordToMessage(keyword, words),
167
188
  location,
168
189
  });
169
190
  }
@@ -171,7 +192,7 @@ function readComment(comment, element, read) {
171
192
  if (exampleStart !== undefined) {
172
193
  examples.push({ start: exampleStart, end: comment.end });
173
194
  }
174
- warnSkippedTags(file, comment, fences, examples, read);
195
+ warnSkippedTags(file, comment, fences, examples, read, words);
175
196
  if (tags.length > 0) {
176
197
  const typedef = comment.tags?.find((tag) => ts.isJSDocTypedefTag(tag) || ts.isJSDocCallbackTag(tag));
177
198
  let target = element;
@@ -180,17 +201,24 @@ function readComment(comment, element, read) {
180
201
  !isOwnComment(comment, element)) {
181
202
  target = typedef;
182
203
  }
183
- read.comments.push({ element: target, tags });
204
+ read.comments.push({ element: target, tags, hasUnknownTag });
184
205
  }
185
206
  }
186
- function warnSkippedTags(file, comment, fences, examples, read) {
207
+ function unknownKeywordToMessage(keyword, words) {
208
+ const renamed = words.renamed.get(keyword);
209
+ if (renamed === undefined) {
210
+ return `unknown tag "@${tagName} ${keyword}": use ${words.keywordChoice}`;
211
+ }
212
+ return `unknown tag "@${tagName} ${keyword}": write "@${tagName} ${renamed}"`;
213
+ }
214
+ function warnSkippedTags(file, comment, fences, examples, read, words) {
187
215
  for (const mention of commentToMentions(file, comment)) {
188
216
  if (mention.written !== `@${tagName}` ||
189
217
  isInside(fences, mention.position)) {
190
218
  continue;
191
219
  }
192
220
  const atLineStart = startsItsLine(file, comment, mention.position);
193
- const isKeyword = keywords.some((keyword) => keyword === mention.next);
221
+ const isKeyword = words.keywords.includes(mention.next);
194
222
  const shown = [mention.written, mention.next].join(' ').trim();
195
223
  const { line } = file.getLineAndCharacterOfPosition(mention.position);
196
224
  const location = { file: file.fileName, line: line + 1 };
@@ -235,8 +263,20 @@ function startsItsLine(file, comment, position) {
235
263
  const lineStart = Math.max(file.text.lastIndexOf('\n', position - 1) + 1, comment.pos);
236
264
  return /^\s*(\/\*\*)?\s*\**\s*$/.test(file.text.slice(lineStart, position));
237
265
  }
238
- function argumentsToTag(keyword, tagArguments, location) {
239
- const tag = { keyword, arguments: tagArguments, location };
266
+ function keywordToOwner(keyword, words) {
267
+ const protocol = words.owners.get(keyword);
268
+ if (protocol === undefined) {
269
+ return {};
270
+ }
271
+ return { protocol };
272
+ }
273
+ function argumentsToTag(keyword, owner, tagArguments, location) {
274
+ const tag = {
275
+ keyword,
276
+ ...owner,
277
+ arguments: tagArguments,
278
+ location,
279
+ };
240
280
  if (tagArguments.some((argument) => argument.includes('"') && !quotedDescriptionPattern.test(argument))) {
241
281
  tag.error = {
242
282
  message: `cannot read "${tagToText(tag)}": remove the quotes, only description="<text>" takes them`,
@@ -256,9 +296,9 @@ function isFollowedBySpace(tag) {
256
296
  const next = tag.getSourceFile().text.charAt(tag.tagName.end);
257
297
  return next === '' || /[\s*]/.test(next);
258
298
  }
259
- function namesPackageOrDecorator(written) {
299
+ function namesPackageOrDecorator(written, words) {
260
300
  const [name] = written.slice(1).split(/[^\w$]/);
261
- return written.startsWith(`@${tagName}/`) || isSdkExportName(name);
301
+ return written.startsWith(`@${tagName}/`) || words.decorators.has(name);
262
302
  }
263
303
  function tagToWritten(tag) {
264
304
  const [written] = /^@[^\s*]+/.exec(tag.getSourceFile().text.slice(tag.pos)) ?? [`@${tag.tagName.text}`];
@@ -274,14 +314,14 @@ function textToArguments(text) {
274
314
  .replaceAll('*\\/', '*/')
275
315
  .match(argumentPattern) ?? []);
276
316
  }
277
- function warnUnreadComment(file, range, read) {
317
+ function warnUnreadComment(file, range, read, words) {
278
318
  if (!file.text.startsWith('/**', range.pos)) {
279
319
  return;
280
320
  }
281
321
  const fences = commentToFences(file, range);
282
322
  const tag = commentToMentions(file, range).find(({ position, written }) => startsItsLine(file, range, position) &&
283
323
  !isInside(fences, position) &&
284
- !namesPackageOrDecorator(written));
324
+ !namesPackageOrDecorator(written, words));
285
325
  if (tag === undefined) {
286
326
  return;
287
327
  }
@@ -10,7 +10,7 @@ export function propertyNameToText(name) {
10
10
  }
11
11
  return undefined;
12
12
  }
13
- export function expressionToLiteralOptions(expression, what, known, computedKeyToMessage) {
13
+ export function expressionToLiteralOptions(expression, what, known, computedKeyToMessage, unknownToHint) {
14
14
  const options = new Map();
15
15
  if (expression === undefined) {
16
16
  return options;
@@ -39,7 +39,7 @@ export function expressionToLiteralOptions(expression, what, known, computedKeyT
39
39
  }
40
40
  if (known !== undefined && !known.includes(name)) {
41
41
  return {
42
- message: `unknown option "${name}" in ${what}: write ${namesToChoice(known)}`,
42
+ message: `unknown option "${name}" in ${what}: write ${namesToChoice(known)}${hintToSuffix(unknownToHint?.(name))}`,
43
43
  location: nodeToLocation(property.name),
44
44
  };
45
45
  }
@@ -60,6 +60,12 @@ export function computedKeyToValue(key, checker) {
60
60
  }
61
61
  return undefined;
62
62
  }
63
+ export function hintToSuffix(hint) {
64
+ if (hint === undefined) {
65
+ return '';
66
+ }
67
+ return `; ${hint}`;
68
+ }
63
69
  export function namesToChoice(names) {
64
70
  if (names.length === 1) {
65
71
  return names[0];
@@ -1,6 +1,6 @@
1
1
  import { dirname, relative } from 'node:path';
2
2
  import ts from 'typescript';
3
- const sdkPackage = '@bidirekt/typescript-sdk';
3
+ export const sdkPackage = '@bidirekt/typescript-sdk';
4
4
  const forcedOptions = {
5
5
  noEmit: true,
6
6
  strictNullChecks: true,
@@ -1,14 +1,17 @@
1
1
  import { declarationsToContract } from "../model/declarations-to-contract.js";
2
2
  import { programToTaggedComments } from "./comment-tags.js";
3
- import { sdkReferencesToResources } from "./handler-methods.js";
4
3
  import { programToSyntaxErrors, projectToProgram } from "./program.js";
5
4
  import { sdkReferencesToSchemas } from "./schema-classes.js";
6
5
  import { programToSchemaContext } from "./schema-context.js";
7
6
  import { programToSdkReferences } from "./sdk-references.js";
8
- import { taggedCommentsToResources } from "./tag-handlers.js";
7
+ import { taggedCommentsToHandlerComments } from "./tag-handlers.js";
9
8
  import { taggedCommentsToSchemaTags } from "./tag-schemas.js";
10
- export function projectToContract(project, cwd) {
11
- const contract = { provides: [], consumes: [], schemas: [] };
9
+ export function projectToContract(project, cwd, protocols) {
10
+ const contract = {
11
+ provides: new Map(),
12
+ consumes: new Map(),
13
+ schemas: [],
14
+ };
12
15
  const projectProgram = projectToProgram(project);
13
16
  if ('message' in projectProgram) {
14
17
  return {
@@ -21,41 +24,66 @@ export function projectToContract(project, cwd) {
21
24
  if (syntaxErrors.length > 0) {
22
25
  return { contract, errors: syntaxErrors, warnings: [] };
23
26
  }
24
- const references = programToSdkReferences(projectProgram);
25
- const tagged = programToTaggedComments(projectProgram);
27
+ const references = programToSdkReferences(projectProgram, protocols);
28
+ const tagged = programToTaggedComments(projectProgram, protocols);
26
29
  const context = programToSchemaContext(projectProgram.program, cwd);
27
- const schemaTags = taggedCommentsToSchemaTags(tagged.comments, context);
28
- const schemas = sdkReferencesToSchemas(references, schemaTags, context);
29
- const resources = sdkReferencesToResources(references, context);
30
- const tagResources = taggedCommentsToResources(tagged.comments, references);
30
+ const schemaTags = taggedCommentsToSchemaTags(tagged.comments, context, protocols);
31
+ const schemas = sdkReferencesToSchemas(references, schemaTags, context, protocols);
32
+ const decorators = references.filter(isProtocolDecorator);
33
+ const handlers = taggedCommentsToHandlerComments(tagged.comments, decorators, protocols);
34
+ const reads = protocols.map((protocol) => ({
35
+ name: protocol.name,
36
+ vocabulary: protocol.vocabulary,
37
+ read: protocol.read({
38
+ decorators: decorators.filter((decorator) => decorator.protocol === protocol.name),
39
+ comments: handlers.comments.get(protocol.name) ?? [],
40
+ context,
41
+ }),
42
+ }));
31
43
  const merged = declarationsToContract({
32
- provides: [...resources.provides, ...tagResources.provides],
33
- consumes: [...resources.consumes, ...tagResources.consumes],
44
+ blocks: new Map(reads.map(({ name, read }) => [name, read.blocks])),
34
45
  schemas: [
35
46
  ...schemas.schemas,
36
- ...resources.schemas,
37
- ...tagResources.schemas,
47
+ ...reads.flatMap(({ vocabulary, read }) => read.derived.map((schema) => withVocabulary(schema, vocabulary))),
48
+ ...handlers.schemas,
38
49
  ],
39
- });
50
+ }, protocols);
40
51
  return {
41
52
  contract: merged.contract,
42
53
  errors: [
43
- ...new Set([...schemas.errors, ...resources.errors]),
54
+ ...referencesToDiagnostics(references, 'unregistered'),
55
+ ...referencesToDiagnostics(references, 'unexported'),
56
+ ...new Set([
57
+ ...schemas.errors,
58
+ ...reads.flatMap(({ read }) => read.errors),
59
+ ]),
44
60
  ...tagged.errors,
45
61
  ...schemaTags.errors,
46
- ...tagResources.errors,
62
+ ...handlers.errors,
47
63
  ...merged.errors,
48
64
  ],
49
65
  warnings: [
50
- ...references.flatMap((reference) => {
51
- if (reference.use !== 'misplaced') {
52
- return [];
53
- }
54
- return [{ message: reference.message, location: reference.location }];
55
- }),
66
+ ...referencesToDiagnostics(references, 'misplaced'),
56
67
  ...schemas.warnings,
57
68
  ...tagged.warnings,
58
69
  ...schemaTags.warnings,
59
70
  ],
60
71
  };
61
72
  }
73
+ function withVocabulary(schema, vocabulary) {
74
+ if (vocabulary === undefined) {
75
+ return schema;
76
+ }
77
+ return { ...schema, vocabulary };
78
+ }
79
+ function isProtocolDecorator(reference) {
80
+ return reference.use === 'decorator' && reference.protocol !== undefined;
81
+ }
82
+ function referencesToDiagnostics(references, use) {
83
+ return references.flatMap((reference) => {
84
+ if (reference.use === 'decorator' || reference.use !== use) {
85
+ return [];
86
+ }
87
+ return [{ message: reference.message, location: reference.location }];
88
+ });
89
+ }