Commit 6b1cec5b authored by Anton's avatar Anton Committed by Anton
Browse files

fix: es build

parent b1620ada
# Remember to keep in sync with .npmignore
*.tgz
tsconfig.tsbuildinfo
/.nyc_output/
/.tscache/
/dist
......
......@@ -50,10 +50,11 @@
"!**/*.spec.{js,ts,d.ts}"
],
"scripts": {
"prebuild": "tsc",
"prebuild": "tsc --build src",
"build": "rollup --config rollup.config.js",
"postbuild": "scripts/pkg",
"build:docs": "grunt docs",
"prepack": "npm run build",
"clean": "rm -rf dist public",
"compatibility": "scripts/compatibility.sh",
"debug": "node --inspect ./node_modules/.bin/jest --runInBand --watch --no-coverage",
......
import fs from "fs";
import path from "path";
import { builtinModules } from "module";
import json from "@rollup/plugin-json";
import json from "@rollup/plugin-json"; //native solution coming: https://nodejs.org/docs/latest/api/esm.html#esm_json_modules
import replace from "@rollup/plugin-replace";
import virtual from "@rollup/plugin-virtual";
import copy from "rollup-plugin-copy";
import dts from "rollup-plugin-dts";
import typescript from "@rollup/plugin-typescript";
const packageJson = fs.readFileSync(path.join(__dirname, "package.json"), "utf-8");
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf-8"));
/**
* @typedef {import('rollup').RollupOptions} RollupOptions
......@@ -38,12 +38,17 @@ const inputs = [...entrypoints, ...types];
const external = [
/* nodejs */
...builtinModules,
...builtinModules.map((name) => `node:${name}`), //spec: https://nodejs.org/docs/latest/api/esm.html#esm_node_imports
/* npm dependencies */
...Object.keys(JSON.parse(packageJson).dependencies),
...Object.keys(JSON.parse(packageJson).peerDependencies),
...Object.keys(packageJson.dependencies),
...Object.keys(packageJson.peerDependencies),
];
const jsonConfig = {
preferConst: true,
};
/**
* @param {string} id
* @returns {string|undefined}
......@@ -67,16 +72,35 @@ function manualChunks(id) {
return "core";
}
/**
* @param {string} format
* @returns {string}
*/
function generateResolved(format) {
if (format === "es") {
return `
import path from "path";
import { fileURLToPath } from "node:url";
import { createRequire } from "module";
export const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../");
export const legacyRequire = createRequire(import.meta.url);
export const distFolder = path.resolve(projectRoot, "dist/${format}");
`;
} else {
return `
import path from "path";
export const projectRoot = path.resolve(__dirname, "../../");
export const legacyRequire = require;
export const distFolder = path.resolve(projectRoot, "dist/${format}");
`;
}
}
/**
* @param {string} format
* @returns {RollupOptions[]}
*/
function build(format) {
const resolved = `
import path from "path";
export const projectRoot = path.resolve(__dirname, "../../");
export const distFolder = path.resolve(projectRoot, "dist/${format}");
`;
return [
{
input: entrypoints,
......@@ -90,23 +114,19 @@ function build(format) {
external,
plugins: [
virtual({
"package.json": packageJson,
"src/resolve": resolved,
"src/resolve": generateResolved(format),
}),
typescript({
tsconfig: "src/tsconfig.json",
outDir: `dist/${format}`,
declaration: false,
declarationDir: undefined,
}),
json(),
json(jsonConfig),
replace({
preventAssignment: true,
delimiters: ["", ""],
values: {
/**
* Fix the path from src/package.ts
*/
'"../package.json"': '"../../package.json"',
/**
* Replace __filename global with source filename relative to dist folder
*
......@@ -129,6 +149,17 @@ function build(format) {
chunkFileNames: "[name].d.ts",
},
plugins: [
replace({
preventAssignment: true,
delimiters: ["", ""],
values: {
/**
* Fix the path from dist/types/browser.d.ts
*/
'"../package.json"': '"../../package.json"',
},
}),
json(jsonConfig),
dts(),
copy({
verbose: true,
......
......@@ -15,4 +15,4 @@ export { TransformContext, Transformer, TemplateExtractor } from "./transform";
export { Plugin } from "./plugin";
export { Parser } from "./parser";
export { ruleExists } from "./utils";
export { version } from "./package";
export { version } from "../package.json";
import fs from "fs";
import path from "path";
import { Formatter, Report, Result, UserError, formatterFactory } from "..";
import { legacyRequire } from "../resolve";
type WrappedFormatter = (results: Result[]) => string;
......@@ -27,8 +28,7 @@ function loadFormatter(name: string): Formatter {
}
try {
/* eslint-disable-next-line import/no-dynamic-require */
return require(name);
return legacyRequire(name);
} catch (error) {
throw new UserError(`No formatter named "${name}"`, error);
}
......
......@@ -3,7 +3,7 @@ import path from "path";
import kleur from "kleur";
import minimist from "minimist";
import { TokenDump, SchemaValidationError, UserError, Report, Reporter, Result } from "..";
import * as pkg from "../package";
import { name, version, bugs as pkgBugs } from "../../package.json";
import { eventFormatter } from "./json";
import { CLI } from "./cli";
......@@ -123,8 +123,8 @@ function handleUnknownError(err: Error): void {
console.error(err);
}
console.groupEnd();
const bugUrl = `${pkg.bugs}?issuable_template=Bug`;
console.error(kleur.red(`This is a bug in ${pkg.name}-${pkg.version}.`));
const bugUrl = `${pkgBugs.url}?issuable_template=Bug`;
console.error(kleur.red(`This is a bug in ${name}-${version}.`));
console.error(
kleur.red(
[
......@@ -168,7 +168,7 @@ const argv: minimist.ParsedArgs = minimist(process.argv.slice(2), {
});
function showUsage(): void {
process.stdout.write(`${pkg.name}-${pkg.version}
process.stdout.write(`${name}-${version}
Usage: html-validate [OPTIONS] [FILENAME..] [DIR..]
Common options:
......@@ -204,7 +204,7 @@ e.g. "checkstyle=dist/html-validate.xml"
}
function showVersion(): void {
process.stdout.write(`${pkg.name}-${pkg.version}\n`);
process.stdout.write(`${name}-${version}\n`);
}
if (argv.stdin) {
......
import fs from "fs";
import path from "path";
import Ajv from "ajv";
import ajvSchemaDraft from "ajv/lib/refs/json-schema-draft-06.json";
import deepmerge from "deepmerge";
import { Source } from "../context";
import { NestedError, SchemaValidationError } from "../error";
......@@ -10,7 +11,7 @@ import { Plugin } from "../plugin";
import schema from "../schema/config.json";
import { TransformContext, Transformer, TRANSFORMER_API } from "../transform";
import { requireUncached } from "../utils";
import { projectRoot } from "../resolve";
import { projectRoot, legacyRequire } from "../resolve";
import bundledRules from "../rules";
import { Rule } from "../rule";
import { ConfigData, RuleConfig, RuleOptions, TransformMap } from "./config-data";
......@@ -37,7 +38,7 @@ interface LoadedPlugin extends Plugin {
let rootDirCache: string | null = null;
const ajv = new Ajv({ strict: true, strictTuples: true, strictTypes: true });
ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json"));
ajv.addMetaSchema(ajvSchemaDraft);
const validator = ajv.compile(schema);
......@@ -286,8 +287,7 @@ export class Config {
/* assume it is loadable with require() */
try {
// eslint-disable-next-line security/detect-non-literal-require, import/no-dynamic-require
metaTable.loadFromObject(require(entry));
metaTable.loadFromObject(legacyRequire(entry));
} catch (err) {
throw new ConfigError(`Failed to load elements from "${entry}": ${err.message}`, err);
}
......@@ -358,8 +358,7 @@ export class Config {
private loadPlugins(plugins: string[]): LoadedPlugin[] {
return plugins.map((moduleName: string) => {
try {
// eslint-disable-next-line security/detect-non-literal-require, import/no-dynamic-require
const plugin = require(moduleName.replace("<rootDir>", this.rootDir)) as LoadedPlugin;
const plugin = legacyRequire(moduleName.replace("<rootDir>", this.rootDir)) as LoadedPlugin;
plugin.name = plugin.name || moduleName;
plugin.originalName = moduleName;
return plugin;
......@@ -613,8 +612,7 @@ export class Config {
/* expand <rootDir> */
const moduleName = name.replace("<rootDir>", this.rootDir);
// eslint-disable-next-line security/detect-non-literal-require, import/no-dynamic-require
const fn = require(moduleName);
const fn = legacyRequire(moduleName);
/* sanity check */
if (typeof fn !== "function") {
......
import Ajv, { KeywordDefinition, ValidateFunction } from "ajv";
import ajvSchemaDraft from "ajv/lib/refs/json-schema-draft-06.json";
import { DataValidateFunction, DataValidationCxt, SchemaObject } from "ajv/dist/types";
import deepmerge from "deepmerge";
import jsonMergePatch from "json-merge-patch";
......@@ -208,7 +209,7 @@ export class MetaTable {
*/
private getSchemaValidator(): ValidateFunction<MetaDataTable> {
const ajv = new Ajv({ strict: true, strictTuples: true, strictTypes: true });
ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json"));
ajv.addMetaSchema(ajvSchemaDraft);
ajv.addKeyword(ajvRegexpKeyword);
ajv.addKeyword({ keyword: "copyable" });
return ajv.compile<MetaDataTable>(this.schema);
......
const pkg = require("../package.json");
export const name: string = pkg.name;
export const version: string = pkg.version;
export const homepage: string = pkg.homepage;
export const bugs: string = pkg.bugs.url;
......@@ -7,6 +7,7 @@ import { EventHandler } from "../event";
import { Parser } from "../parser";
import { Rule } from "../rule";
import { Transformer, TRANSFORMER_API } from "../transform";
import { legacyRequire } from "../resolve";
import { Plugin } from "./plugin";
let mockPlugin: Plugin;
......@@ -36,7 +37,7 @@ describe("Plugin", () => {
/* reset mock */
jest.resetModules();
mockPlugin = require("mock-plugin");
mockPlugin = legacyRequire("mock-plugin");
});
it("should throw ConfigError when loading plugin fails", () => {
......
......@@ -6,4 +6,5 @@
import path from "path";
export const projectRoot = path.resolve(__dirname, "..");
export const legacyRequire = require;
export const distFolder = path.join(projectRoot, "src");
import path from "path";
import Ajv, { ErrorObject, SchemaObject, ValidateFunction } from "ajv";
import ajvSchemaDraft from "ajv/lib/refs/json-schema-draft-06.json";
import { homepage } from "../package.json";
import { ConfigData, Severity } from "./config";
import { Location } from "./context";
import { DOMNode } from "./dom";
......@@ -9,7 +11,6 @@ import { Reporter } from "./reporter";
import { MetaTable, MetaLookupableProperty } from "./meta";
import { SchemaValidationError } from "./error";
import { distFolder } from "./resolve";
import { homepage } from "./package";
export { SchemaObject } from "ajv";
......@@ -19,7 +20,7 @@ const remapEvents: Record<string, string> = {
};
const ajv = new Ajv({ strict: true, strictTuples: true, strictTypes: true });
ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json"));
ajv.addMetaSchema(ajvSchemaDraft);
export interface RuleDocumentation {
description: string;
......
import path from "path";
import { Location, sliceLocation } from "../context";
import { NodeType } from "../dom";
import { AttributeEvent, ElementReadyEvent } from "../event";
import { projectRoot } from "../resolve";
import { Rule, RuleDocumentation, ruleDocumentationUrl } from "../rule";
/* eslint-disable-next-line import/no-dynamic-require */
const entities = require(path.join(projectRoot, "elements/entities.json"));
import entities from "../../elements/entities.json";
const regexp = /&([a-z0-9]+|#x?[0-9a-f]+);/gi;
......
......@@ -6,11 +6,11 @@ import fs from "fs";
// eslint-disable-next-line import/no-unresolved
import ESTree from "estree";
import { legacyRequire } from "../resolve";
import { Source } from "../context";
const espree = require("espree");
const walk = require("acorn-walk");
const espree = legacyRequire("espree");
const walk = legacyRequire("acorn-walk");
export interface Position {
line: number;
column: number;
......
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "../dist/",
"composite": false
},
"include": ["./**/*.ts"],
"exclude": ["**/*.spec.ts"],
"files": [],
"references": [{ "path": "../" }]
}
{
"$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
"extends": ["../tsdoc.json"]
}
import semver from "semver";
import kleur from "kleur";
import { version } from "../package";
import { version } from "../../package.json";
export interface CompatibilityOptions {
/** If `true` nothing no output will be generated on console. Default: `false` */
......
import { legacyRequire } from "../resolve";
/**
* Similar to `require(..)` but removes the cached copy first.
*/
export function requireUncached(moduleId: string): any {
const filename = require.resolve(moduleId);
const filename = legacyRequire.resolve(moduleId);
/* remove references from the parent module to prevent memory leak */
const m = require.cache[filename];
const m = legacyRequire.cache[filename];
if (m && m.parent) {
const { parent } = m;
for (let i = parent.children.length - 1; i >= 0; i--) {
......@@ -16,8 +18,7 @@ export function requireUncached(moduleId: string): any {
}
/* remove old module from cache */
delete require.cache[filename];
delete legacyRequire.cache[filename];
// eslint-disable-next-line import/no-dynamic-require
return require(filename);
return legacyRequire(filename);
}
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "dist",
"rootDir": ".",
"outDir": ".",
"emitDeclarationOnly": true,
"declaration": true,
"declarationDir": "dist/types",
"declarationDir": "dist/types/",
"target": "es2017",
"lib": ["es2017"],
......@@ -17,8 +17,8 @@
"noImplicitAny": true,
"resolveJsonModule": true,
"sourceMap": true,
"strict": true
"strict": true,
"composite": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "**/*.spec.ts"]
"files": ["package.json", "elements/entities.json"]
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment