@metamask-previews/platform-api-docs 0.0.0-preview-1275d0fda → 0.0.0-preview-6235c3779

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.
@@ -1,12 +1,18 @@
1
1
  import * as path from "node:path";
2
2
  import { Node as NodeGuards, Project, ts } from "ts-morph";
3
3
  // ---------------------------------------------------------------------------
4
+ // NOTE: `ts-morph` is used heavily in this file to parse and extract
5
+ // information from TypeScript files. Although this library is not well
6
+ // documented, it wraps the TypeScript AST fairly well, and you can get a good
7
+ // sense of the AST by using this website: <https://ts-ast-viewer.com>
8
+ // ---------------------------------------------------------------------------
9
+ // ---------------------------------------------------------------------------
4
10
  // JSDoc utilities
5
11
  // ---------------------------------------------------------------------------
6
12
  /**
7
- * Convert `{@link X}` references inside a string to plain backtick code spans,
8
- * and escape any remaining (out-of-backtick) curly braces so the output is
9
- * safe to drop into MDX.
13
+ * Convert `{@link X}` references inside a JSDoc comment string to plain
14
+ * backtick code spans and escape any remaining (out-of-backtick) curly braces.
15
+ * This way the output is safe to render in a MDX document.
10
16
  *
11
17
  * @param text - The raw text to normalize.
12
18
  * @returns The text with `@link` resolved and stray braces escaped.
@@ -24,32 +30,30 @@ function escapeJsDocTextForMdx(text) {
24
30
  });
25
31
  }
26
32
  /**
27
- * Extract a JSDoc tag's comment text, normalizing whitespace so continuation
28
- * lines are joined with single spaces. ts-morph returns the raw comment with
29
- * embedded newlines preserved; we collapse those for the markdown output.
33
+ * Extract the comment text of a JSDoc tag the part that comes after the tag
34
+ * and any identifier, e.g. "Some param" in "@param foo Some param"
35
+ * normalizing whitespace to a single space so we can better control how it's
36
+ * rendered within the site.
30
37
  *
31
38
  * @param tag - The JSDoc tag.
32
39
  * @returns The flattened comment text.
33
40
  */
34
41
  function extractJsDocTagComment(tag) {
35
- // istanbul ignore next: ts-morph returns null for tags without comment text,
36
- // but every fixture tag we extract from carries a comment.
37
42
  return (tag.getCommentText() ?? '').replace(/\s+/gu, ' ').trim();
38
43
  }
39
44
  /**
40
45
  * Strip the conventional `- ` separator from the start of a `@param` tag's
41
- * comment. JSDoc style is `@param name - description`, and ts-morph hands us
42
- * back `- description` for the comment. The hyphen is purely cosmetic; we'd
43
- * rather render the description without it.
46
+ * comment.
44
47
  *
45
48
  * @param comment - The flattened comment text from a `@param` tag.
46
49
  * @returns The comment with any leading `- ` (or `– `, `— `) removed.
47
50
  */
