Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve imported module IDs without Rollup. #6694

Merged
merged 4 commits into from
Jul 24, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions config/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import * as path from "path";
import * as recast from "recast";
import * as parser from "recast/parsers/babel";
import glob = require("glob");

export const distDir = path.resolve(__dirname, "..", "dist");

export function eachFile(dir: string, callback: (
absPath: string,
relPath: string,
) => any) {
const promises: Promise<any>[] = [];

return new Promise((resolve, reject) => {
glob(`${dir}/**/*.js`, (error, files) => {
if (error) return reject(error);

files.sort().forEach(file => {
const relPath = path.relative(dir, file);

// Outside the distDir, somehow.
if (relPath.startsWith("../")) return;

// Avoid re-transforming CommonJS bundle files.
if (relPath.endsWith(".cjs.js")) return;

// Avoid re-transforming CommonJS bundle files.
if (relPath.endsWith(".min.js")) return;

// This file is not meant to be imported or processed.
if (relPath.endsWith("invariantErrorCodes.js")) return;

promises.push(new Promise(resolve => {
resolve(callback(file, relPath));
}));
});

resolve();
});
}).then(() => Promise.all(promises));
}

export function reparse(source: string) {
return recast.parse(source, { parser });
}

export function reprint(ast: ReturnType<typeof reparse>) {
return recast.print(ast).code;
}
36 changes: 10 additions & 26 deletions config/processInvariants.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,14 @@
import * as fs from "fs";
import * as path from "path";
import glob = require("glob");

const distDir = path.resolve(__dirname, "..", "dist");

