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

Publish native ES modules #668

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
16 changes: 8 additions & 8 deletions .eslintrc.js → .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'script',
ecmaVersion: 2019,
sourceType: 'module',
},
plugins: ['prettier', 'node'],
extends: ['eslint:recommended', 'plugin:node/recommended', 'prettier'],
env: {
node: true,
},
rules: {
// these are disabled because the import statements have to use `.js` extension,
// but eslint-plugin-node can only see `.ts` files (so it flags them as missing)
'node/no-missing-import': 'off',
'node/no-unpublished-import': 'off',

'node/no-unsupported-features/es-syntax': ['error', { ignores: ['dynamicImport', 'modules'] }],
'prettier/prettier': 'error',
},

Expand All @@ -18,10 +24,6 @@ module.exports = {
files: ['**/*.ts'],

parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
},

plugins: ['@typescript-eslint'],
extends: ['plugin:@typescript-eslint/recommended'],
Expand All @@ -39,8 +41,6 @@ module.exports = {
},

rules: {
'node/no-unsupported-features/es-syntax': ['error', { ignores: ['modules'] }],

// we should work to remove these overrides
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-use-before-define': 'off',
Expand Down
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 100
}
7 changes: 0 additions & 7 deletions .prettierrc.js

This file was deleted.

6 changes: 3 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
preset: 'ts-jest',
export default {
transform: {},
testEnvironment: 'node',
roots: ['<rootDir>/src/'],
roots: ['<rootDir>/lib/'],
};
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@
"lib/",
"!lib/**/*.test.*"
],
"type": "module",
"scripts": {
"build": "tsc",
"lint": "npm-run-all lint:*",
"lint:files": "eslint .",
"lint:tsc": "tsc --noEmit",
"prepare": "tsc",
"release": "release-it",
"test": "npm-run-all lint test:*",
"test:jest": "jest"
"test": "npm-run-all lint build test:*",
"test:jest": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js"
},
"dependencies": {
"@glimmer/reference": "^0.82.0",
Expand Down Expand Up @@ -62,7 +63,6 @@
"prettier": "^2.4.1",
"release-it": "^14.11.6",
"release-it-lerna-changelog": "^4.0.1",
"ts-jest": "^26.5.6",
"typescript": "~4.4.4"
},
"engines": {
Expand Down
11 changes: 8 additions & 3 deletions src/bin.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import * as path from 'path';
import { existsSync } from 'fs';
import { fileURLToPath } from 'url';
import execa from 'execa';
import { join } from 'path';
import { createTempDir, TempDir } from 'broccoli-test-helper';
import slash from 'slash';

const COMPILED_BIN_PATH = path.join(__dirname, '../lib/bin.js');
const COMPILED_BIN_PATH = fileURLToPath(new URL('./bin.js', import.meta.url));

if (!existsSync(COMPILED_BIN_PATH)) {
throw new Error('Missing compiled output, run `yarn build`!');
throw new Error(
`Missing compiled output, run \`yarn build\`! Looked at ${COMPILED_BIN_PATH} (based on ${
import.meta.url
})`
);
}

function run(args: string[], cwd: string) {
Expand Down
12 changes: 9 additions & 3 deletions src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
#!/usr/bin/env node

import * as os from 'os';
import { readFileSync } from 'fs';
import { program } from 'commander';
import run from './runner';
import run from './runner.js';
import { pathToFileURL } from 'url';

const version = JSON.parse(
readFileSync(new URL('../package.json', import.meta.url), { encoding: 'utf-8' })
);
program
.version(require('../package').version)
.version(version)
.usage('<files> -t transform-plugin.js')
.option(
'-t, --transform <file>',
Expand All @@ -32,5 +37,6 @@ if (program.args.length < 1 || !programOptions.transform) {
silent: programOptions.silent,
};

run(programOptions.transform, program.args, options);
const transformPath = pathToFileURL(programOptions.transform);
run(transformPath, program.args, options);
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { traverse, builders, Walker, print as glimmerPrint } from '@glimmer/syntax';
import type { ASTv1 as AST, NodeVisitor } from '@glimmer/syntax';
import ParseResult, { NodeInfo } from './parse-result';
import ParseResult, { NodeInfo } from './parse-result.js';

const PARSE_RESULT_FOR = new WeakMap<AST.Node, ParseResult>();
const NODE_INFO = new WeakMap<AST.Node, NodeInfo>();
Expand Down Expand Up @@ -143,4 +143,4 @@ export function transform(
export type { AST, NodeVisitor } from '@glimmer/syntax';

export { builders, traverse } from '@glimmer/syntax';
export { sourceForLoc } from './utils';
export { sourceForLoc } from './utils.js';
2 changes: 1 addition & 1 deletion src/parse-result.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { preprocess, builders, print as _print, traverse, ASTv1 as AST } from '@glimmer/syntax';
import { getLines, sortByLoc, sourceForLoc } from './utils';
import { getLines, sortByLoc, sourceForLoc } from './utils.js';

const leadingWhitespace = /(^\s+)/;
const attrNodeParts = /(^[^=]+)(\s+)?(=)?(\s+)?(['"])?(\S+)?/;
Expand Down
30 changes: 17 additions & 13 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as http from 'http';
import * as https from 'https';
import { writeFileSync } from 'fs';
import { resolve } from 'path';
import colors from 'colors/safe';
import colors from 'colors/safe.js';
import slash from 'slash';
import globby from 'globby';
import ora from 'ora';
Expand All @@ -12,6 +12,9 @@ import workerpool from 'workerpool';

tmp.setGracefulCleanup();

import { fileURLToPath } from 'url';
const WORKER_PATH = fileURLToPath(new URL('./worker.js', import.meta.url));

class NoFilesError extends Error {}

class SilentLogger {
Expand Down Expand Up @@ -119,7 +122,7 @@ class StatsCollector {
}

export default async function run(
transformFile: string,
transformFile: URL,
filePaths: string[],
options: { silent?: boolean; cpus: number }
): Promise<void> {
Expand Down Expand Up @@ -149,11 +152,11 @@ export default async function run(
/**
* Returns the location of the transform module on disk.
*/
async function loadTransform(transformFile: string): Promise<string> {
const isRemote = transformFile.startsWith('http');
async function loadTransform(transformFile: URL): Promise<string> {
const isLocal = transformFile.protocol === 'file:';

if (!isRemote) {
return resolve(process.cwd(), transformFile);
if (isLocal) {
return fileURLToPath(transformFile);
}

const contents = await downloadFile(transformFile);
Expand All @@ -164,9 +167,9 @@ async function loadTransform(transformFile: string): Promise<string> {
return filePath.name;
}

function downloadFile(url: string): Promise<string> {
function downloadFile(url: URL): Promise<string> {
return new Promise((resolve, reject) => {
const transport = url.startsWith('https') ? https : http;
const transport = url.protocol === 'https:' ? https : http;

let contents = '';
transport
Expand Down Expand Up @@ -219,7 +222,7 @@ async function spawnWorkers(

logger.spin('Processed 0 files');

const pool = workerpool.pool(require.resolve('./worker'), { maxWorkers: cpus });
const pool = workerpool.pool(WORKER_PATH, { maxWorkers: cpus });

let i = 0;
const worker = (queue as any).async.asyncify(async (file: string) => {
Expand All @@ -238,13 +241,14 @@ async function spawnWorkers(

function handleError(err: any, logger: Logger): void {
if (err.code === 'MODULE_NOT_FOUND') {
logger.error('Transform plugin not found');
logger.error(`Transform plugin not found`);
} else if (err instanceof NoFilesError) {
logger.error('No files matched');
} else {
logger.error(err);
if (err.stack) {
logger.error(err.stack);
}
}

if (err.stack) {
logger.error(err.stack);
}
}
4 changes: 2 additions & 2 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as fs from 'fs';
import workerpool from 'workerpool';
import { transform } from './index';
import { transform } from './index.js';
import type { TransformPluginBuilder } from './index';

interface TransformResult {
Expand All @@ -14,7 +14,7 @@ interface TransformOptions {
}

async function run(transformPath: string, filePath: string, options: TransformOptions) {
const module = require(transformPath);
const module = await import(transformPath);
const plugin: TransformPluginBuilder =
typeof module.default === 'function' ? module.default : module;

Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"declarationMap": true,
"sourceMap": true,
"target": "es2018",
"module": "commonjs",
"module": "es2020",
"moduleResolution": "Node",
"strict": true,
"esModuleInterop": true,
"outDir": "./lib",
Expand Down
Loading