dts-gen
Version:
TypeScript Definition File Generator
123 lines • 4.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = writeDefinitelyTypedPackage;
const child_process_1 = require("child_process");
const fs_1 = require("fs");
const http_1 = require("http");
const https_1 = require("https");
const path_1 = require("path");
const which = require("which");
const names_1 = require("./names");
function writeDefinitelyTypedPackage(indexDtsContent, packageName, overwrite) {
const dtName = (0, names_1.getDTName)(packageName);
const packageDir = (0, path_1.join)("types", dtName);
// Check for overwrite
if (!overwrite) {
if ((0, fs_1.existsSync)(packageDir)) {
console.log(`Directory ${packageDir} already exists and --overwrite was not specified; exiting.`);
process.exit(2);
}
}
if (!(0, fs_1.existsSync)(packageDir)) {
(0, fs_1.mkdirSync)(packageDir);
}
run(indexDtsContent, packageName, dtName, packageDir).catch((e) => {
console.error(e);
process.exit(1);
});
}
async function run(indexDtsContent, packageName, dtName, packageDir) {
const files = [
["index.d.ts", indexDtsContent],
[`${dtName}-tests.ts`, ""],
["tsconfig.json", `${JSON.stringify(getTSConfig(dtName), undefined, 4)}\n`],
["package.json", `${JSON.stringify(await getPackageJson(dtName, packageName), undefined, 4)}\n`],
[".npmignore", ["*", "!**/*.d.ts", "!**/*.d.cts", "!**/*.d.mts", "!**/*.d.*.ts"].join("\n") + "\n"],
];
for (const [name, text] of files) {
(0, fs_1.writeFileSync)((0, path_1.join)(packageDir, name), text, "utf-8");
}
}
function getTSConfig(dtName) {
return {
compilerOptions: {
module: "node16",
lib: ["es6"],
noImplicitAny: true,
noImplicitThis: true,
strictFunctionTypes: true,
strictNullChecks: true,
types: [],
noEmit: true,
forceConsistentCasingInFileNames: true,
},
files: ["index.d.ts", `${dtName}-tests.ts`],
};
}
async function getPackageJson(dtName, packageName) {
let version = "x.x";
let project = "https://github.com/baz/foo " +
"(Does not have to be to GitHub, " +
"but prefer linking to a source code repository rather than to a project website.)";
try {
const reg = JSON.parse(await loadString(`https://registry.npmjs.org/${packageName}`));
const { latest } = reg["dist-tags"];
const { homepage } = reg.versions[latest];
version = latest.split(".").slice(0, 2).join("."); // Just major.minor
if (homepage !== undefined)
project = homepage;
}
catch (e) {
console.warn(`Warning: Could not retrieve version/homepage information: ${e.message}`);
}
let authorName = "My Self";
try {
authorName =
(0, child_process_1.execFileSync)(which.sync("git"), ["config", "--global", "user.name"], { encoding: "utf-8" }).trim() || authorName;
}
catch (e) {
console.warn(`Warning: Could not retrieve author name: ${e.message}`);
}
let authorUserName = "me";
try {
const remoteUrl = (0, child_process_1.execFileSync)(which.sync("git"), ["config", "--get", "remote.origin.url"], {
encoding: "utf-8",
}).trim();
// Handle HTTPS URLs like https://github.com/user/repo.git
const httpsMatch = remoteUrl.match(/github\.com\/([^/]+)/);
// Handle SSH URLs like git@github.com:user/repo.git
const sshMatch = remoteUrl.match(/github\.com:([^/]+)/);
authorUserName = httpsMatch?.[1] || sshMatch?.[1] || authorUserName;
}
catch (e) {
console.warn(`Warning: Could not retrieve author's user name: ${e.message}`);
}
return {
private: true,
name: `@types/${dtName}`,
version: `${version}.9999`,
projects: [project],
devDependencies: {
[`@types/${dtName}`]: "workspace:.",
},
owners: [
{
name: authorName,
githubUsername: authorUserName,
},
],
};
}
function loadString(url) {
return new Promise((resolve, reject) => {
(0, https_1.get)(url, (res) => {
if (res.statusCode !== 200) {
return reject(new Error(`HTTP Error ${res.statusCode}: ${http_1.STATUS_CODES[res.statusCode || 500]} for ${url}`));
}
let rawData = "";
res.on("data", (chunk) => (rawData += chunk));
res.on("end", () => resolve(rawData));
}).on("error", (e) => reject(e));
});
}
//# sourceMappingURL=definitely-typed.js.map