Skip to content

Commit

Permalink
v0.1.0: Initial release 🍾
Browse files Browse the repository at this point in the history
  • Loading branch information
nchevsky committed Jun 3, 2023
0 parents commit 8c68e88
Show file tree
Hide file tree
Showing 7 changed files with 9,943 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('bitumen/configuration/eslint');
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
BSD 2-Clause License

Copyright (c) Nick Chevsky

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Overview

`renova` patches third-party packages with non-fully-ESM-compliant source and/or TypeScript declaration files (e.g. `@apollo/client`) by appending explicit file names and extensions to unqualified `export` and `import` statements, facilitating `nodenext`/`node16`+ module resolution of dependencies with legacy exports.

For example, given the following source tree:

- `directory/`
- `index.js`
- `file.js`

Unqualified exports and imports are corrected as follows:

## Input
```js
export {foo} from './directory';
import bar from './file';
```

## Output
```js
export {foo} from './directory/index.js';
import bar from './file.js';
```

# Usage

## Automatic

📍 `package.json`

```json
{
"scripts": {
"dependencies": "renova @apollo/client"
}
}
```

This will patch `@apollo/client`'s `.d.ts` files whenever dependencies are installed or upgraded.

💡 Note that, when run from the `dependencies` lifecycle script, no output may be printed. In contrast, `postinstall` does allow output but is only executed when installing _all_ dependencies; not when installing or upgrading one or more specific packages.

## Manual
```shell
$ npx renova [--dry-run] [--extensions=<extension>,...] [--verbose] <package> ...

<package>: Name of a package under ./node_modules to patch, e.g. '@apollo/client'.

--dry-run: Print potential outcome without altering files. Implies --verbose.
--extensions: Comma-separated list of file name extensions to process. Defaults to '.d.ts'.
--verbose: Print all matching exports and imports.
```

# Example
```shell
# first-time run
$ npx renova --verbose @apollo/client
./node_modules/@apollo/client/cache/core/cache.d.ts
🛠️ ../../utilities → ../../utilities/index.js
🛠️ ./types/DataProxy → ./types/DataProxy.js
🛠️ ./types/Cache → ./types/Cache.js
...

# safe to run on an already-patched package
$ npx renova --verbose @apollo/client
./node_modules/@apollo/client/cache/core/cache.d.ts
✔️ ../../utilities/index.js
✔️ ./types/DataProxy.js
✔️ ./types/Cache.js
...
```
112 changes: 112 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#!/usr/bin/env node

import {open, opendir, stat} from 'node:fs/promises';

import {parse, print} from 'recast';
import typeScriptParser from 'recast/parsers/typescript.js';

const options = {dryRun: false, extensions: ['.d.ts'], packages: new Set(), verbose: false};

/**
* Recursively discovers matching files and directories in the given path and corrects any
* unqualified exports and imports by appending the appropriate file names and extensions.
*/
async function processFiles(rootPath) {
for await (const directoryEntry of await opendir(rootPath)) {
/** Whether the current file contained exports/imports that have been corrected. */
let hasFileBeenCorrected = false;
/** Whether the path to the current file has so far been logged. */
let hasPathBeenPrinted = false;
/** Absolute path to the current directory or file. */
const path = `${rootPath}/${directoryEntry.name}`;

/**
* @param {string} message
* @param {'error' | 'info'} severity
*/
const log = (message, severity = 'info') => {
if (severity == 'info' && !options.verbose) return;

if (!hasPathBeenPrinted) {
hasPathBeenPrinted = true;
console.log(path);
}

(severity == 'error' ? console.error : console.log)('\t', message);
};

if (directoryEntry.isDirectory() && directoryEntry.name != 'node_modules') {
await processFiles(path);
} else if (options.extensions.some((extension) => directoryEntry.name.endsWith(extension))) {
const file = await open(path, 'r+');

try {
const ast = parse((await file.readFile()).toString(), {parser: typeScriptParser});

for (const node of ast.program.body) {
if ((node.type.startsWith('Export') || node.type.startsWith('Import'))
&& node.source?.value.startsWith('.')) {
const unqualifiedPath = node.source.value;

/** @type {Awaited<ReturnType<stat>>} */
let stats;
for (const suffix of ['', '/index.js', '.js']) {
try {
const qualifiedPath = `${unqualifiedPath}${suffix}`;
stats = await stat(`${rootPath}/${qualifiedPath}`);
if (!stats.isFile() /* is directory */) continue; // try next suffix

if (suffix) { // needs qualification
log(`🛠️ ${unqualifiedPath}${qualifiedPath}`);
node.source.value = qualifiedPath;
hasFileBeenCorrected = true;
} else { // already fully qualified
log(`✔️ ${qualifiedPath}`);
}
break;
} catch (error) {
if (error.code == 'ENOENT' /* no such file or directory */) continue; // try next suffix
throw error;
}
}
if (!stats) log(`❌ ${unqualifiedPath}`, 'error');
}
}

// write modified file
if (hasFileBeenCorrected && !options.dryRun) {
await file.truncate();
await file.write(print(ast, {quote: 'single'}).code, 0);
}
} finally {
await file.close();
}
}
}
}

for (const argument of process.argv.slice(2)) {
switch (argument) {
case '--dry-run': options.dryRun = options.verbose = true; break;
case '--verbose': options.verbose = true; break;
default:
if (argument.startsWith('--extensions=')) {
const extensions = argument.split('=')[1].split(',').filter((extension) => Boolean(extension.trim()));
if (extensions.length) options.extensions = extensions;
} else if (!argument.startsWith('--') && argument.match(/^[^._][^~)('!*]{1,214}$/)) {
options.packages.add(argument);
}
}
}

if (options.packages.size) {
options.packages.forEach(async (packageName) => await processFiles(`./node_modules/${packageName}`));
} else {
console.log(`npx renova [--dry-run] [--extensions=<extension>,...] [--verbose] <package> ...
<package>: Name of a package under ./node_modules to patch, e.g. '@apollo/client'.
--dry-run: Print potential outcome without altering files. Implies --verbose.
--extensions: Comma-separated list of file name extensions to process. Defaults to '.d.ts'.
--verbose: Print all matching exports and imports.`);
}
Loading

0 comments on commit 8c68e88

Please sign in to comment.