48
- function stripParamSeparator(comment) {
51
+ function stripJsDocParamSeparator(comment) {
49
52
  return comment.replace(/^[-–—]\s*/u, '');
50
53
  }
51
54
  /**
52
- * Decompose a node's JSDoc into the parts the rendered docs need:
55
+ * Extract JSDoc from a TypeScript AST node and decompose it into the parts we
56
+ * need to render docs:
53
57
  *
54
58
  * - `description` — the body above the first tag, with `@deprecated` comments
55
59
  * appended as `**Deprecated:** <comment>` lines and normalized for MDX
@@ -59,7 +63,7 @@ function stripParamSeparator(comment) {
59
63
  *
60
64
  * Other tags (`@see`, `@throws`, `@template`, `@example`) are dropped.
61
65
  *
62
- * @param node - The AST node to extract JSDoc from.
66
+ * @param node - The AST node to extract JSDoc from (e.g. a type or a method).
63
67
  * @returns The decomposed JSDoc; empty strings/arrays when the node has no JSDoc.
64
68
  */
65
69
  function extractJsDoc(node) {
@@ -76,23 +80,23 @@ function extractJsDoc(node) {
76
80
  const tagName = tag.getTagName();
77
81
  if (tagName === 'deprecated') {
78
82
  const comment = extractJsDocTagComment(tag);
79
- // istanbul ignore next: bare `@deprecated` (without explanatory text)
80
- // doesn't appear in messenger JSDoc in practice.
81
83
  deprecatedLines.push(comment ? `**Deprecated:** ${comment}` : '**Deprecated:**');
82
84
  }
83
85
  else if (tagName === 'param' && NodeGuards.isJSDocParameterTag(tag)) {
84
86
  const nameNode = tag.getNameNode();
85
- // istanbul ignore next: `@param` tags without a name aren't valid JSDoc.
86
- if (!nameNode) {
87
+ const paramName = nameNode.getText();
88
+ if (!paramName) {
87
89
  continue;
88
90
  }
91
+ const comment = extractJsDocTagComment(tag);
89
92
  params.push({
90
- name: nameNode.getText(),
91
- description: escapeJsDocTextForMdx(stripParamSeparator(extractJsDocTagComment(tag))),
93
+ name: paramName,
94
+ description: escapeJsDocTextForMdx(stripJsDocParamSeparator(comment)),
92
95
  });
93
96
  }
94
97
  else if (tagName === 'returns' || tagName === 'return') {
95
- returns = escapeJsDocTextForMdx(extractJsDocTagComment(tag));
98
+ const comment = extractJsDocTagComment(tag);
99
+ returns = escapeJsDocTextForMdx(comment);
96
100
  }
97
101
  }
98
102
  const description = escapeJsDocTextForMdx([descriptionBody, ...deprecatedLines]
@@ -106,7 +110,7 @@ function extractJsDoc(node) {
106
110
  * @param node - The AST node to check.
107
111
  * @returns True if the node has an `@deprecated` tag.
108
112
  */
109
- function isDeprecated(node) {
113
+ function hasDeprecatedJsDocTag(node) {
110
114
  return node
111
115
  .getJsDocs()
112
116
  .flatMap((jsDoc) => jsDoc.getTags())
@@ -115,50 +119,6 @@ function isDeprecated(node) {
115
119
  // ---------------------------------------------------------------------------
116
120
  // Type-resolution helpers (powered by ts-morph's type checker)
117
121
  // ---------------------------------------------------------------------------
118
- /**
119
- * Resolve a TemplateLiteralTypeNode (e.g. `` `${typeof X}:foo` ``) to its
120
- * concrete string value, using the type checker to follow `typeof X` to its
121
- * literal type. Returns null if the type checker can't reduce it to a single
122
- * string literal.
123
- *
124
- * @param node - The template literal type node.
125
- * @returns The resolved string, or null.
126
- */
127
- function resolveTemplateLiteralType(node) {
128
- const type = node.getType();
129
- if (type.isStringLiteral()) {
130
- return type.getLiteralValueOrThrow();
131
- }
132
- // istanbul ignore next: messenger fixtures always reduce template literal
133
- // types to a single string literal via `typeof X` constants.
134
- return null;
135
- }
136
- /**
137
- * Resolve a capability-type-constructor's first generic argument to a
138
- * namespace string. Accepts either `typeof X` (resolved via the type checker)
139
- * or a string literal.
140
- *
141
- * @param typeArg - The first generic argument node.
142
- * @returns The resolved namespace, or null.
143
- */
144
- function resolveNamespaceFromTypeArg(typeArg) {
145
- if (NodeGuards.isTypeQuery(typeArg)) {
146
- const type = typeArg.getType();
147
- if (type.isStringLiteral()) {
148
- return type.getLiteralValueOrThrow();
149
- }
150
- }
151
- if (NodeGuards.isLiteralTypeNode(typeArg)) {
152
- const literal = typeArg.getLiteral();
153
- // istanbul ignore else: only string literals are valid namespace args.
154
- if (NodeGuards.isStringLiteral(literal)) {
155
- return literal.getLiteralValue();
156
- }
157
- }
158
- // istanbul ignore next: namespace args are always a `typeof X` query or a
159
- // string literal in valid messenger usage.
160
- return null;
161
- }
162
122
  /**
163
123
  * If `typeNode` is `Class['method']`, resolve `Class` to its declaration
164
124
  * (across files if needed via the type checker) and look up the method by
@@ -241,15 +201,11 @@ function buildMethodInfo(method) {
241
201
  const paramName = param.getNameNode().getText();
242
202
  const optional = param.hasQuestionToken() ? '?' : '';
243
203
  const typeNode = param.getTypeNode();
244
- // istanbul ignore next: handler parameters in messenger fixtures always
245
- // declare an explicit type.
246
204
  const paramType = typeNode ? typeNode.getText() : 'unknown';
247
205
  return `${paramName}${optional}: ${paramType}`;
248
206
  })
249
207
  .join(', ');
250
208
  const returnTypeNode = method.getReturnTypeNode();
251
- // istanbul ignore next: handler class methods in messenger fixtures always
252
- // declare an explicit return type.
253
209
  const returnType = returnTypeNode ? returnTypeNode.getText() : 'void';
254
210
  // For async methods, the declared return type already includes `Promise<>`,
255
211
  // so we don't need to wrap again.
@@ -258,224 +214,280 @@ function buildMethodInfo(method) {
258
214
  return { jsDoc: description, params, returns, signature };
259
215
  }
260
216
  /**
261
- * Find every `*Messenger` type alias in a source file, parse its
262
- * `Messenger<Namespace, Actions, Events>` generic arguments, and return the
263
- * capability-type declarations referenced from the Actions and Events slots
264
- * — paired with the kind under which they were referenced.
265
- *
266
- * The walker follows imported references via ts-morph's symbol resolution,
267
- * so capability types declared in sibling files (e.g. the auto-generated
268
- * `*-method-action-types.ts` files) are discovered even though only the
269
- * `*Messenger` declaration is local to this file.
217
+ * Looks for Messenger types in the source file (that is, those that are type
218
+ * aliases whose names end with "Messenger"), then extracts the `Actions` and
219
+ * `Events` parameters from these types.
270
220
  *
271
221
  * @param sourceFile - The TypeScript source file to scan.
272
- * @returns The list of locally- and transitively-referenced capability types.
222
+ * @returns A list of objects that represent messenger types.
273
223
  */
274
- function collectMessengerCapabilityTypeDeclarations(sourceFile) {
275
- const declarations = [];
276
- const seen = new Set();
224
+ function findMessengerTypeAliases(sourceFile) {
225
+ const parsedMessengerTypeAliases = [];
277
226
  for (const typeAlias of sourceFile.getTypeAliases()) {
278
227
  if (!typeAlias.getName().endsWith('Messenger')) {
279
228
  continue;
280
229
  }
281
230
  const body = typeAlias.getTypeNode();
231
+ // Basic check
282
232
  if (!body || !NodeGuards.isTypeReference(body)) {
283
233
  continue;
284
234
  }
285
235
  const typeArgs = body.getTypeArguments();
236
+ // Messenger types always have 3 type parameters
237
+ // (e.g. `Messenger<'FooController', Actions, Events>`)
286
238
  if (typeArgs.length < 3) {
287
239
  continue;
288
240
  }
289
- walkCapabilityTypes(typeArgs[1], 'action', declarations, seen);
290
- walkCapabilityTypes(typeArgs[2], 'event', declarations, seen);
241
+ parsedMessengerTypeAliases.push({
242
+ actionsTypeParameter: typeArgs[1],
243
+ eventsTypeParameter: typeArgs[2],
244
+ });
291
245
  }
292
- return declarations;
246
+ return parsedMessengerTypeAliases;
293
247
  }
294
248
  /**
295
- * Walk an Actions or Events type-argument tree and append the underlying
296
- * capability-type declarations to `output`. Unions are expanded. Type
297
- * references are resolved via ts-morph's symbol resolution (so imported
298
- * names are followed across files); a resolved alias whose body is itself a
299
- * union expands transparently, leaving the intermediate alias unrecorded.
300
- *
301
- * A resolved alias whose body is a single non-union type reference (e.g.
302
- * `type AllowedActions = ConnectivityControllerGetStateAction`) is treated
303
- * as an opaque re-export — the walk stops there, leaving the target to be
304
- * documented from its home package by the dedup logic later.
305
- *
306
- * For example, given:
249
+ * Walks the `Actions` and `Events` type parameters of the given messenger
250
+ * types, extracted in a previous step, to find all type declarations (i.e.,
251
+ * statements) that represent individual messenger actions or events.
307
252
  *
308
- * ```typescript
309
- * // NetworkController.ts
310
- * import type { NetworkControllerMethodActions } from './NetworkController-method-action-types';
311
- * type NetworkControllerActions =
312
- * | NetworkControllerGetStateAction
313
- * | NetworkControllerMethodActions;
314
- * type NetworkControllerMessenger = Messenger<typeof name, NetworkControllerActions, ...>;
315
- *
316
- * // NetworkController-method-action-types.ts
317
- * export type NetworkControllerAddNetworkAction = {
318
- * type: 'NetworkController:addNetwork';
319
- * handler: NetworkController['addNetwork'];
320
- * };
321
- * // ... more ...
322
- * export type NetworkControllerMethodActions =
323
- * | NetworkControllerAddNetworkAction
324
- * | ...;
325
- * ```
326
- *
327
- * walking the Actions slot yields each individual `NetworkController*Action`
328
- * declaration — both the local `NetworkControllerGetStateAction` and the
329
- * cross-file ones reached via `NetworkControllerMethodActions`.
253
+ * @param parsedMessengerTypeAliases - The list of objects representing
254
+ * messenger types, parsed in a previous step.
255
+ * @returns The list of type aliases that represent messenger capabilities among
256
+ * the given messenger types.
257
+ */
258
+ function findAllMessengerCapabilityTypeDeclarations(parsedMessengerTypeAliases) {
259
+ const allCapabilityTypeDeclarations = [];
260
+ let allVisitedTypeDeclarations = new Set();
261
+ for (const { actionsTypeParameter, eventsTypeParameter, } of parsedMessengerTypeAliases) {
262
+ for (const [typeParameter, kind] of [
263
+ [actionsTypeParameter, 'action'],
264
+ [eventsTypeParameter, 'event'],
265
+ ]) {
266
+ const result = recursivelyFindMessengerCapabilityTypeDeclarations(typeParameter, kind, allVisitedTypeDeclarations);
267
+ allCapabilityTypeDeclarations.push(...result.capabilityTypeDeclarations);
268
+ allVisitedTypeDeclarations = result.visitedTypeDeclarations;
269
+ }
270
+ }
271
+ return allCapabilityTypeDeclarations;
272
+ }
273
+ /**
274
+ * Recursively walks a `ts-morph` AST node at first the `Actions` or `Events`
275
+ * type parameter of a messenger type, and then a node within that parameter —
276
+ * to find all type aliases that represent individual messenger actions or
277
+ * events, no matter how deeply the type aliases exist in the tree or in which
278
+ * file they are located.
330
279
  *
331
- * @param node - The Actions or Events type-argument node to walk.
332
- * @param kind - Whether to tag found declarations as 'action' or 'event'.
333
- * @param output - The list to append discovered declarations to.
334
- * @param seen - Declaration nodes already visited (prevents cycles and
335
- * duplicate work).
280
+ * @param node - The `ts-morph` AST node to walk.
281
+ * @param kind - Whether to tag found type aliases as 'action' or 'event'.
282
+ * @param visitedTypeDeclarations - A variable that tracks visited type aliases
283
+ * and prevents duplicates.
284
+ * @returns The list of extracted messenger capability type aliases as well as
285
+ * an updated version of `visitedTypeDeclarations`.
336
286
  */
337
- function walkCapabilityTypes(node, kind, output, seen) {
287
+ function recursivelyFindMessengerCapabilityTypeDeclarations(node, kind, visitedTypeDeclarations) {
288
+ const result = {
289
+ capabilityTypeDeclarations: [],
290
+ visitedTypeDeclarations: new Set([...visitedTypeDeclarations]),
291
+ };
292
+ // If `node` is a union type, walk each type within it.
293
+ // EXAMPLES:
294
+ // type Actions = FooControllerSomeAction | FooControllerSomeOtherAction
295
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
296
+ // type FooControllerActions = FooControllerSomeAction | FooControllerSomeOtherAction
297
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
338
298
  if (NodeGuards.isUnionTypeNode(node)) {
339
- for (const member of node.getTypeNodes()) {
340
- walkCapabilityTypes(member, kind, output, seen);
299
+ for (const typeNode of node.getTypeNodes()) {
300
+ const innerResult = recursivelyFindMessengerCapabilityTypeDeclarations(typeNode, kind, result.visitedTypeDeclarations);
301
+ result.capabilityTypeDeclarations.push(...innerResult.capabilityTypeDeclarations);
302
+ for (const typeDeclaration of innerResult.visitedTypeDeclarations) {
303
+ result.visitedTypeDeclarations.add(typeDeclaration);
304
+ }
341
305
  }
342
- return;
343
- }
306
+ return result;
307
+ }
308
+ // If `node` is not a type reference, don't walk it.
309
+ // EXAMPLE:
310
+ // // Bad
311
+ // type Actions = { ... }
312
+ // ^^^^^^^
313
+ // // Good
314
+ // type Actions = FooControllerSomeAction;
315
+ // // Good
316
+ // type Actions = ControllerGetStateAction<...>;
344
317
  if (!NodeGuards.isTypeReference(node)) {
345
- return;
318
+ return result;
346
319
  }
347
320
  const nameNode = node.getTypeName();
348
- // istanbul ignore next: qualified-name references aren't used in messenger
349
- // generic arguments.
321
+ // Reject qualified-name type references, as we can't follow those.
322
+ // EXAMPLE:
323
+ // import * as somePackage from '...';
324
+ // type Actions = somePackage.FooControllerSomeAction;
325
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
350
326
  if (!NodeGuards.isIdentifier(nameNode)) {
351
- return;
327
+ return result;
352
328
  }
353
- // For a TypeReference whose name was imported, `getSymbol()` returns the
354
- // import alias symbol — its only declaration is the `ImportSpecifier`.
355
- // `getAliasedSymbol()` follows the alias to the original declaration in
356
- // the imported file. Use it when present; otherwise fall back to the
357
- // (already-local) symbol.
329
+ // Since we know we have a type reference, we can assume that we have a symbol.
330
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
358
331
  const localSymbol = nameNode.getSymbol();
359
- // istanbul ignore next: a referenced type name always resolves to a symbol
360
- // in a typechecked project.
361
- if (!localSymbol) {
362
- return;
363
- }
332
+ // If we have a type imported from another file, ensure that when we access
333
+ // the declaration, it's the *type* declaration in the other file, not the
334
+ // *import* declaration in this file.
335
+ // EXAMPLE:
336
+ // import { FooControllerSomeAction } from '@metamask/foo-controller';
337
+ // type Actions = FooControllerSomeAction;
338
+ // ^^^^^^^^^^^^^^^^^^^^^^^
364
339
  const symbol = localSymbol.getAliasedSymbol() ?? localSymbol;
365
- // istanbul ignore next: a resolved symbol always exposes its declarations
366
- // array in a typechecked project.
367
- for (const declaration of symbol.getDeclarations() ?? []) {
368
- if (seen.has(declaration)) {
340
+ // At this point, we have a type *reference*, but we need to find the type
341
+ // *declaration*.
342
+ // For instance, if we have `FooControllerSomeAction`, we need to find
343
+ // the full `type FooControllerSomeAction = ...` statement.
344
+ for (const declaration of symbol.getDeclarations()) {
345
+ // Prevent duplicates
346
+ if (result.visitedTypeDeclarations.has(declaration)) {
369
347
  continue;
370
348
  }
371
- seen.add(declaration);
349
+ result.visitedTypeDeclarations.add(declaration);
350
+ // If we have a type alias, then we have to handle a few scenarios.
351
+ // EXAMPLES:
352
+ // type FooControllerMethodActions = ...
353
+ // type FooControllerSomeAction = ...
372
354
  if (NodeGuards.isTypeAliasDeclaration(declaration)) {
373
- const aliasBody = declaration.getTypeNode();
374
- if (aliasBody && NodeGuards.isUnionTypeNode(aliasBody)) {
375
- // Umbrella union — descend through it without documenting the alias.
376
- walkCapabilityTypes(aliasBody, kind, output, seen);
355
+ const body = declaration.getTypeNode();
356
+ // If we have a union type, then walk each type in the union.
357
+ // EXAMPLE:
358
+ // type FooControllerMethodActions = FooControllerSomeAction | FooControllerSomeOtherAction
359
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
360
+ if (body && NodeGuards.isUnionTypeNode(body)) {
361
+ const innerResult = recursivelyFindMessengerCapabilityTypeDeclarations(body, kind, result.visitedTypeDeclarations);
362
+ result.capabilityTypeDeclarations.push(...innerResult.capabilityTypeDeclarations);
363
+ for (const typeDeclaration of innerResult.visitedTypeDeclarations) {
364
+ result.visitedTypeDeclarations.add(typeDeclaration);
365
+ }
377
366
  continue;
378
367
  }
368
+ // TODO: Is this necessary?
379
369
  // A bare TypeReference body with no type arguments (e.g.
380
370
  // `type AllowedActions = ConnectivityControllerGetStateAction`) is a
381
371
  // plain re-export — leave the target to be documented from its home
382
372
  // package, not this one. TypeReferences *with* type arguments are
383
373
  // capability-type-constructor invocations (e.g.
384
374
  // `ControllerGetStateAction<typeof name, State>`) and are recorded.
385
- if (aliasBody &&
386
- NodeGuards.isTypeReference(aliasBody) &&
387
- aliasBody.getTypeArguments().length === 0) {
375
+ if (body &&
376
+ NodeGuards.isTypeReference(body) &&
377
+ body.getTypeArguments().length === 0) {
388
378
  continue;
389
379
  }
390
- // TypeLiteral body, capability-type-constructor invocation, etc.
391
- output.push({ statement: declaration, kind });
380
+ // We finally found a messenger capability type! Capture the whole thing.
381
+ // (We will parse the body later.)
382
+ // EXAMPLE:
383
+ // type FooControllerSomeAction = { ... }
384
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
385
+ result.capabilityTypeDeclarations.push({ declaration, kind });
392
386
  }
387
+ // If we have an interface, we don't have any scenarios to handle, so
388
+ // capture it as is.
389
+ // EXAMPLE:
390
+ // interface FooControllerSomeAction { ... }
391
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
393
392
  else if (NodeGuards.isInterfaceDeclaration(declaration)) {
394
- output.push({ statement: declaration, kind });
393
+ result.capabilityTypeDeclarations.push({ declaration, kind });
395
394
  }
396
395
  }
396
+ return result;
397
397
  }
398
398
  // ---------------------------------------------------------------------------
399
399
  // Per-statement extraction
400
400
  // ---------------------------------------------------------------------------
401
401
  /**
402
- * Extract a single capability-type declaration to an
403
- * {@link ExtractedMessengerCapabilityType}.
402
+ * Given the declaration of a messenger capability type, extract information
403
+ * about it (action/event type string, handler/payload arguments and return
404
+ * type, etc.)
404
405
  *
405
- * @param statement - The type alias or interface declaration.
406
- * @param kind - Whether this statement is referenced as an action or an event.
406
+ * @param capabilityTypeDeclaration - The statement that declared the type for a
407
+ * messenger action or event, extracted in a previous step.
407
408
  * @param projectPath - Project root, used for computing relative source paths.
408
- * @returns The extracted capability, or null if no recognized pattern matches.
409
+ * @returns Information that may be extracted from the messenger capability type
410
+ * (may be `null` if the type is ineligible for extraction).
409
411
  */
410
- function extractFromMessengerCapabilityType(statement, kind, projectPath) {
411
- const inlineCapability = extractFromInlineMessengerCapabilityType(statement, kind, projectPath);
412
- if (inlineCapability) {
413
- return inlineCapability;
414
- }
415
- if (NodeGuards.isTypeAliasDeclaration(statement)) {
416
- return extractFromCapabilityTypeConstructor(statement, kind, projectPath);
417
- }
418
- // istanbul ignore next: interface declarations always have members and
419
- // therefore an inline shape, so the inline branch above always returns
420
- // non-null here.
421
- return null;
412
+ function extractFromMessengerCapabilityTypeDeclaration(capabilityTypeDeclaration, projectPath) {
413
+ return (tryToExtractFromMessengerCapabilityTypeLiteral(capabilityTypeDeclaration, projectPath) ??
414
+ tryToExtractFromCapabilityTypeConstructor(capabilityTypeDeclaration, projectPath));
422
415
  }
423
416
  /**
424
- * Try the inline messenger-capability-type pattern:
425
- * `{ type: '...'; handler: ... }` (action) or
426
- * `{ type: '...'; payload: ... }` (event), expressed as either a type alias
427
- * body or an interface body.
417
+ * If a messenger capability type is a type alias or interface and its body is
418
+ * a literal object type i.e. one of:
419
+ *
420
+ * - `{ type: '...'; handler: ... }` (action)
421
+ * - `{ type: '...'; payload: ... }` (event)
422
+ *
423
+ * then this function extracts information about the type (action/event type
424
+ * string, handler/payload arguments and return type, etc.)
428
425
  *
429
- * @param statement - The type alias or interface declaration.
430
- * @param kind - The expected kind (action or event).
426
+ * @param capabilityTypeDeclaration - The statement that declared the type for a
427
+ * messenger action or event, extracted in a previous step.
431
428
  * @param projectPath - Project root, used for computing relative source paths.
432
- * @returns The extracted capability, or null if the shape doesn't match.
429
+ * @returns The extracted capability packet, or null if the shape of the type
430
+ * doesn't match.
433
431
  */
434
- function extractFromInlineMessengerCapabilityType(statement, kind, projectPath) {
432
+ function tryToExtractFromMessengerCapabilityTypeLiteral(capabilityTypeDeclaration, projectPath) {
433
+ const { declaration, kind } = capabilityTypeDeclaration;
434
+ // Reject empty type aliases or interfaces.
435
+ // EXAMPLES:
436
+ // // Good
437
+ // type FooControllerSomeAction = {
438
+ // type: 'FooController:getState';
439
+ // handler: FooController['getState'];
440
+ // }
441
+ // // Good
442
+ // interface FooControllerSomeAction {
443
+ // type: 'FooController:getState';
444
+ // handler: FooController['getState'];
445
+ // }
446
+ // // Bad
447
+ // type FooControllerSomeAction = {};
448
+ // // Bad
449
+ // interface FooControllerSomeAction {};
435
450
  let members;
436
- if (NodeGuards.isTypeAliasDeclaration(statement)) {
437
- const body = statement.getTypeNode();
451
+ if (NodeGuards.isTypeAliasDeclaration(declaration)) {
452
+ const body = declaration.getTypeNode();
438
453
  if (body && NodeGuards.isTypeLiteral(body)) {
439
454
  members = body.getMembers();
440
455
  }
441
456
  }
442
457
  else {
443
- members = statement.getMembers();
458
+ members = declaration.getMembers();
444
459
  }
445
460
  if (!members) {
446
461
  return null;
447
462
  }
448
- const typeString = resolveInlineTypeString(members);
449
- // istanbul ignore next: capabilities reachable via the messenger walk
450
- // always have a resolvable `Namespace:name` type string.
451
- if (!typeString?.includes(':')) {
463
+ const propertySignatures = members.filter(NodeGuards.isPropertySignature.bind(NodeGuards));
464
+ // Actions and events must have a `type`, and it must be a string.
465
+ const typeString = getMessengerCapabilityTypeString(propertySignatures);
466
+ if (!typeString) {
452
467
  return null;
453
468
  }
454
- const handlerMember = getPropertyMember(members, 'handler');
455
- const payloadMember = getPropertyMember(members, 'payload');
456
- const rawSourceMember = kind === 'action' ? handlerMember : payloadMember;
457
- // istanbul ignore next: actions always have `handler` and events always
458
- // have `payload`; the messenger walk wouldn't have surfaced this
459
- // declaration otherwise.
460
- if (!rawSourceMember) {
469
+ // Actions must have a `handler`, and events must have a `payload`.
470
+ const handlerOrPayloadProperty = findProperty(propertySignatures, kind === 'action' ? 'handler' : 'payload');
471
+ if (!handlerOrPayloadProperty) {
461
472
  return null;
462
473
  }
463
- const rawSourceTypeNode = rawSourceMember.getTypeNode();
464
- // istanbul ignore next: property signatures we care about always have an
465
- // explicit type.
466
- if (!rawSourceTypeNode) {
467
- return null;
468
- }
469
- let handlerOrPayload = rawSourceTypeNode.getText().trim();
470
- let { description: jsDoc, params, returns } = extractJsDoc(statement);
471
- // For actions, if the handler resolves to a class method (`Class['method']`
472
- // — possibly in another file), inherit its signature plus any JSDoc fields
473
- // the type alias itself doesn't already provide.
474
+ const handlerOrPayloadPropertyTypeNode =
475
+ // We can assume the property has a type; otherwise it wouldn't compile.
476
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
477
+ handlerOrPayloadProperty.getTypeNode();
478
+ let handlerOrPayloadSignature = handlerOrPayloadPropertyTypeNode
479
+ .getText()
480
+ .trim();
481
+ let { description: jsDoc, params, returns } = extractJsDoc(declaration);
482
+ // For actions, if the handler resolves to a class method (e.g.
483
+ // `FooController['method']`), inherit its signature plus any JSDoc fields the
484
+ // type alias itself doesn't already provide.
485
+ // TODO: We don't want to do this.
474
486
  if (kind === 'action') {
475
- const resolvedMethod = resolveIndexedAccessMethod(rawSourceTypeNode);
487
+ const resolvedMethod = resolveIndexedAccessMethod(handlerOrPayloadPropertyTypeNode);
476
488
  if (resolvedMethod) {
477
489
  const info = buildMethodInfo(resolvedMethod);
478
- handlerOrPayload = info.signature;
490
+ handlerOrPayloadSignature = info.signature;
479
491
  if (!jsDoc && info.jsDoc) {
480
492
  jsDoc = info.jsDoc;
481
493
  }
@@ -487,147 +499,176 @@ function extractFromInlineMessengerCapabilityType(statement, kind, projectPath)
487
499
  }
488
500
  }
489
501
  }
490
- const sourceFile = statement.getSourceFile();
502
+ const sourceFile = declaration.getSourceFile();
491
503
  return {
492
- typeName: statement.getName(),
504
+ typeName: declaration.getName(),
493
505
  typeString,
494
506
  kind,
495
507
  jsDoc,
496
508
  params,
497
509
  returns,
498
- handlerOrPayload,
510
+ handlerOrPayload: handlerOrPayloadSignature,
499
511
  sourceFile: path.relative(projectPath, sourceFile.getFilePath()),
500
- line: statement.getStartLineNumber(),
501
- deprecated: isDeprecated(statement),
512
+ line: declaration.getStartLineNumber(),
513
+ deprecated: hasDeprecatedJsDocTag(declaration),
502
514
  };
503
515
  }
504
516
  /**
505
- * Resolve the literal value of an inline shape's `type` property — either a
506
- * direct string literal or a template literal type with `typeof X`
507
- * substitutions (resolved via the type checker).
517
+ * Searches the property signatures of a messenger capability type alias or
518
+ * interface to find the value of the `type` property, and then resolves it to a
519
+ * string (assuming it is already a string or a resolvable template literal).
508
520
  *
509
- * @param members - The type elements of the inline shape.
510
- * @returns The resolved type string, or null if it can't be resolved.
521
+ * @param capabilityTypeProperties - The property signatures of the messenger
522
+ * capability type.
523
+ * @returns The extracted capability type string, or null if `type` cannot be
524
+ * found in the members or it is an unexpected node.
511
525
  */
512
- function resolveInlineTypeString(members) {
513
- for (const member of members) {
514
- // istanbul ignore next: capability-type bodies only contain property
515
- // signatures.
516
- if (!NodeGuards.isPropertySignature(member)) {
517
- continue;
518
- }
519
- const memberNameNode = member.getNameNode();
520
- if (
521
- // istanbul ignore next: `type` is always a plain identifier.
522
- !NodeGuards.isIdentifier(memberNameNode) ||
523
- memberNameNode.getText() !== 'type') {
524
- continue;
525
- }
526
- const typeNode = member.getTypeNode();
527
- // istanbul ignore next: a `type` property without an explicit type
528
- // wouldn't compile.
529
- if (!typeNode) {
530
- continue;
531
- }
532
- if (NodeGuards.isLiteralTypeNode(typeNode)) {
533
- const literal = typeNode.getLiteral();
534
- // istanbul ignore next: messenger `type` fields are written as
535
- // quoted string literals in real fixtures; backtick template literals
536
- // are valid TypeScript but don't appear in practice.
537
- if (NodeGuards.isStringLiteral(literal) ||
538
- NodeGuards.isNoSubstitutionTemplateLiteral(literal)) {
539
- return literal.getLiteralValue();
540
- }
541
- // istanbul ignore next: numeric/boolean literal types aren't valid as a
542
- // messenger `type` and don't appear in real fixtures.
543
- return null;
544
- }
545
- if (NodeGuards.isTemplateLiteralTypeNode(typeNode)) {
546
- return resolveTemplateLiteralType(typeNode);
526
+ function getMessengerCapabilityTypeString(capabilityTypeProperties) {
527
+ const typeProperty = findProperty(capabilityTypeProperties, 'type');
528
+ if (!typeProperty) {
529
+ return null;
530
+ }
531
+ // A `type` property without an explicit type wouldn't compile.
532
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
533
+ const typeNode = typeProperty.getTypeNode();
534
+ // Ask the type checker to resolve the value of `type`. We're looking for
535
+ // `type` to be either a string literal or template literal.
536
+ //
537
+ // EXAMPLES:
538
+ // type FooControllerSomeAction = {
539
+ // type: 'FooController:someAction';
540
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^
541
+ // }
542
+ // type FooControllerSomeAction = {
543
+ // type: `FooController:someAction`;
544
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^
545
+ // }
546
+ // type FooControllerSomeAction = {
547
+ // type: `${typeof CONTROLLER_NAME}:someAction`;
548
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
549
+ // }
550
+ const resolvedType = typeNode.getType();
551
+ if (resolvedType.isStringLiteral()) {
552
+ // Type assertion: There aren't any type guards we can use to narrow this
553
+ // type further.
554
+ const literalValue = resolvedType.getLiteralValueOrThrow();
555
+ // Messenger action/event types need to be namespaced.
556
+ if (literalValue.includes(':')) {
557
+ return literalValue;
547
558
  }
548
559
  }
549
- // istanbul ignore next: the inline shape always has a `type` member that
550
- // produces either a literal or template-literal type.
551
560
  return null;
552
561
  }
553
562
  /**
554
- * Find the `PropertySignature` named `propName` in a type literal body.
563
+ * Finds a specific property in a list of property signatures for an object
564
+ * type.
555
565
  *
556
- * @param members - The type literal members to search.
557
- * @param propName - The property name to find.
566
+ * @param propertySignatures - The property signatures of the messenger
567
+ * capability type.
568
+ * @param name - The property name to find.
558
569
  * @returns The property signature, or null.
559
570
  */
560
- function getPropertyMember(members, propName) {
561
- for (const member of members) {
562
- // istanbul ignore next: capability-type bodies only contain property
563
- // signatures.
564
- if (!NodeGuards.isPropertySignature(member)) {
565
- continue;
566
- }
567
- const memberNameNode = member.getNameNode();
568
- if (
569
- // istanbul ignore next: capability properties always have identifier names.
570
- !NodeGuards.isIdentifier(memberNameNode) ||
571
- memberNameNode.getText() !== propName) {
571
+ function findProperty(propertySignatures, name) {
572
+ for (const property of propertySignatures) {
573
+ const propertyNameNode = property.getNameNode();
574
+ if (!NodeGuards.isIdentifier(propertyNameNode) ||
575
+ propertyNameNode.getText() !== name) {
572
576
  continue;
573
577
  }
574
- return member;
578
+ return property;
575
579
  }
576
580
  return null;
577
581
  }
578
582
  /**
579
- * Try the capability-type-constructor pattern:
580
- * `ControllerGetStateAction<typeof X, State>` for actions, or
581
- * `ControllerStateChangeEvent<typeof X, State>` for events.
583
+ * If a messenger capability type is a type alias for either the
584
+ * `ControllerGetStateAction` or `ControllerStateChangeEvent` type constructors,
585
+ * then this function extracts information about the type (action/event type
586
+ * string, handler/payload arguments and return type, etc.)
582
587
  *
583
- * @param statement - The type alias declaration.
584
- * @param kind - The expected kind (action or event).
588
+ * @param capabilityTypeDeclaration - The statement that declared the type for a
589
+ * messenger action or event, extracted in a previous step.
585
590
  * @param projectPath - Project root, used for computing relative source paths.
586
- * @returns The extracted capability, or null if the constructor doesn't match.
591
+ * @returns The extracted capability packet, or null if the shape of the type
592
+ * doesn't match.
587
593
  */
588
- function extractFromCapabilityTypeConstructor(statement, kind, projectPath) {
589
- const aliasBody = statement.getTypeNode();
590
- // istanbul ignore next: walker only records aliases whose body matches.
591
- if (!aliasBody || !NodeGuards.isTypeReference(aliasBody)) {
594
+ function tryToExtractFromCapabilityTypeConstructor(capabilityTypeDeclaration, projectPath) {
595
+ const { declaration, kind } = capabilityTypeDeclaration;
596
+ // Basic check: we need a type alias, otherwise the rest doesn't make sense.
597
+ // EXAMPLE:
598
+ // type FooControllerSomeAction = ...
599
+ if (!NodeGuards.isTypeAliasDeclaration(declaration)) {
592
600
  return null;
593
601
  }
594
- const nameNode = aliasBody.getTypeName();
595
- // istanbul ignore next: qualified-name type references aren't used.
596
- if (!NodeGuards.isIdentifier(nameNode)) {
602
+ // We want our type alias to be a reference to a utility type.
603
+ // Non-null assertion: We can assume the type has a body of some kind,
604
+ // otherwise it wouldn't compile.
605
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
606
+ const body = declaration.getTypeNode();
607
+ // We already determined in
608
+ // `recursivelyFindMessengerCapabilityTypeDeclarations` that the declaration
609
+ // is a type reference.
610
+ // TODO: Capture the following information ahead of time so we don't need to
611
+ // check this again.
612
+ // istanbul ignore next
613
+ if (!NodeGuards.isTypeReference(body)) {
597
614
  return null;
598
615
  }
599
- const constructorName = nameNode.getText();
600
- const typeArgs = aliasBody.getTypeArguments();
601
- if (typeArgs.length < 2) {
616
+ const typeName = body.getTypeName();
617
+ // We already determined in
618
+ // `recursivelyFindMessengerCapabilityTypeDeclarations` that the type is an
619
+ // identifier.
620
+ // TODO: Capture the following information ahead of time so we don't need to
621
+ // check this again.
622
+ // istanbul ignore next
623
+ if (!NodeGuards.isIdentifier(typeName)) {
602
624
  return null;
603
625
  }
626
+ // The name of the utility type should be either `ControllerGetStateAction`
627
+ // (for actions) or `ControllerStateChangeEvent` (for events).
628
+ // EXAMPLES:
629
+ // type FooControllerSomeAction = ControllerGetStateAction<...>
630
+ // type FooControllerSomeEvent = ControllerStateChangeEvent<...>
604
631
  const expectedConstructor = kind === 'action'
605
632
  ? 'ControllerGetStateAction'
606
633
  : 'ControllerStateChangeEvent';
607
- if (constructorName !== expectedConstructor) {
634
+ if (typeName.getText() !== expectedConstructor) {
635
+ return null;
636
+ }
637
+ // The utility type should take two parameters.
638
+ // EXAMPLES:
639
+ // type FooControllerSomeAction = ControllerGetStateAction<..., ...>
640
+ // type FooControllerSomeEvent = ControllerStateChangeEvent<..., ...>
641
+ const typeArgs = body.getTypeArguments();
642
+ if (typeArgs.length < 2) {
608
643
  return null;
609
644
  }
610
- const namespace = resolveNamespaceFromTypeArg(typeArgs[0]);
611
- // istanbul ignore next: recognized constructors always have resolvable args.
612
- if (!namespace) {
645
+ const namespaceArgType = typeArgs[0].getType();
646
+ // The first parameter should be a string literal.
647
+ // EXAMPLES:
648
+ // type FooControllerSomeAction = ControllerGetStateAction<'FooController', ...>
649
+ // type FooControllerSomeAction = ControllerGetStateAction<typeof CONTROLLER_NAME, ...>
650
+ if (!namespaceArgType.isStringLiteral()) {
613
651
  return null;
614
652
  }
653
+ // Type assertion: There aren't any type guards we can use to narrow this type
654
+ // further.
655
+ const namespace = namespaceArgType.getLiteralValueOrThrow();
656
+ const typeString = kind === 'action' ? `${namespace}:getState` : `${namespace}:stateChange`;
615
657
  const stateArgText = typeArgs[1].getText();
616
- const { description, params, returns } = extractJsDoc(statement);
617
- const sourceFile = statement.getSourceFile();
658
+ const handlerOrPayload = kind === 'action' ? `() => ${stateArgText}` : `[${stateArgText}, Patch[]]`;
659
+ const { description, params, returns } = extractJsDoc(declaration);
660
+ const sourceFile = declaration.getSourceFile();
618
661
  return {
619
- typeName: statement.getName(),
620
- typeString: kind === 'action' ? `${namespace}:getState` : `${namespace}:stateChange`,
662
+ typeName: declaration.getName(),
663
+ typeString,
621
664
  kind,
622
665
  jsDoc: description,
623
666
  params,
624
667
  returns,
625
- handlerOrPayload: kind === 'action'
626
- ? `() => ${stateArgText}`
627
- : `[${stateArgText}, Patch[]]`,
668
+ handlerOrPayload,
628
669
  sourceFile: path.relative(projectPath, sourceFile.getFilePath()),
629
- line: statement.getStartLineNumber(),
630
- deprecated: isDeprecated(statement),
670
+ line: declaration.getStartLineNumber(),
671
+ deprecated: hasDeprecatedJsDocTag(declaration),
631
672
  };
632
673
  }
633
674
  // ---------------------------------------------------------------------------
@@ -659,30 +700,29 @@ export function createExtractionProject() {
659
700
  });
660
701
  }
661
702
  /**
662
- * Extract every messenger action/event type reachable from a single source
663
- * file's `*Messenger` declarations.
703
+ * Extract information (action/event type string, handler/payload arguments and
704
+ * return type, etc.) about every messenger action or event type which is
705
+ * reachable through all of a source file's `*Messenger` type declarations.
664
706
  *
665
707
  * The caller is responsible for ensuring `sourceFile` (plus any files it
666
- * imports from) belongs to a ts-morph Project so cross-file symbol resolution
708
+ * imports from) belongs to a `ts-morph` Project so cross-file symbol resolution
667
709
  * works.
668
710
  *
669
711
  * @param sourceFile - The TypeScript source file to extract from.
670
712
  * @param projectPath - Project root, used for computing relative source paths.
671
- * @returns The extracted capability list.
713
+ * @returns The extracted information about actions and events.
672
714
  */
673
715
  export function extractFromSourceFile(sourceFile, projectPath) {
674
- const declarations = collectMessengerCapabilityTypeDeclarations(sourceFile);
675
- if (declarations.length === 0) {
676
- return [];
677
- }
678
- const items = [];
679
- for (const { statement, kind } of declarations) {
680
- const item = extractFromMessengerCapabilityType(statement, kind, projectPath);
681
- if (item) {
682
- items.push(item);
716
+ const messengerTypeAliases = findMessengerTypeAliases(sourceFile);
717
+ const capabilityTypeDeclarations = findAllMessengerCapabilityTypeDeclarations(messengerTypeAliases);
718
+ const messengerCapabilityPackets = [];
719
+ for (const capabilityTypeDeclaration of capabilityTypeDeclarations) {
720
+ const messengerCapabilityPacket = extractFromMessengerCapabilityTypeDeclaration(capabilityTypeDeclaration, projectPath);
721
+ if (messengerCapabilityPacket) {
722
+ messengerCapabilityPackets.push(messengerCapabilityPacket);
683
723
  }
684
724
  }
685
- return items;
725
+ return messengerCapabilityPackets;
686
726
  }
687
727
  /**
688
728
  * Convenience wrapper: extract from a single file by path. Loads the file