@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,28 +1,38 @@
1
1
  import ts from 'typescript';
2
- import { isDiagnostic } from "../model/diagnostic.js";
3
- import { listToNamedSchema } from "../model/schema-names.js";
4
- import { expressionToSchemaRef } from "./expression-to-schema-node.js";
5
- import { computedKeyToValue, expressionToLiteralOptions, literalOptionToName, literalOptionToString, } from "./literal-options.js";
6
- import { nodeToLocation } from "./location.js";
2
+ import { isDiagnostic } from "../../../model/diagnostic.js";
3
+ import { listToNamedSchema } from "../../../model/protocols/rest/schema-names.js";
4
+ import { expressionToSchemaRef } from "../../expression-to-schema-node.js";
5
+ import { computedKeyToValue, expressionToLiteralOptions, literalOptionToName, literalOptionToString, } from "../../literal-options.js";
6
+ import { nodeToLocation } from "../../location.js";
7
+ export const restDecoratorTargets = {
8
+ BidirektRestProvider: {
9
+ isTarget: ts.isMethodDeclaration,
10
+ description: 'a method',
11
+ },
12
+ BidirektRestConsumer: {
13
+ isTarget: ts.isMethodDeclaration,
14
+ description: 'a method',
15
+ },
16
+ };
17
+ export const restRenamedExports = {
18
+ BidirektProvider: 'BidirektRestProvider',
19
+ BidirektConsumer: 'BidirektRestConsumer',
20
+ BidirektProviderOptions: 'BidirektRestProviderOptions',
21
+ BidirektConsumerOptions: 'BidirektRestConsumerOptions',
22
+ BidirektHttpMethod: 'BidirektRestHttpMethod',
23
+ };
7
24
  const listKeys = ['list', 'name'];
8
25
  const handlerOptions = {
9
- BidirektProvider: ['method', 'path', 'request', 'responses'],
10
- BidirektConsumer: ['provider', 'method', 'path', 'request', 'responses'],
26
+ BidirektRestProvider: ['method', 'path', 'request', 'responses'],
27
+ BidirektRestConsumer: ['provider', 'method', 'path', 'request', 'responses'],
11
28
  };
