Skip to content

Instantly share code, notes, and snippets.

@ptantiku
Last active April 5, 2024 04:46
Show Gist options
  • Save ptantiku/01c2187f00110691ce2c2f2a0e23ad92 to your computer and use it in GitHub Desktop.
Save ptantiku/01c2187f00110691ce2c2f2a0e23ad92 to your computer and use it in GitHub Desktop.
Generate Bunfig.toml by using scope and token from .npmrc
#!/usr/bin/env bun
import Bun from 'bun';
/**
* Main function
* @return {Promise<void>} nothing
*/
async function main() {
// open and read inFile
const inFile = Bun.file('.npmrc');
const inData = await inFile.text();
// find all registries
const registries = [...inData.matchAll(/(@[^:]+):registry=(\S+)/g)];
let scopeData = '[install.scopes]\n';
// for each registry, find authToken and write in TOML format
for (const registry of registries) {
const scope = registry[1];
const url = registry[2];
const tokenRegex = new RegExp(
`/${scope.replace('@', '')}/:_authToken=['"]?(\\S+)['"]?`
);
const usernameRegex = new RegExp(
`/${scope.replace('@', '')}/:username=['"]?(\\S+)['"]?`
);
const passwordRegex = new RegExp(
`/${scope.replace('@', '')}/:_password=['"]?(\\S+)['"]?`
);
const token = inData.match(tokenRegex);
const username = inData.match(usernameRegex);
const password = inData
.match(passwordRegex)
?.map(p => p.replaceAll(/["']/g, ''));
if (token) {
// authToken found
scopeData += `"${scope}" = { url = "${url}", token = "${token[1]}" }\n`;
} else if (!!username && !!password) {
// username & password found
if (password[1].startsWith('ZX')) {
// if double-encoded, decode once
password[1] = atob(password[1]);
}
scopeData += `"${scope}" = { url = "${url}", username = "${username[1]}", password = "${password[1]}" }\n`;
} else {
// no authToken found
scopeData += `"${scope}" = "${url}"\n`;
}
}
// open outFile
const outFile = Bun.file('bunfig.toml');
await Bun.write(outFile, scopeData);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment