summaryrefslogtreecommitdiffstats
path: root/tools/ts/build_xpcom.js
blob: d09b18fb6922e0fc69d16b7812b7f48ba475545d (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

/**
 * Build: <objdir>/dist/@types/lib.gecko.xpcom.d.ts,
 *
 * from:  <objdir>/config/makefiles/xpidl/*.d.json type definition files,
 *        generated by a previous build step.
 */

const fs = require("fs");
const URL = "https://searchfox.org/mozilla-central/source/";

const HEADER = `/**
 * NOTE: Do not modify this file by hand.
 * Content was generated from source XPCOM .idl files.
 */
`;

// Emit a typescript interface, along with any related enums.
function ts_interface(iface) {
  let lines = [];
  let base = iface.base;
  iface.class = iface.id;

  // Make QueryInterface optional, enable plain objects to pass as nsISupports.
  let partial = iface.id === "nsISupports" ? "?" : "";

  let enums = iface.enums.map(e => `typeof ${iface.id}.${e.id}`).join(" & ");
  if (enums) {
    base += `, Enums<${enums}>`;
    iface.class += `, ${enums}`;

    // Close the global scope, avoid polluting it with the namespace value.
    lines.push("}  // global\n");
    lines.push(`declare namespace ${iface.id} {\n`);

    for (let e of iface.enums) {
      lines.push(`enum ${e.id} {`);
      for (let v of e.variants) {
        lines.push(`  ${v.name} = ${v.value},`);
      }
      lines.push("}\n");
    }

    lines.push("}\n");
    lines.push("declare global {\n");
  }

  // Handle [function] interfaces.
  if (iface.callable) {
    lines.push(`type ${iface.id} = Callable<{`);
  } else {
    lines.push(`interface ${iface.id} ${base ? `extends ${base} ` : ""}{`);
  }

  for (let c of iface.consts) {
    lines.push(`  readonly ${c.name}: ${c.value};`);
  }

  if (iface.consts.length && iface.members.length) {
    // For style points.
    lines.push("");
  }

  for (let m of iface.members) {
    if (!m.args) {
      lines.push(`  ${m.readonly ? "readonly " : ""}${m.name}: ${m.type};`);
    } else {
      let args = [];
      for (let arg of m.args) {
        // If this is the generic parameter, adjust its type.
        let type = arg.name === m.iid_is ? "T" : arg.type;
        args.push(`${arg.name}${arg.optional ? "?" : ""}: ${type}`);
      }
      let type = `(${args.join(", ")}): ${m.type}`;
      // Adjust signature if this is a generic method.
      let signature = m.iid_is ? `<T extends nsIID>${type}<T>` : type;
      lines.push(`  ${m.name}${partial}${signature};`);
    }
  }

  lines.push(iface.callable ? "}>\n" : "}\n");
  return lines;
}

// Link all generated .d.json files into a self-contained ts typelib.
function ts_link(dir, files) {
  let lines = [HEADER, "declare global {\n"];
  let typedefs = {};
  let iids = [];

  for (let djson of files) {
    let modules = JSON.parse(fs.readFileSync(`${dir}/${djson}`, "utf8"));

    for (let mod of modules) {
      lines.push(`// ${URL}${mod.path}\n`);
      Object.assign(typedefs, Object.fromEntries(mod.typedefs ?? []));

      for (let iface of mod.interfaces ?? []) {
        if (iface.id !== "nsIXPCComponents_Interfaces") {
          lines = lines.concat(ts_interface(iface));
          iids.push(`  ${iface.id}: nsJSIID<${iface.class}>;`);
        }
      }
    }
  }

  lines.push("interface nsIXPCComponents_Interfaces {");
  lines = lines.concat(iids);
  lines.push("}\n");

  lines.push("}  // global\n");

  lines.push("// Typedefs from xpidl.");
  for (let [id, type] of Object.entries(typedefs).sort()) {
    lines.push(`type ${id} = ${type};`);
  }
  lines.push("");

  // Include xpcom builtins.
  lines.push(fs.readFileSync(`${__dirname}/fixtures/intrinsics.d.ts`, "utf8"));
  return lines;
}

// For testing.
module.exports = { ts_link };

function main(lib_dts, djson_dir, ...djson_files) {
  let dts = ts_link(djson_dir, djson_files).join("\n");
  console.log(`[INFO] ${lib_dts} (${dts.length.toLocaleString()} bytes)`);
  fs.writeFileSync(lib_dts, dts);
}

if (require.main === module) {
  main(...process.argv.slice(2));
}