12
- export function isHandlerDecorator(reference) {
13
- return (reference.use === 'decorator' &&
14
- (reference.name === 'BidirektProvider' ||
15
- reference.name === 'BidirektConsumer'));
16
- }
17
- export function sdkReferencesToResources(references, context) {
29
+ export function sdkDecoratorsToResources(decorators, context) {
18
30
  const read = {
19
- provides: [],
20
- consumes: [],
21
- schemas: [],
31
+ blocks: [],
32
+ derived: [],
22
33
  errors: [],
23
34
  };
24
- for (const reference of references.filter(isHandlerDecorator)) {
25
- const { name, call } = reference;
35
+ for (const { name, call } of decorators) {
26
36
  const what = `@${name}`;
27
37
  const options = expressionToLiteralOptions(call.arguments[0], `${what} options`, handlerOptions[name]);
28
38
  if (isDiagnostic(options)) {
@@ -38,7 +48,7 @@ export function sdkReferencesToResources(references, context) {
38
48
  errors: [],
39
49
  };
40
50
  let provider;
41
- if (name === 'BidirektConsumer') {
51
+ if (name === 'BidirektRestConsumer') {
42
52
  provider = withoutDiagnostic(requiredString(handler, 'provider'), handler);
43
53
  }
44
54
  const declared = handlerToDeclared(handler);
@@ -50,17 +60,17 @@ export function sdkReferencesToResources(references, context) {
50
60
  }
51
61
  return read;
52
62
  }
53
- export function declaredToRead({ provider, request, ...rest }, derived, read) {
54
- read.schemas.push(...derived);
55
- const resource = rest;
63
+ export function declaredToRead({ provider, request, ...declared }, derived, read) {
64
+ read.derived.push(...derived);
65
+ const resource = declared;
56
66
  if (request !== undefined) {
57
67
  resource.request = request;
58
68
  }
59
- if (provider === undefined) {
60
- read.provides.push(resource);
61
- return;
69
+ const sideBlock = { block: [resource] };
70
+ if (provider !== undefined) {
71
+ sideBlock.provider = provider;
62
72
  }
63
- read.consumes.push({ ...resource, provider });
73
+ read.blocks.push(sideBlock);
64
74
  }
65
75
  function handlerToDeclared(handler) {
66
76
  const method = withoutDiagnostic(handlerToMethod(handler), handler);
@@ -0,0 +1,11 @@
1
+ import { sdkDecoratorsToResources } from "./handler-methods.js";
2
+ import { taggedCommentsToResources } from "./tag-handlers.js";
3
+ export function protocolInputToResources(input) {
4
+ const decorated = sdkDecoratorsToResources(input.decorators, input.context);
5
+ const tagged = taggedCommentsToResources(input.comments);
6
+ return {
7
+ blocks: [...decorated.blocks, ...tagged.blocks],
8
+ derived: [...decorated.derived, ...tagged.derived],
9
+ errors: [...decorated.errors, ...tagged.errors],
10
+ };
11
+ }
@@ -0,0 +1,152 @@
1
+ import { isDiagnostic } from "../../../model/diagnostic.js";
2
+ import { listToNamedSchema } from "../../../model/protocols/rest/schema-names.js";
3
+ import { isHandlerTag, tagToText } from "../../comment-tags.js";
4
+ import { declaredToRead, methodToUppercaseDiagnostic, statusToNumberDiagnostic, } from "./handler-methods.js";
5
+ export const restRenamedTags = {
6
+ provides: 'rest provides',
7
+ consumes: 'rest consumes',
8
+ };
9
+ const endpointForms = {
10
+ provides: { usage: '@bidirekt rest provides <METHOD> <path>', arguments: 2 },
11
+ consumes: {
12
+ usage: '@bidirekt rest consumes <provider> <METHOD> <path>',
13
+ arguments: 3,
14
+ },
15
+ };
16
+ const bodyPattern = /^([^\s[\]]+)(?:\[\](?: as [^\s[\]]+)?)?$/;
17
+ export function taggedCommentsToResources(comments) {
18
+ const read = {
19
+ blocks: [],
20
+ derived: [],
21
+ errors: [],
22
+ };
23
+ for (const { tags } of comments) {
24
+ const handler = tags.find(isHandlerTag);
25
+ const bodies = tags.filter((tag) => !isHandlerTag(tag));
26
+ if (handler === undefined) {
27
+ read.errors.push(...bodies.map((tag) => ({
28
+ message: `"@bidirekt ${tag.keyword}" needs a "@bidirekt rest provides" or "@bidirekt rest consumes" tag in the same comment`,
29
+ location: tag.location,
30
+ })));
31
+ continue;
32
+ }
33
+ tagsToResource(handler, bodies, read);
34
+ }
35
+ return read;
36
+ }
37
+ function tagsToResource(handler, bodies, read) {
38
+ const errors = [];
39
+ const derived = [];
40
+ const endpoint = handlerToEndpoint(handler);
41
+ if (isDiagnostic(endpoint)) {
42
+ errors.push(endpoint);
43
+ }
44
+ let request;
45
+ const responses = [];
46
+ for (const tag of bodies) {
47
+ if (tag.error !== undefined) {
48
+ errors.push(tag.error);
49
+ continue;
50
+ }
51
+ if (tag.keyword === 'request') {
52
+ if (request !== undefined) {
53
+ errors.push({
54
+ message: `"@bidirekt request" is declared more than once in this comment: keep one`,
55
+ location: tag.location,
56
+ });
57
+ continue;
58
+ }
59
+ const body = argumentsToBody(tag.arguments, tag.location, derived);
60
+ if (isDiagnostic(body)) {
61
+ errors.push(body);
62
+ continue;
63
+ }
64
+ request = body;
65
+ continue;
66
+ }
67
+ const response = tagToResponse(tag, responses, derived);
68
+ if (isDiagnostic(response)) {
69
+ errors.push(response);
70
+ continue;
71
+ }
72
+ responses.push(response);
73
+ }
74
+ read.errors.push(...errors);
75
+ if (isDiagnostic(endpoint) || errors.length > 0) {
76
+ return;
77
+ }
78
+ declaredToRead({ ...endpoint, request, responses, location: handler.location }, derived, read);
79
+ }
80
+ function handlerToEndpoint(handler) {
81
+ if (handler.error !== undefined) {
82
+ return handler.error;
83
+ }
84
+ const [form, ...endpointArguments] = handler.arguments;
85
+ if (form !== 'provides' && form !== 'consumes') {
86
+ return {
87
+ message: `cannot read "${tagToText(handler)}": write "${endpointForms.provides.usage}" or "${endpointForms.consumes.usage}"`,
88
+ location: handler.location,
89
+ };
90
+ }
91
+ const { usage, arguments: count } = endpointForms[form];
92
+ if (endpointArguments.length !== count) {
93
+ return {
94
+ message: `cannot read "${tagToText(handler)}": write "${usage}"`,
95
+ location: handler.location,
96
+ };
97
+ }
98
+ const [method, path] = endpointArguments.slice(-2);
99
+ const uppercase = methodToUppercaseDiagnostic(method, handler.location);
100
+ if (uppercase !== undefined) {
101
+ return uppercase;
102
+ }
103
+ const endpoint = { method, path };
104
+ if (form === 'consumes') {
105
+ endpoint.provider = endpointArguments[0];
106
+ }
107
+ return endpoint;
108
+ }
109
+ function tagToResponse(tag, declared, derived) {
110
+ if (tag.arguments.length === 0) {
111
+ return {
112
+ message: `cannot read "${tagToText(tag)}": write "@bidirekt response <status> [schema]"`,
113
+ location: tag.location,
114
+ };
115
+ }
116
+ const [status, ...body] = tag.arguments;
117
+ const number = statusToNumberDiagnostic(status, tag.location);
118
+ if (number !== undefined) {
119
+ return number;
120
+ }
121
+ if (declared.some((response) => response.status === Number(status))) {
122
+ return {
123
+ message: `response status "${status}" is declared more than once in this comment: keep one`,
124
+ location: tag.location,
125
+ };
126
+ }
127
+ const read = argumentsToBody(body, tag.location, derived);
128
+ if (isDiagnostic(read)) {
129
+ return read;
130
+ }
131
+ return { ...read, status: Number(status) };
132
+ }
133
+ function argumentsToBody(body, location, derived) {
134
+ if (body.length === 0) {
135
+ return { schema: null, location };
136
+ }
137
+ const text = body.join(' ');
138
+ const match = bodyPattern.exec(text);
139
+ if (match === null) {
140
+ return {
141
+ message: `cannot read "${text}" as a body: write "<schema>", "<schema>[]" or "<schema>[] as <name>"`,
142
+ location,
143
+ };
144
+ }
145
+ const [, schema] = match;
146
+ if (!text.includes('[]')) {
147
+ return { schema, location };
148
+ }
149
+ const list = listToNamedSchema(schema, / as (\S+)$/.exec(text)?.[1], location);
150
+ derived.push(list);
151
+ return { schema: list.name, location };
152
+ }
@@ -1,20 +1,34 @@
1
1
  import ts from 'typescript';
2
2
  import { isDiagnostic } from "../model/diagnostic.js";
3
- import { expressionToUnionMembers } from "./expression-to-schema-node.js";
3
+ import { expressionToSchemaRef, expressionToUnionMembers, } from "./expression-to-schema-node.js";
4
4
  import { expressionToLiteralOptions, literalOptionToBoolean, literalOptionToDescription, literalOptionToName, literalOptionToStringLiteral, propertyNameToText, } from "./literal-options.js";
5
5
  import { nodeToLocation } from "./location.js";
6
- import { builtDeclarationToDiagnostic, isLibrarySymbol, isObjectDeclaration, javaScriptTagHints, memberToOwner, nodeToSymbol, symbolToClass, tagHints, unreadClassToDiagnostic, } from "./schema-context.js";
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
- import { typeNodeToDeclaredUnion, typeNodeToFlags, typeNodeToTranslatedType, } from "./type-to-schema-node.js";
9
- export function sdkReferencesToSchemas(references, tags, context) {
8
+ import { typeNodeToDeclaredUnion, typeNodeToFlags, typeNodeToShapedLeaf, typeNodeToTranslatedType, } from "./type-to-schema-node.js";
9
+ const schemaOptionKeys = ['name', 'union'];
10
+ const fieldOptionKeys = [
11
+ 'name',
12
+ 'description',
13
+ 'optional',
14
+ 'nullable',
15
+ 'type',
16
+ 'union',
17
+ ];
18
+ export function sdkReferencesToSchemas(references, tags, context, protocols) {
10
19
  const errors = new Set();
11
20
  const fieldAnnotations = new Map();
12
21
  for (const [field, tagField] of tags.fields) {
13
22
  fieldAnnotations.set(field, { from: 'tag', ...tagField });
14
23
  }
24
+ const fieldDecorators = protocolsToFieldDecorators(protocols);
15
25
  const schemaDecorators = [];
16
26
  for (const reference of references) {
17
- if (reference.use === 'misplaced') {
27
+ if (reference.use !== 'decorator') {
28
+ continue;
29
+ }
30
+ const vocabulary = fieldDecorators.get(reference.name);
31
+ if (reference.protocol !== undefined && vocabulary === undefined) {
18
32
  continue;
19
33
  }
20
34
  const element = reference.decorator.parent;
@@ -22,17 +36,32 @@ export function sdkReferencesToSchemas(references, tags, context) {
22
36
  schemaDecorators.push([element, reference.call]);
23
37
  }
24
38
  else if (ts.isPropertyDeclaration(element)) {
25
- if (fieldAnnotations.get(element)?.from === 'tag') {
39
+ const tagged = tags.fields.get(element);
40
+ if (tagged !== undefined) {
26
41
  errors.add({
27
- message: '@BidirektField and "@bidirekt field" are both on this property: keep one',
42
+ message: `@${reference.name} and "${tagged.label}" are both on this property: keep one`,
28
43
  location: reference.location,
29
44
  });
30
45
  continue;
31
46
  }
32
- fieldAnnotations.set(element, { from: 'decorator', call: reference.call });
47
+ const decorated = fieldAnnotations.get(element);
48
+ if (decorated?.from === 'decorator' &&
49
+ decorated.name !== reference.name) {
50
+ const message = `@${decorated.name} and @${reference.name} are both on this property: keep one`;
51
+ errors.add({ message, location: nodeToLocation(decorated.call) });
52
+ errors.add({ message, location: reference.location });
53
+ continue;
54
+ }
55
+ fieldAnnotations.set(element, {
56
+ from: 'decorator',
57
+ name: reference.name,
58
+ call: reference.call,
59
+ vocabulary,
60
+ });
33
61
  }
34
62
  }
35
63
  const unreadOptions = new Set();
64
+ const unionOptions = new Map();
36
65
  for (const [declaration, call] of schemaDecorators) {
37
66
  if (tags.schemas.has(declaration)) {
38
67
  errors.add({
@@ -42,18 +71,32 @@ export function sdkReferencesToSchemas(references, tags, context) {
42
71
  continue;
43
72
  }
44
73
  let name = declaration.name?.text;
45
- const declared = schemaClassToName(declaration, call);
74
+ const declared = schemaClassToOptions(declaration, call);
46
75
  if (isDiagnostic(declared)) {
47
76
  errors.add(declared);
48
77
  unreadOptions.add(declaration);
49
78
  }
50
79
  else {
51
- name = declared;
80
+ name = declared.name;
81
+ unionOptions.set(declaration, declared.union);
52
82
  }
53
83
  if (name !== undefined) {
54
84
  context.schemaDeclarations.set(declaration, name);
55
85
  }
56
86
  }
87
+ const unions = new Map(tags.unions);
88
+ for (const [declaration, expression] of unionOptions) {
89
+ if (expression === undefined) {
90
+ continue;
91
+ }
92
+ const members = expressionToUnionMembers(expression, '"union"', context);
93
+ if (isDiagnostic(members)) {
94
+ errors.add(members);
95
+ unreadOptions.add(declaration);
96
+ continue;
97
+ }
98
+ unions.set(declaration, { members, location: nodeToLocation(expression) });
99
+ }
57
100
  const fields = new Map();
58
101
  const schemas = [];
59
102
  const reading = {
@@ -66,7 +109,9 @@ export function sdkReferencesToSchemas(references, tags, context) {
66
109
  for (const [declaration, name] of context.schemaDeclarations) {
67
110
  const properties = [];
68
111
  const declaredFields = declarationToFields(declaration, reading);
112
+ const union = unions.get(declaration);
69
113
  if (declaredFields.length === 0 &&
114
+ union === undefined &&
70
115
  !unreadOptions.has(declaration) &&
71
116
  !hasUnreadFields(declaration, reading)) {
72
117
  errors.add({
@@ -76,7 +121,7 @@ export function sdkReferencesToSchemas(references, tags, context) {
76
121
  }
77
122
  for (const [field, annotation] of declaredFields) {
78
123
  if (!fields.has(field)) {
79
- const read = fieldToProperty(field, annotation, context);
124
+ const read = fieldToProperty(field, annotation, context, protocols);
80
125
  fields.set(field, read);
81
126
  if (isDiagnostic(read)) {
82
127
  errors.add(read);
@@ -87,9 +132,13 @@ export function sdkReferencesToSchemas(references, tags, context) {
87
132
  properties.push(read);
88
133
  }
89
134
  }
135
+ const selfMember = union && unionToSelfMemberDiagnostic(union, name);
136
+ if (selfMember !== undefined) {
137
+ errors.add(selfMember);
138
+ }
90
139
  schemas.push({
91
140
  name,
92
- node: { type: 'object', properties },
141
+ node: propertiesToSchemaNode(properties, union),
93
142
  location: nodeToLocation(declaration.name ?? declaration),
94
143
  });
95
144
  }
@@ -102,6 +151,33 @@ export function sdkReferencesToSchemas(references, tags, context) {
102
151
  ]),
103
152
  };
104
153
  }
154
+ function unionToSelfMemberDiagnostic(union, name) {
155
+ const itself = union.members.find(({ node }) => node.type === 'ref' && node.schema === name);
156
+ if (itself === undefined) {
157
+ return undefined;
158
+ }
159
+ return {
160
+ message: `schema "${name}" lists itself as member "${itself.key}" of its union: remove that member`,
161
+ location: union.location,
162
+ };
163
+ }
164
+ function propertiesToSchemaNode(properties, union) {
165
+ if (union === undefined) {
166
+ return { type: 'object', properties };
167
+ }
168
+ if (properties.length === 0) {
169
+ return { type: 'union', members: union.members };
170
+ }
171
+ return { type: 'union', properties, members: union.members };
172
+ }
173
+ function protocolsToFieldDecorators(protocols) {
174
+ return new Map(protocols.flatMap(({ vocabulary }) => {
175
+ if (vocabulary === undefined) {
176
+ return [];
177
+ }
178
+ return [[vocabulary.fieldDecorator, vocabulary]];
179
+ }));
180
+ }
105
181
  function schemaToHints(declaration, tags, context) {
106
182
  if (tags.schemas.has(declaration)) {
107
183
  return tagHints;
@@ -131,7 +207,7 @@ function fieldsOutsideSchemas({ fieldAnnotations, parents, context }, annotatedS
131
207
  }
132
208
  return [
133
209
  {
134
- message: `@BidirektField is in ${declarationToDescription(field.parent)}, which is neither a schema nor the parent of one, so it is not read: add @BidirektSchema to the class`,
210
+ message: `@${annotation.name} is in ${declarationToDescription(field.parent)}, which is neither a schema nor the parent of one, so it is not read: add @BidirektSchema to the class`,
135
211
  location: nodeToLocation(annotation.call),
136
212
  },
137
213
  ];
@@ -163,8 +239,8 @@ export function declarationToDescription(declaration) {
163
239
  }
164
240
  return `class "${name}"`;
165
241
  }
166
- function schemaClassToName(declaration, call) {
167
- const options = expressionToLiteralOptions(call.arguments[0], '@BidirektSchema options', ['name']);
242
+ function schemaClassToOptions(declaration, call) {
243
+ const options = expressionToLiteralOptions(call.arguments[0], '@BidirektSchema options', schemaOptionKeys);
168
244
  if (isDiagnostic(options)) {
169
245
  return options;
170
246
  }
@@ -179,7 +255,7 @@ function schemaClassToName(declaration, call) {
179
255
  location: nodeToLocation(declaration),
180
256
  };
181
257
  }
182
- return resolved;
258
+ return { name: resolved, union: options.get('union') };
183
259
  }
184
260
  function declarationToFields(declaration, reading, visited = new Set()) {
185
261
  const fields = [];
@@ -314,9 +390,9 @@ function unreadableParent(parent, declaration) {
314
390
  location: nodeToLocation(parent),
315
391
  };
316
392
  }
317
- function fieldToProperty(field, annotation, context) {
393
+ function fieldToProperty(field, annotation, context, protocols) {
318
394
  const location = nodeToLocation(field.name);
319
- const options = annotationToFieldOptions(annotation, context);
395
+ const options = annotationToFieldOptions(annotation, context, protocols);
320
396
  if (isDiagnostic(options)) {
321
397
  return withLocation(options, location);
322
398
  }
@@ -332,9 +408,9 @@ function fieldToProperty(field, annotation, context) {
332
408
  if (isDiagnostic(read)) {
333
409
  return withLocation(read, location);
334
410
  }
335
- return { name, node: fieldOptionsToNode(read, options), location };
411
+ return fieldOptionsToProperty(name, read, options, location);
336
412
  }
337
- export function fieldOptionsToNode(read, options) {
413
+ export function fieldOptionsToProperty(name, read, options, location) {
338
414
  const node = { ...read };
339
415
  delete node.optional;
340
416
  delete node.nullable;
@@ -347,11 +423,23 @@ export function fieldOptionsToNode(read, options) {
347
423
  if (options.description !== undefined) {
348
424
  node.description = options.description;
349
425
  }
350
- return node;
426
+ const { extension } = options;
427
+ if (extension === undefined) {
428
+ return { name, node, location };
429
+ }
430
+ return {
431
+ name,
432
+ node: extension.vocabulary.toNode(extension.options, node),
433
+ location,
434
+ vocabulary: extension.vocabulary,
435
+ };
351
436
  }
352
437
  function annotationToContext(annotation, field, context) {
353
438
  if (annotation.from !== 'tag') {
354
- return context;
439
+ return {
440
+ ...context,
441
+ hints: { ...context.hints, ...fieldDecoratorHints(annotation.name) },
442
+ };
355
443
  }
356
444
  if ((field.flags & ts.NodeFlags.JavaScriptFile) !== 0) {
357
445
  return { ...context, hints: javaScriptTagHints };
@@ -366,6 +454,7 @@ function withLocation(diagnostic, location) {
366
454
  }
367
455
  function fieldToSchemaNode(field, options, context) {
368
456
  const typeNode = field.type ?? ts.getJSDocType(field);
457
+ const leaf = fieldOptionsToLeaf(options);
369
458
  if (options.declared !== undefined) {
370
459
  const declared = declaredToFieldNode(options.declared, typeNode, context);
371
460
  if (isDiagnostic(declared)) {
@@ -373,13 +462,13 @@ function fieldToSchemaNode(field, options, context) {
373
462
  }
374
463
  const flags = fieldToFlags(field, typeNode, context);
375
464
  return {
376
- ...declared,
465
+ ...withLeaf(declared, leaf),
377
466
  optional: declared.optional ?? flags.optional,
378
467
  nullable: declared.nullable ?? flags.nullable,
379
468
  };
380
469
  }
381
470
  if (typeNode !== undefined) {
382
- const translated = typeNodeToTranslatedType(typeNode, context);
471
+ const translated = typeNodeToFieldType(typeNode, leaf, context);
383
472
  if (isDiagnostic(translated)) {
384
473
  return translated;
385
474
  }
@@ -388,10 +477,32 @@ function fieldToSchemaNode(field, options, context) {
388
477
  optional: translated.optional || field.questionToken !== undefined,
389
478
  };
390
479
  }
480
+ if (leaf !== undefined) {
481
+ return { ...leaf, optional: field.questionToken !== undefined };
482
+ }
391
483
  return {
392
484
  message: `cannot read the type of "${field.name.getText()}": write its type or declare it with ${context.hints.declareFieldType}`,
393
485
  };
394
486
  }
487
+ function typeNodeToFieldType(typeNode, leaf, context) {
488
+ if (leaf === undefined) {
489
+ return typeNodeToTranslatedType(typeNode, context);
490
+ }
491
+ return typeNodeToShapedLeaf(typeNode, leaf, context);
492
+ }
493
+ export function fieldOptionsToLeaf(options) {
494
+ const { extension } = options;
495
+ return extension?.vocabulary.toLeaf?.(extension.options);
496
+ }
497
+ export function withLeaf(node, leaf) {
498
+ if (leaf === undefined) {
499
+ return node;
500
+ }
501
+ if (node.type === 'array') {
502
+ return { ...node, items: withLeaf(node.items, leaf) };
503
+ }
504
+ return leaf;
505
+ }
395
506
  function declaredToFieldNode(declared, typeNode, context) {
396
507
  if (declared.type !== 'union' || typeNode === undefined) {
397
508
  return declared;
@@ -425,17 +536,68 @@ function fieldToFlags(field, typeNode, context) {
425
536
  optional: flags.optional || field.questionToken !== undefined,
426
537
  };
427
538
  }
428
- function annotationToFieldOptions(annotation, context) {
539
+ function annotationToFieldOptions(annotation, context, protocols) {
429
540
  if (annotation.from === 'tag') {
430
541
  return annotation.options;
431
542
  }
432
- const options = expressionToLiteralOptions(annotation.call.arguments[0], '@BidirektField options', ['name', 'description', 'optional', 'nullable', 'type', 'union']);
543
+ const { name, call, vocabulary } = annotation;
544
+ const options = expressionToLiteralOptions(call.arguments[0], `@${name} options`, [...fieldOptionKeys, ...(vocabulary?.fieldOptions ?? [])], undefined, (key) => optionToFieldDecoratorHint(key, protocols));
433
545
  if (isDiagnostic(options)) {
434
546
  return options;
435
547
  }
436
- return literalOptionsToFieldOptions(options, context);
548
+ const fieldOptions = literalOptionsToFieldOptions(options, name, context);
549
+ if (vocabulary === undefined || isDiagnostic(fieldOptions)) {
550
+ return fieldOptions;
551
+ }
552
+ const extension = literalOptionsToExtension(options, vocabulary, context);
553
+ if (isDiagnostic(extension)) {
554
+ return extension;
555
+ }
556
+ return { ...fieldOptions, extension };
557
+ }
558
+ function optionToFieldDecoratorHint(key, protocols) {
559
+ const vocabulary = optionToOwningProtocol(key, protocols)?.vocabulary;
560
+ if (vocabulary === undefined) {
561
+ return undefined;
562
+ }
563
+ return `for ${vocabulary.label}, use @${vocabulary.fieldDecorator}`;
564
+ }
565
+ export function optionToOwningProtocol(key, protocols) {
566
+ return protocols.find(({ vocabulary }) => vocabulary?.fieldOptions.includes(key) === true);
567
+ }
568
+ function literalOptionsToExtension(options, vocabulary, context) {
569
+ const values = {};
570
+ for (const key of vocabulary.fieldOptions) {
571
+ const expression = options.get(key);
572
+ if (expression === undefined) {
573
+ continue;
574
+ }
575
+ const value = expressionToOptionValue(key, expression, context);
576
+ if (isDiagnostic(value)) {
577
+ return value;
578
+ }
579
+ values[key] = value;
580
+ }
581
+ return { vocabulary, options: values };
582
+ }
583
+ function expressionToOptionValue(key, expression, context) {
584
+ if (ts.isStringLiteralLike(expression)) {
585
+ return expression.text;
586
+ }
587
+ if (ts.isIdentifier(expression) ||
588
+ ts.isPropertyAccessExpression(expression)) {
589
+ const ref = expressionToSchemaRef(expression, context);
590
+ if (isDiagnostic(ref)) {
591
+ return ref;
592
+ }
593
+ return ref.schema;
594
+ }
595
+ return {
596
+ message: `"${key}" must be a string literal or a @BidirektSchema class written in place`,
597
+ location: nodeToLocation(expression),
598
+ };
437
599
  }
438
- function literalOptionsToFieldOptions(options, context) {
600
+ function literalOptionsToFieldOptions(options, decorator, context) {
439
601
  const name = literalOptionToName(options, 'name');
440
602
  if (isDiagnostic(name)) {
441
603
  return name;
@@ -459,7 +621,7 @@ function literalOptionsToFieldOptions(options, context) {
459
621
  const union = options.get('union');
460
622
  if (type !== undefined && union !== undefined) {
461
623
  return {
462
- message: 'declare either "type" or "union" in @BidirektField, not both',
624
+ message: `declare either "type" or "union" in @${decorator}, not both`,
463
625
  };
464
626
  }
465
627
  const fieldOptions = { name, description, optional, nullable };
@@ -2,14 +2,19 @@ import ts from 'typescript';
2
2
  import { pathToShown } from "./location.js";
3
3
  import { declarationToScript, isBuildOutput, isInstalledFile, } from "./program.js";
4
4
  import { symbolToTarget } from "./sdk-references.js";
5
+ export function fieldDecoratorHints(decorator) {
6
+ return {
7
+ declareType: `@${decorator}({ type })`,
8
+ declareFieldType: `@${decorator}({ type })`,
9
+ declareUnion: `@${decorator}({ union })`,
10
+ declareName: `@${decorator}({ name })`,
11
+ placeUnion: `the "union" of @${decorator}`,
12
+ };
13
+ }
5
14
  const decoratorHints = {
6
- declareType: '@BidirektField({ type })',
7
- declareFieldType: '@BidirektField({ type })',
8
- declareUnion: '@BidirektField({ union })',
9
- declareName: '@BidirektField({ name })',
15
+ ...fieldDecoratorHints('BidirektField'),
10
16
  schemaAnnotation: '@BidirektSchema',
11
17
  addSchema: 'add @BidirektSchema to it',
12
- placeUnion: 'the "union" of @BidirektField',
13
18
  annotateField: '@BidirektField',
14
19
  builtDeclaration: 'which has no decorators',
15
20
  readsDeclarationFiles: false,