@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
@@ -1,38 +1,41 @@
1
1
  import ts from 'typescript';
2
2
  import { nodeToLocation } from "./location.js";
3
- import { programToUserFiles } from "./program.js";
4
- const decoratorTargets = {
3
+ import { programToUserFiles, sdkPackage } from "./program.js";
4
+ export const fieldTarget = {
5
+ isTarget: (node) => ts.isPropertyDeclaration(node) && !isStatic(node),
6
+ description: 'a property',
7
+ };
8
+ const coreTargets = {
5
9
  BidirektSchema: {
6
10
  isTarget: ts.isClassDeclaration,
7
11
  description: 'a class declaration',
8
12
  },
9
- BidirektField: {
10
- isTarget: (node) => ts.isPropertyDeclaration(node) && !isStatic(node),
11
- description: 'a property',
12
- },
13
- BidirektProvider: {
14
- isTarget: ts.isMethodDeclaration,
15
- description: 'a method',
16
- },
17
- BidirektConsumer: {
18
- isTarget: ts.isMethodDeclaration,
19
- description: 'a method',
20
- },
13
+ BidirektField: fieldTarget,
21
14
  };
22
- export function isSdkExportName(name) {
23
- return Object.hasOwn(decoratorTargets, name);
15
+ export function protocolsToDecoratorTargets(protocols) {
16
+ return new Map([
17
+ ...Object.entries(coreTargets),
18
+ ...protocols.flatMap(({ name, exports }) => Object.entries(exports).map(([exported, target]) => [
19
+ exported,
20
+ { ...target, protocol: name },
21
+ ])),
22
+ ]);
24
23
  }
25
- export function programToSdkReferences(projectProgram) {
24
+ export function programToSdkReferences(projectProgram, protocols) {
25
+ const targets = protocolsToDecoratorTargets(protocols);
26
+ const renamed = new Map(protocols.flatMap(({ renamedExports }) => Object.entries(renamedExports ?? {})));
26
27
  const checker = projectProgram.program.getTypeChecker();
27
- const sdkExports = programToSdkExports(projectProgram, checker);
28
+ const sdk = programToSdkModule(projectProgram, checker);
28
29
  const found = [];
29
- if (sdkExports.size === 0) {
30
+ const unexported = [];
31
+ if (sdk === undefined) {
30
32
  return [];
31
33
  }
32
34
  const pending = programToUserFiles(projectProgram)
33
35
  .filter((file) => !file.isDeclarationFile)
34
36
  .reverse();
35
37
  for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
38
+ unexported.push(...nodeToUnexported(node, checker, sdk, renamed));
36
39
  if (ts.isImportDeclaration(node) ||
37
40
  ts.isImportEqualsDeclaration(node) ||
38
41
  ts.isExportDeclaration(node) ||
@@ -41,7 +44,7 @@ export function programToSdkReferences(projectProgram) {
41
44
  continue;
42
45
  }
43
46
  if (ts.isIdentifier(node)) {
44
- const name = identifierToSdkExportName(node, checker, sdkExports);
47
+ const name = identifierToSdkExportName(node, checker, sdk.functions);
45
48
  if (name !== undefined) {
46
49
  const expression = identifierToExpression(node);
47
50
  found.push({
@@ -58,7 +61,95 @@ export function programToSdkReferences(projectProgram) {
58
61
  pending.push(children[index]);
59
62
  }
60
63
  }
61
- return foundToSdkReferences(found);
64
+ return [...foundToSdkReferences(found, targets), ...unexported];
65
+ }
66
+ function nodeToUnexported(node, checker, sdk, renamed) {
67
+ const imported = nodeToImportedNames(node);
68
+ if (imported === undefined || !isSdkModule(imported.from, checker, sdk)) {
69
+ return [];
70
+ }
71
+ return imported.names
72
+ .filter(({ name }) => !sdk.names.has(name.text))
73
+ .map(({ name, typeOnly }) => ({
74
+ use: 'unexported',
75
+ name: name.text,
76
+ message: unexportedToMessage(name.text, typeOnly, renamed),
77
+ location: nodeToLocation(name),
78
+ }));
79
+ }
80
+ function unexportedToMessage(name, typeOnly, renamed) {
81
+ const current = renamed.get(name);
82
+ if (current !== undefined) {
83
+ return `${name} is not exported by ${sdkPackage}: it is now ${current}`;
84
+ }
85
+ if (typeOnly) {
86
+ return `${name} is not exported by ${sdkPackage}`;
87
+ }
88
+ return `${name} is not exported by ${sdkPackage}, so it is not read`;
89
+ }
90
+ function nodeToImportedNames(node) {
91
+ if (ts.isImportDeclaration(node) &&
92
+ node.importClause?.namedBindings !== undefined &&
93
+ ts.isNamedImports(node.importClause.namedBindings)) {
94
+ const isTypeOnly = node.importClause.phaseModifier === ts.SyntaxKind.TypeKeyword;
95
+ return {
96
+ from: node.moduleSpecifier,
97
+ names: node.importClause.namedBindings.elements.map((specifier) => specifierToName(specifier, isTypeOnly)),
98
+ };
99
+ }
100
+ if (ts.isExportDeclaration(node) &&
101
+ node.moduleSpecifier !== undefined &&
102
+ node.exportClause !== undefined &&
103
+ ts.isNamedExports(node.exportClause)) {
104
+ const { isTypeOnly } = node;
105
+ return {
106
+ from: node.moduleSpecifier,
107
+ names: node.exportClause.elements.map((specifier) => specifierToName(specifier, isTypeOnly)),
108
+ };
109
+ }
110
+ if (ts.isImportEqualsDeclaration(node) &&
111
+ ts.isQualifiedName(node.moduleReference)) {
112
+ return {
113
+ from: node.moduleReference.left,
114
+ names: [{ name: node.moduleReference.right, typeOnly: node.isTypeOnly }],
115
+ };
116
+ }
117
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {
118
+ return {
119
+ from: node.expression,
120
+ names: [{ name: node.name, typeOnly: false }],
121
+ };
122
+ }
123
+ if (ts.isBindingElement(node)) {
124
+ return requireBindingToImportedNames(node);
125
+ }
126
+ return undefined;
127
+ }
128
+ function specifierToName(specifier, declarationIsTypeOnly) {
129
+ return {
130
+ name: specifier.propertyName ?? specifier.name,
131
+ typeOnly: declarationIsTypeOnly || specifier.isTypeOnly,
132
+ };
133
+ }
134
+ function requireBindingToImportedNames(binding) {
135
+ const name = binding.propertyName ?? binding.name;
136
+ const declaration = binding.parent.parent;
137
+ if (!ts.isObjectBindingPattern(binding.parent) ||
138
+ !ts.isVariableDeclaration(declaration) ||
139
+ declaration.initializer === undefined ||
140
+ !ts.isCallExpression(declaration.initializer) ||
141
+ !(ts.isIdentifier(name) || ts.isStringLiteral(name))) {
142
+ return undefined;
143
+ }
144
+ const specifier = declaration.initializer.arguments.at(0);
145
+ if (specifier === undefined) {
146
+ return undefined;
147
+ }
148
+ return { from: specifier, names: [{ name, typeOnly: false }] };
149
+ }
150
+ function isSdkModule(node, checker, sdk) {
151
+ const symbol = checker.getSymbolAtLocation(node);
152
+ return symbol !== undefined && symbolToTarget(symbol, checker) === sdk.symbol;
62
153
  }
63
154
  function nodeToChildren(node) {
64
155
  const children = [];
@@ -77,32 +168,50 @@ function isImportBinding(node, checker) {
77
168
  export function isStatic(property) {
78
169
  return (ts.getCombinedModifierFlags(property) & ts.ModifierFlags.Static) !== 0;
79
170
  }
80
- function foundToSdkReferences(found) {
171
+ function foundToSdkReferences(found, targets) {
81
172
  return found.map(({ name, expression, call, location }) => {
173
+ const target = targets.get(name);
174
+ if (target === undefined) {
175
+ return {
176
+ use: 'unregistered',
177
+ name,
178
+ message: `${name}: no registered protocol reads it`,
179
+ location,
180
+ };
181
+ }
82
182
  if (call !== undefined &&
83
183
  ts.isDecorator(call.parent) &&
84
- decoratorTargets[name].isTarget(call.parent.parent)) {
85
- return { use: 'decorator', name, call, decorator: call.parent, location };
184
+ target.isTarget(call.parent.parent)) {
185
+ const decorator = {
186
+ use: 'decorator',
187
+ name,
188
+ call,
189
+ decorator: call.parent,
190
+ location,
191
+ };
192
+ if (target.protocol !== undefined) {
193
+ decorator.protocol = target.protocol;
194
+ }
195
+ return decorator;
86
196
  }
87
197
  return {
88
198
  use: 'misplaced',
89
199
  name,
90
- message: misplacedToMessage(name, expression, call),
200
+ message: misplacedToMessage(name, target, targets, expression, call),
91
201
  location,
92
202
  };
93
203
  });
94
204
  }
95
- function misplacedToMessage(name, expression, call) {
96
- const target = decoratorTargets[name];
205
+ function misplacedToMessage(name, target, targets, expression, call) {
97
206
  if (call !== undefined && ts.isDecorator(call.parent)) {
98
- return `@${name} is on ${elementToDescription(call.parent.parent)}, so it is not read: put it on ${target.description}`;
207
+ return `@${name} is on ${elementToDescription(call.parent.parent, targets)}, so it is not read: put it on ${target.description}`;
99
208
  }
100
209
  if (ts.isDecorator(expression.parent)) {
101
210
  return `@${name} is not called, so it is not read: write @${name}()`;
102
211
  }
103
212
  return `${name} is not written as a decorator, so it is not read: write @${name}() on ${target.description}`;
104
213
  }
105
- function elementToDescription(element) {
214
+ function elementToDescription(element, targets) {
106
215
  if (ts.isClassExpression(element)) {
107
216
  return 'a class expression';
108
217
  }
@@ -115,26 +224,27 @@ function elementToDescription(element) {
115
224
  if (ts.isPropertyDeclaration(element) && isStatic(element)) {
116
225
  return 'a static property';
117
226
  }
118
- const target = Object.values(decoratorTargets).find(({ isTarget }) => isTarget(element));
227
+ const target = [...targets.values()].find(({ isTarget }) => isTarget(element));
119
228
  return target?.description ?? 'this element';
120
229
  }
121
- function programToSdkExports({ program, sdkEntry }, checker) {
122
- const sdkExports = new Map();
230
+ function programToSdkModule({ program, sdkEntry }, checker) {
123
231
  const entry = program.getSourceFile(sdkEntry);
124
232
  if (entry === undefined) {
125
- return sdkExports;
233
+ return undefined;
126
234
  }
127
- const entryModule = checker.getSymbolAtLocation(entry);
128
- if (entryModule === undefined) {
129
- return sdkExports;
235
+ const symbol = checker.getSymbolAtLocation(entry);
236
+ if (symbol === undefined) {
237
+ return undefined;
130
238
  }
131
- for (const exported of checker.getExportsOfModule(entryModule)) {
239
+ const exports = checker.getExportsOfModule(symbol);
240
+ const functions = new Map();
241
+ for (const exported of exports) {
132
242
  const target = symbolToTarget(exported, checker);
133
243
  if (target.flags & ts.SymbolFlags.Function) {
134
- sdkExports.set(target, exported.name);
244
+ functions.set(target, exported.name);
135
245
  }
136
246
  }
137
- return sdkExports;
247
+ return { symbol, names: new Set(exports.map(({ name }) => name)), functions };
138
248
  }
139
249
  export function symbolToTarget(symbol, checker) {
140
250
  if (symbol.flags & ts.SymbolFlags.Alias) {
@@ -1,40 +1,28 @@
1
1
  import { isDiagnostic } from "../model/diagnostic.js";
2
- import { listToNamedSchema } from "../model/schema-names.js";
3
2
  import { isHandlerTag, tagToText } from "./comment-tags.js";
4
- import { declaredToRead, isHandlerDecorator, methodToUppercaseDiagnostic, statusToNumberDiagnostic, } from "./handler-methods.js";
5
- import { fieldOptionsToNode } from "./schema-classes.js";
3
+ import { namesToChoice } from "./literal-options.js";
4
+ import { fieldOptionsToLeaf, fieldOptionsToProperty, withLeaf, } from "./schema-classes.js";
6
5
  import { argumentsToOptions, blockFieldKeys } from "./tag-schemas.js";
7
- const endpointForms = {
8
- provides: { usage: '@bidirekt provides <METHOD> <path>', arguments: 2 },
9
- consumes: {
10
- usage: '@bidirekt consumes <provider> <METHOD> <path>',
11
- arguments: 3,
12
- },
13
- };
14
- const bodyPattern = /^([^\s[\]]+)(?:\[\](?: as [^\s[\]]+)?)?$/;
15
- export function taggedCommentsToResources(comments, references) {
6
+ export function taggedCommentsToHandlerComments(comments, decorators, protocols) {
16
7
  const read = {
17
- provides: [],
18
- consumes: [],
8
+ comments: new Map(),
19
9
  schemas: [],
20
10
  errors: [],
21
11
  };
22
- const decorated = Map.groupBy(references.filter(isHandlerDecorator), (reference) => reference.decorator.parent);
12
+ const decorated = Map.groupBy(decorators, (reference) => reference.decorator.parent);
23
13
  const handled = new Set();
24
14
  for (const { element, tags } of comments) {
25
15
  const handlers = tags.filter(isHandlerTag);
26
- const bodies = tags.filter(({ keyword }) => keyword === 'request' || keyword === 'response');
16
+ const protocolTags = tags.filter((tag) => tag.protocol !== undefined && !isHandlerTag(tag));
27
17
  if (handlers.length === 0) {
28
- read.errors.push(...bodies.map((tag) => ({
29
- message: `"@bidirekt ${tag.keyword}" needs a "@bidirekt provides" or "@bidirekt consumes" tag in the same comment`,
30
- location: tag.location,
31
- })));
18
+ tagsToProtocolComments(element, protocolTags, read);
32
19
  continue;
33
20
  }
34
21
  const [handler, ...extra] = handlers;
35
22
  if (handled.has(element)) {
23
+ const handlerTags = protocols.map(({ name }) => `"@bidirekt ${name}"`);
36
24
  read.errors.push({
37
- message: 'a handler is declared more than once on this element: keep one "@bidirekt provides" or "@bidirekt consumes" comment',
25
+ message: `a handler is declared more than once on this element: keep one ${namesToChoice(handlerTags)} comment`,
38
26
  location: handler.location,
39
27
  });
40
28
  continue;
@@ -44,9 +32,9 @@ export function taggedCommentsToResources(comments, references) {
44
32
  message: `a comment declares one handler: move "${tagToText(tag)}" to its own comment`,
45
33
  location: tag.location,
46
34
  })));
47
- const decorators = decorated.get(element) ?? [];
48
- if (decorators.length > 0) {
49
- read.errors.push(...decorators.flatMap(({ name, location }) => {
35
+ const onElement = decorated.get(element) ?? [];
36
+ if (onElement.length > 0) {
37
+ read.errors.push(...onElement.flatMap(({ name, location }) => {
50
38
  const message = `@${name} and "${tagToText(handler)}" are both on this handler: keep one`;
51
39
  return [
52
40
  { message, location },
@@ -55,12 +43,22 @@ export function taggedCommentsToResources(comments, references) {
55
43
  }));
56
44
  continue;
57
45
  }
58
- tagsToResource(handler, bodies, read);
59
- read.schemas.push(...tagsToBlockSchemas(tags, read.errors));
46
+ tagsToProtocolComments(element, [handler, ...protocolTags], read);
47
+ read.schemas.push(...tagsToBlockSchemas(tags, read.errors, protocols));
60
48
  }
61
49
  return read;
62
50
  }
63
- function tagsToBlockSchemas(tags, errors) {
51
+ function tagsToProtocolComments(element, tags, read) {
52
+ for (const [protocol, own] of Map.groupBy(tags, (tag) => tag.protocol)) {
53
+ if (protocol === undefined) {
54
+ continue;
55
+ }
56
+ const comments = read.comments.get(protocol) ?? [];
57
+ comments.push({ element, tags: own });
58
+ read.comments.set(protocol, comments);
59
+ }
60
+ }
61
+ function tagsToBlockSchemas(tags, errors, protocols) {
64
62
  const blocks = [];
65
63
  let fields;
66
64
  for (const tag of tags) {
@@ -84,7 +82,7 @@ function tagsToBlockSchemas(tags, errors) {
84
82
  });
85
83
  continue;
86
84
  }
87
- const property = tagToBlockProperty(tag);
85
+ const property = tagToBlockProperty(tag, protocols);
88
86
  if (isDiagnostic(property)) {
89
87
  errors.push(property);
90
88
  fields.hasUnreadField = true;
@@ -119,8 +117,8 @@ function tagToBlockSchemaName(tag) {
119
117
  }
120
118
  return name;
121
119
  }
122
- function tagToBlockProperty(tag) {
123
- const [name, ...rest] = tag.arguments;
120
+ function tagToBlockProperty(tag, protocols) {
121
+ const [name, ...remaining] = tag.arguments;
124
122
  if (tag.error !== undefined) {
125
123
  return tag.error;
126
124
  }
@@ -130,128 +128,20 @@ function tagToBlockProperty(tag) {
130
128
  location: tag.location,
131
129
  };
132
130
  }
133
- const options = argumentsToOptions(rest, tag, blockFieldKeys);
131
+ const options = argumentsToOptions(remaining, tag, blockFieldKeys, protocols);
134
132
  if (isDiagnostic(options)) {
135
133
  return options;
136
134
  }
137
- if (options.declared === undefined) {
138
- return {
139
- message: `field "${name}" in a handler's comment needs its type: declare it with "type=<type>"`,
140
- location: tag.location,
141
- };
142
- }
143
- return {
144
- name,
145
- node: fieldOptionsToNode(options.declared, options),
146
- location: tag.location,
147
- };
148
- }
149
- function tagsToResource(handler, bodies, read) {
150
- const errors = [];
151
- const derived = [];
152
- const endpoint = handlerToEndpoint(handler);
153
- if (isDiagnostic(endpoint)) {
154
- errors.push(endpoint);
155
- }
156
- let request;
157
- const responses = [];
158
- for (const tag of bodies) {
159
- if (tag.error !== undefined) {
160
- errors.push(tag.error);
161
- continue;
162
- }
163
- if (tag.keyword === 'request') {
164
- if (request !== undefined) {
165
- errors.push({
166
- message: `"@bidirekt request" is declared more than once in this comment: keep one`,
167
- location: tag.location,
168
- });
169
- continue;
170
- }
171
- const body = argumentsToBody(tag.arguments, tag.location, derived);
172
- if (isDiagnostic(body)) {
173
- errors.push(body);
174
- continue;
175
- }
176
- request = body;
177
- continue;
178
- }
179
- const response = tagToResponse(tag, responses, derived);
180
- if (isDiagnostic(response)) {
181
- errors.push(response);
182
- continue;
183
- }
184
- responses.push(response);
185
- }
186
- read.errors.push(...errors);
187
- if (isDiagnostic(endpoint) || errors.length > 0) {
188
- return;
189
- }
190
- declaredToRead({ ...endpoint, request, responses, location: handler.location }, derived, read);
191
- }
192
- function handlerToEndpoint(handler) {
193
- const { usage, arguments: count } = endpointForms[handler.keyword];
194
- if (handler.error !== undefined) {
195
- return handler.error;
196
- }
197
- if (handler.arguments.length !== count) {
198
- return {
199
- message: `cannot read "${tagToText(handler)}": write "${usage}"`,
200
- location: handler.location,
201
- };
202
- }
203
- const [method, path] = handler.arguments.slice(-2);
204
- const uppercase = methodToUppercaseDiagnostic(method, handler.location);
205
- if (uppercase !== undefined) {
206
- return uppercase;
207
- }
208
- const endpoint = { method, path };
209
- if (handler.keyword === 'consumes') {
210
- endpoint.provider = handler.arguments[0];
135
+ const leaf = fieldOptionsToLeaf(options);
136
+ let read = leaf;
137
+ if (options.declared !== undefined) {
138
+ read = withLeaf(options.declared, leaf);
211
139
  }
212
- return endpoint;
213
- }
214
- function tagToResponse(tag, declared, derived) {
215
- if (tag.arguments.length === 0) {
140
+ if (read === undefined) {
216
141
  return {
217
- message: `cannot read "${tagToText(tag)}": write "@bidirekt response <status> [schema]"`,
218
- location: tag.location,
219
- };
220
- }
221
- const [status, ...body] = tag.arguments;
222
- const number = statusToNumberDiagnostic(status, tag.location);
223
- if (number !== undefined) {
224
- return number;
225
- }
226
- if (declared.some((response) => response.status === Number(status))) {
227
- return {
228
- message: `response status "${status}" is declared more than once in this comment: keep one`,
142
+ message: `field "${name}" in a handler's comment needs its type: declare it with "type=<type>"`,
229
143
  location: tag.location,
230
144
  };
231
145
  }
232
- const read = argumentsToBody(body, tag.location, derived);
233
- if (isDiagnostic(read)) {
234
- return read;
235
- }
236
- return { ...read, status: Number(status) };
237
- }
238
- function argumentsToBody(body, location, derived) {
239
- if (body.length === 0) {
240
- return { schema: null, location };
241
- }
242
- const text = body.join(' ');
243
- const match = bodyPattern.exec(text);
244
- if (match === null) {
245
- return {
246
- message: `cannot read "${text}" as a body: write "<schema>", "<schema>[]" or "<schema>[] as <name>"`,
247
- location,
248
- };
249
- }
250
- const [, schema] = match;
251
- if (!text.includes('[]')) {
252
- return { schema, location };
253
- }
254
- const list = listToNamedSchema(schema, / as (\S+)$/.exec(text)?.[1], location);
255
- derived.push(list);
256
- return { schema: list.name, location };
146
+ return fieldOptionsToProperty(name, read, options, tag.location);
257
147
  }