glob(`${distDir}/**/*.js`, (error, files) => {
if (error) throw error;

files.sort().forEach(file => {
const relPath = path.relative(distDir, file);

// Outside the distDir, somehow.
if (relPath.startsWith("../")) return;

// Avoid re-transforming CommonJS bundle files.
if (relPath.endsWith(".cjs.js")) return;

const source = fs.readFileSync(file, "utf8");
const output = transform(source, relPath);
if (source !== output) {
console.log("transformed invariants in " + relPath);
fs.writeFileSync(file, output, "utf8");
}
});
import { distDir, eachFile, reparse, reprint } from './helpers';

eachFile(distDir, (file, relPath) => {
const source = fs.readFileSync(file, "utf8");
const output = transform(source, relPath);
if (source !== output) {
fs.writeFileSync(file, output, "utf8");
}
}).then(() => {
fs.writeFileSync(
path.join(distDir, "invariantErrorCodes.js"),
recast.print(errorCodeManifest, {
Expand All @@ -33,7 +18,6 @@ glob(`${distDir}/**/*.js`, (error, files) => {
});

import * as recast from "recast";
import * as parser from "recast/parsers/babel";
const b = recast.types.builders;
const n = recast.types.namedTypes;
type Node = recast.types.namedTypes.Node;
Expand Down Expand Up @@ -79,7 +63,7 @@ function transform(code: string, file: string) {
return code;
}

const ast = recast.parse(code, { parser });
const ast = reparse(code);

recast.visit(ast, {
visitCallExpression(path) {
Expand Down Expand Up @@ -136,7 +120,7 @@ function transform(code: string, file: string) {
}
});

return recast.print(ast).code;
return reprint(ast);
}

function isIdWithName(node: Node, ...names: string[]) {
Expand Down
81 changes: 81 additions & 0 deletions config/resolveModuleIds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import * as fs from "fs";
import * as path from "path";
import resolve from "resolve";
import { distDir, eachFile, reparse, reprint } from './helpers';

eachFile(distDir, (file, relPath) => new Promise((resolve, reject) => {
fs.readFile(file, "utf8", (error, source) => {
if (error) return reject(error);
const output = transform(source, file);
if (source === output) {
resolve(file);
} else {
fs.writeFile(file, output, "utf8", error => {
error ? reject(error) : resolve(file);
});
}
});
}));

import * as recast from "recast";
const n = recast.types.namedTypes;
type Node = recast.types.namedTypes.Node;

function transform(code: string, file: string) {
const ast = reparse(code);

recast.visit(ast, {
visitImportDeclaration(path) {
this.traverse(path);
normalizeSourceString(file, path.node.source);
},

visitImportExpression(path) {
this.traverse(path);
normalizeSourceString(file, path.node.source);
},

visitExportAllDeclaration(path) {
this.traverse(path);
normalizeSourceString(file, path.node.source);
},

visitExportNamedDeclaration(path) {
this.traverse(path);
normalizeSourceString(file, path.node.source);
},
});

return reprint(ast);
}

function isRelative(id: string) {
return id.startsWith("./") || id.startsWith("../");
}

function normalizeSourceString(file: string, source?: Node | null) {
if (source && n.StringLiteral.check(source) && isRelative(source.value)) {
try {
source.value = normalizeId(source.value, file);
} catch (error) {
console.error(`Failed to resolve ${source.value} in ${file}`);
process.exit(1);
}
}
}

function normalizeId(id: string, file: string) {
const basedir = path.dirname(file);
const absPath = resolve.sync(id, {
basedir,
packageFilter(pkg) {
return pkg.module ? {
...pkg,
main: pkg.module,
} : pkg;
},
});
const relPath = path.relative(basedir, absPath);
const relId = relPath.split(path.sep).join('/');
return isRelative(relId) ? relId : "./" + relId;
}
25 changes: 0 additions & 25 deletions config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,30 +93,6 @@ function prepareBundle({
};
}

// Resolve indirect imports and exports to the original exporting module,
// so that more imports are explicitly named (fewer *s), and all source
// module identifiers have file extensions.
function resolveESMImportsAndFileExtensions(input, outputDir) {
return {
input,
external(id) {
return externalPackages.has(id);
},
output: {
dir: outputDir,
format: 'esm',
sourcemap: true,
},
// By setting preserveModules to true, we're making sure Rollup
// doesn't attempt to create a single combined ESM bundle with the
// final result of running this job.
preserveModules: true,
plugins: [
nodeResolve(),
],
};
}

export default [
...entryPoints.map(prepareBundle),
// Convert the ESM entry point to a single CJS bundle.
Expand All @@ -128,5 +104,4 @@ export default [
prepareCJSMinified(
'./dist/apollo-client.cjs.js',
),
resolveESMImportsAndFileExtensions(packageJson.module, distDir),
];
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,20 @@
"homepage": "https://www.apollographql.com",
"scripts": {
"prebuild": "npm run clean",
"build": "tsc && ts-node-script config/processInvariants.ts",
"postbuild": "npm run bundle && npm run prepdist",
"build": "tsc",
"postbuild": "npm run invariants && npm run rollup && npm run prepdist && npm run resolve",
"invariants": "ts-node-script config/processInvariants.ts",
"rollup": "rollup -c ./config/rollup.config.js",
"prepdist": "node ./config/prepareDist.js",
"resolve": "ts-node-script config/resolveModuleIds.ts",
"watch": "tsc-watch --onSuccess \"npm run postbuild\"",
"clean": "rimraf -r dist coverage lib",
"test": "jest --config ./config/jest.config.js",
"test:debug": "BABEL_ENV=server node --inspect-brk node_modules/.bin/jest --config ./config/jest.config.js --runInBand",
"test:ci": "npm run coverage -- --ci --maxWorkers=2 --reporters=default --reporters=jest-junit",
"test:watch": "jest --config ./config/jest.config.js --watch",
"bundle": "rollup -c ./config/rollup.config.js",
"coverage": "jest --config ./config/jest.config.js --verbose --coverage",
"bundlesize": "npm run build && bundlesize",
"prepdist": "node ./config/prepareDist.js",
"predeploy": "npm run build",
"deploy": "cd dist && npm publish --tag beta"
},
Expand Down Expand Up @@ -105,6 +107,7 @@
"react-dom": "^16.13.1",
"recast": "0.19.1",
"recompose": "^0.30.0",
"resolve": "^1.17.0",
"rimraf": "3.0.2",
"rollup": "1.31.1",
"rollup-plugin-terser": "5.1.3",
Expand Down