summaryrefslogtreecommitdiff
path: root/extract-tsdefs/extract.ts
blob: b4721892679420463af6551288729e0945773960 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
 This file is part of GNU Taler
 (C) 2022 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import * as ts from "typescript";
import * as fs from "fs/promises";
import * as path from "path";
import * as prettier from "prettier";

const currentDir = ".";
const excludedNames = new Set(["TalerErrorCode", "WalletBackupContentV1"]);

const configFile = ts.findConfigFile(
  currentDir,
  ts.sys.fileExists,
  "tsconfig.json"
);
if (!configFile) throw Error("tsconfig.json not found");
const { config } = ts.readConfigFile(configFile, ts.sys.readFile);

const { options, fileNames, errors } = ts.parseJsonConfigFileContent(
  config,
  ts.sys,
  currentDir
);

const program = ts.createProgram({
  options,
  rootNames: fileNames,
  configFileParsingDiagnostics: errors,
});

const checker = program.getTypeChecker();

const sourceFile = program.getSourceFile("src/wallet-api-types.ts");

if (!sourceFile) {
  throw Error();
}

const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

const fileSymbol = program.getTypeChecker().getSymbolAtLocation(sourceFile);

const expo = fileSymbol?.exports;
if (!expo) {
  throw Error();
}

interface PerOpGatherState {
  opName: string;
  nameSet: Set<string>;
  group: string;
}

interface GatherState {
  declTexts: Map<string, string>;
}

function gatherDecls(
  node: ts.Node,
  gatherState: GatherState,
  perOpState: PerOpGatherState
): void {
  switch (node.kind) {
    case ts.SyntaxKind.TypeReference: {
      console.log(`typeref ${node.getText()}`);
      const type = checker.getTypeAtLocation(node);
      if (type.flags === ts.TypeFlags.String) {
        console.log("string!");
        break;
      }
      const symbol = type.symbol || type.aliasSymbol;
      if (!symbol) {
        console.log(`no symbol for ${node.getText()}`);
        break;
      }
      const name = symbol.name;
      if (perOpState.nameSet.has(name)) {
        break;
      }
      perOpState.nameSet.add(name);
      if (excludedNames.has(name)) {
        break;
      }
      const decls = symbol.getDeclarations();
      decls?.forEach((decl) => {
        console.log(`decl kind ${ts.SyntaxKind[node.kind]}`);
        console.log(`decl for ${node.getText()}`);
        const sourceFilename = decl.getSourceFile().fileName;
        if (path.basename(sourceFilename).startsWith("lib.")) {
          return;
        }
        console.log(`decl source ${decl.getSourceFile().fileName}`);
        console.log(`mod name ${decl.getSourceFile().moduleName}`);
        switch (decl.kind) {
          case ts.SyntaxKind.EnumMember: {
            const parentType = checker.getTypeAtLocation(decl.parent);
            const declText = printer.printNode(
              ts.EmitHint.Unspecified,
              decl,
              decl.getSourceFile()!
            );
            gatherState.declTexts.set(
              name,
              `// Enum value:\n// ${
                parentType.symbol.name || parentType.aliasSymbol?.name
              }.${declText}`
            );
            break;
          }
          case ts.SyntaxKind.InterfaceDeclaration:
          case ts.SyntaxKind.EnumDeclaration:
          case ts.SyntaxKind.TypeAliasDeclaration: {
            const declText = printer.printNode(
              ts.EmitHint.Unspecified,
              decl,
              decl.getSourceFile()!
            );
            gatherState.declTexts.set(name, declText);
            console.log(declText);
            break;
          }
          default:
            console.log(`unknown decl kind ${ts.SyntaxKind[decl.kind]}`);
            break;
        }
        gatherDecls(decl, gatherState, perOpState);
      });
      break;
    }
    default:
      node.forEachChild((child) => {
        gatherDecls(child, gatherState, perOpState);
      });
      //console.log(`// unknown node kind ${ts.SyntaxKind[node.kind]}`);
      return;
  }
}

const main = async () => {
  const f = await fs.open("out.md", "w");
  const gatherState: GatherState = {
    declTexts: new Map<string, string>(),
  };
  const perOpStates: PerOpGatherState[] = [];

  let currentGroup: string = "Unknown Group";

  expo.forEach((v, k) => {
    if (!v.name.endsWith("Op")) {
      return;
    }
    const decls = v.getDeclarations();
    decls?.forEach((decl) => {
      const commentRanges = ts.getLeadingCommentRanges(
        sourceFile.getFullText(),
        decl.getFullStart()
      );

      console.log(commentRanges);
      commentRanges?.forEach((r) => {
        const text = sourceFile.getFullText().slice(r.pos, r.end);
        console.log("comment text:", text);
        const groupPrefix = "group:";
        const loc = text.indexOf(groupPrefix);
        if (loc >= 0) {
          const groupName = text.slice(loc + groupPrefix.length);
          console.log("got new group", groupName);
          currentGroup = groupName;
        }
      });

      const perOpState: PerOpGatherState = {
        opName: v.name,
        nameSet: new Set<string>(),
        group: currentGroup,
      };
      const declText = printer.printNode(
        ts.EmitHint.Unspecified,
        decl,
        decl.getSourceFile()!
      );
      perOpState.nameSet.add(v.name);
      gatherState.declTexts.set(v.name, declText);
      gatherDecls(decl, gatherState, perOpState);
      perOpStates.push(perOpState);
    });
  });

  const allNames: Set<string> = new Set();

  for (const g of perOpStates) {
    for (const k of g.nameSet.values()) {
      allNames.add(k);
    }
  }

  const commonNames: Set<string> = new Set();

  for (const name of allNames) {
    let count = 0;
    for (const g of perOpStates) {
      for (const k of g.nameSet.values()) {
        if (name === k) {
          count++;
        }
      }
    }
    if (count > 1) {
      console.log(`common name: ${name}`);
      commonNames.add(name);
    }
  }

  const groups = new Set<string>();
  for (const g of perOpStates) {
    groups.add(g.group);
  }

  await f.write(`# Wallet API Documentation\n`);

  await f.write(`## Overview\n`);
  for (const g of groups.values()) {
    await f.write(`### ${g}\n`);
    for (const op of perOpStates) {
      if (op.group !== g) {
        continue;
      }
      await f.write(`* [${op.opName}](#${op.opName.toLowerCase()})\n`);
    }
  }

  await f.write(`## Operation Reference\n`);
  for (const g of perOpStates) {
    await f.write(`(${g.opName.toLowerCase()})=\n`);
    await f.write(`### ${g.opName}\n`);
    for (const name of g.nameSet.values()) {
      if (commonNames.has(name)) {
        continue;
      }
      const text = gatherState.declTexts.get(name);
      if (!text) {
        continue;
      }
      await f.write("```typescript\n");
      const formatted = prettier.format(text, {
        semi: true,
        parser: "typescript",
      });
      await f.write(`${formatted}\n`);
      await f.write("```\n");
    }
    await f.write("\n");
  }

  await f.write(`## Common Declarations\n`);
  for (const name of commonNames.values()) {
    const text = gatherState.declTexts.get(name);
    if (!text) {
      continue;
    }
    await f.write("```typescript\n");
    const formatted = prettier.format(text, {
      semi: true,
      parser: "typescript",
    });
    await f.write(`${formatted}`);
    await f.write("```\n");
  }

  await f.close();
};

main();