Skip to content

Commit

Permalink
style(*): fix lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jbedard committed Sep 28, 2020
1 parent 5d1921c commit b9b377c
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 54 deletions.
14 changes: 12 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,24 @@
"prettier/@typescript-eslint"
],
"parserOptions": {
"ecmaVersion": 2018
"ecmaVersion": 2018,
"project": "tsconfig.json"
},
"overrides": [
{
"files": [ "test/*.ts" ],
"env": {
"jasmine": true
},
"parserOptions": {
"project": "test/tsconfig.json"
}
}
]
],
"rules": {
// All module boundaries are internal or just for tests
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/prefer-regexp-exec": "off",
"@typescript-eslint/no-var-requires": "off"
}
}
4 changes: 2 additions & 2 deletions .lintstagedrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"src/*.js": ["eslint --fix"],
"test/*.js": ["eslint --fix --env=jasmine"]
"src/*.{ts,js}": ["eslint --fix"],
"test/*.{ts,js}": ["eslint --fix"]
}
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"arrowParens": "avoid",
"htmlWhitespaceSensitivity": "strict",
"trailingComma": "es5"
}

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"build": "tsc",
"clean": "rm -Rf dist/",
"test": "ts-node node_modules/jasmine/bin/jasmine test/*.ts",
"lint": "eslint --fix"
"lint": "eslint --fix {src,test}/*.ts"
},
"husky": {
"hooks": {
Expand Down
81 changes: 44 additions & 37 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
"use strict";

import { Node, TreeAdapter } from "parse5";
import parse5 = require("parse5");
const treeAdapter = require("parse5/lib/tree-adapters/default") as TreeAdapter;

const parse5 = require("parse5");
const treeAdapter: TreeAdapter = require("parse5/lib/tree-adapters/default");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
import crypto = require("crypto");
import fs = require("fs");
import path = require("path");
import mkdirp = require("mkdirp");

const NPM_NAME = "html-insert-assets";

Expand All @@ -17,22 +17,18 @@ const FILE_TYPE_RE = /\.([a-z]+)$/i;
const EXTERNAL_FILE_TYPE_RE = /^[a-z]+:\/\/.*\.([a-z]+)(\?.*)?$/i;
const NOW = String(Date.now());




interface NodeUtils {
toUrl(url: string): string,
body: Node,
head: Node,
toUrl(url: string): string;
body: Node;
head: Node;
}


function fileExtToType(ext: string) {
return ext === "mjs" ? "js" : ext;
}

function computeAssets(assets: string[]) {
return assets.reduce<{[type: string]: string[]}>((map, a) => {
return assets.reduce<{ [type: string]: string[] }>((map, a) => {
const r = a.match(EXTERNAL_FILE_TYPE_RE) || a.match(FILE_TYPE_RE);
const [, ext] = r || ["", "(no ext)"];
const type = fileExtToType(ext.toLowerCase());
Expand Down Expand Up @@ -89,7 +85,11 @@ function readVarArgs(params: string[], i: number): [string[], number] {
return [args, i - 1];
}

function readOptionalParam(params: string[], i: number, defaultValue: string): [string, number] {
function readOptionalParam(
params: string[],
i: number,
defaultValue: string
): [string, number] {
if (i < params.length && !params[i].startsWith("--")) {
return [params[i], i];
}
Expand Down Expand Up @@ -120,7 +120,11 @@ const PRELOAD_TYPES = Object.freeze({
png: "image",
gif: "image",
});
function insertPreloads({ head, toUrl }: NodeUtils, paths: string[], preloadAs: string) {
function insertPreloads(
{ head, toUrl }: NodeUtils,
paths: string[],
preloadAs: string
) {
for (const p of paths) {
const link = treeAdapter.createElement("link", "", [
{ name: "rel", value: "preload" },
Expand All @@ -142,15 +146,13 @@ function parseArgs(cmdParams: string[]) {
let stampType = "hash=8";

const params = cmdParams.reduce<string[]>((a, p) => {
if (p.startsWith("--") && p.match(/^--[a-z]+=/)) {
a.push(...p.split("=", 2));
} else {
a.push(p);
}
return a;
},
[]
);
if (p.startsWith("--") && p.match(/^--[a-z]+=/)) {
a.push(...p.split("=", 2));
} else {
a.push(p);
}
return a;
}, []);

for (let i = 0; i < params.length; i++) {
switch (params[i]) {
Expand Down Expand Up @@ -279,19 +281,21 @@ function insertFavicons({ head, toUrl }: NodeUtils, paths: string[]) {

function createLogger(verbose: boolean) {
if (!verbose) {
return () => {};
return () => {
/* noop */
};
}

return function logger(str: string, ...args: any[]) {
return function logger(str: string, ...args: unknown[]) {
console.log(`${NPM_NAME}: ${str}`, ...args);
};
}

function warn(str: string, ...args: any[]) {
function warn(str: string, ...args: unknown[]) {
console.warn(`${NPM_NAME}: ${str}`, ...args);
}

function newError(str: string, ...args: any[]) {
function newError(str: string, ...args: unknown[]) {
return new Error(`${NPM_NAME}: ${str} ${args.join(" ")}`.trim());
}

Expand Down Expand Up @@ -338,10 +342,10 @@ function createStamper(typeParam: string): (f: string) => string {
return () => NOW.slice(-value);

case "lastmod":
return (f) => fileLastModified(f).slice(-value);
return f => fileLastModified(f).slice(-value);

case "hash":
return (f) => hashFile(f).slice(-value);
return f => hashFile(f).slice(-value);

default:
throw newError(`Invalid stamp type: ${typeParam}`);
Expand Down Expand Up @@ -380,7 +384,9 @@ function main(params: string[], write = mkdirpWrite) {

const document = parse5.parse(
fs.readFileSync(inputFile, { encoding: "utf-8" }),
{ treeAdapter }
{
treeAdapter,
}
);

const body = findElementByName(document, "body");
Expand Down Expand Up @@ -451,9 +457,11 @@ function main(params: string[], write = mkdirpWrite) {

// Insertion of various asset preload types
for (const [type, prePaths] of Object.entries(preloadAssets)) {
if (PRELOAD_TYPES.hasOwnProperty(type)) {
if (type in PRELOAD_TYPES) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
insertPreloads(utils, prePaths, (PRELOAD_TYPES as any)[type]);
} else if (strict) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw newError(`Unknown preload type(${type}), paths(${prePaths})`);
}
}
Expand All @@ -474,7 +482,7 @@ function main(params: string[], write = mkdirpWrite) {
break;

default:
// eslint-disable-next-line no-case-declarations
// eslint-disable-next-line no-case-declarations, @typescript-eslint/restrict-template-expressions
const msg = `Unknown asset type(${type}), paths(${paths})`;
if (strict) {
throw newError(msg);
Expand All @@ -492,7 +500,6 @@ function main(params: string[], write = mkdirpWrite) {
export {
parseArgs,
main,

// For testing
NOW as __NOW
};
NOW as __NOW,
};
20 changes: 8 additions & 12 deletions test/spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";

const path = require("path");
const { main, parseArgs, __NOW } = require("../src/main");
import path = require("path");
import { main, parseArgs, __NOW } from "../src/main";

const inFile = "./test/data/index-template.html";
const inFileHTML5 = "./test/data/index-html5-template.html";
Expand All @@ -19,7 +19,7 @@ const CSS_ASSET_RESET = "./test/data/assets/reset.css";
const CSS_ASSET_RESET_HASH = "D3C2hyvo84Oc7dvX3WUThJ6oUl4"; // original: "D3C2hyvo84Oc7dvX3WUThJ6oUl4=";

let output = "";
function write(_: any, content: string) {
function write(_: string, content: string) {
output = content;
}

Expand All @@ -44,7 +44,9 @@ describe("base", () => {

it("should noop when no assets with html5 template", () => {
expect(mainTest(["--out", "index.html", "--html", inFileHTML5])).toBe(0);
expect(output).toBe("<!DOCTYPE html><html><head></head><body></body></html>");
expect(output).toBe(
"<!DOCTYPE html><html><head></head><body></body></html>"
);
});

it("should normalize asset paths", () => {
Expand Down Expand Up @@ -174,14 +176,7 @@ describe("base", () => {

describe("js assets", () => {
it("should inject js assets as <script> tags", () => {
mainTest([
"--out",
"index.html",
"--html",
inFile,
"--assets",
"a.js",
]);
mainTest(["--out", "index.html", "--html", inFile, "--assets", "a.js"]);
expect(output).toMatch(/<script.*\.\/a\.js/);
});

Expand Down Expand Up @@ -1057,6 +1052,7 @@ describe("stamping", () => {
expect(/\/alert\.js\?v=\d{13}"/.test(output)).toBeTrue();
expect(/\/answer\.mjs\?v=\d{13}"/.test(output)).toBeTrue();

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(output.match(/\/reset\.css\?v=(\d{13})"/)![0]).not.toBe(__NOW);
});

Expand Down
9 changes: 9 additions & 0 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "@tsconfig/node10/tsconfig.json",

"include": ["*.ts"],
"compilerOptions": {
"declaration": false,
"noImplicitAny": true,
}
}

0 comments on commit b9b377c

Please sign in to comment.