Skip to content

Commit

Permalink
style(eslint): lint TypeScript + fix issues (#7454)
Browse files Browse the repository at this point in the history
* chore: enable ESLinting on Typescript
* style(eslint): fix some issues in TypeScript
* style(eslint): remove unused imports
* style(eslint): extract GetFlawsFunction type
* style(eslint): type tryOrExit param
* style(eslint): remove unused eslint-disable comments
* style(eslint): use Record<string, never> for empty object
* style(eslint): remove unused variable
* style(eslint): improve memoize() type
* style(eslint): avoid calling hasOwnProperty() directly
* refactor(tool/cli): extend ActionParameters
* ci(workflows/testing): install lambda dependencies
* style(eslint): enable no-{missing-require,unpublished-import}
* style(eslint): disable no-unpublished-import again

Co-authored-by: Claas Augner <[email protected]>
  • Loading branch information
nschonni and caugner authored Nov 11, 2022
1 parent 3a49ab1 commit 837e5d0
Show file tree
Hide file tree
Showing 26 changed files with 345 additions and 276 deletions.
12 changes: 12 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@ module.exports = {
},
reportUnusedDisableDirectives: true,
overrides: [
{
files: ["**/*.ts", "**/*.tsx"],
parser: "@typescript-eslint/parser",
extends: ["plugin:@typescript-eslint/recommended"],
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-var-requires": "off",
"n/no-missing-import": "off",
"n/no-unpublished-import": "off",
"n/shebang": "off",
},
},
{
files: ["testing/**/*.js"],
globals: {
Expand Down
20 changes: 19 additions & 1 deletion .github/workflows/testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,26 @@ jobs:
with:
node-version: "16"
cache: yarn
cache-dependency-path: |
yarn.lock
deployer/aws-lambda/content-origin-request/yarn.lock
deployer/aws-lambda/content-origin-response/yarn.lock
deployer/aws-lambda/tests/yarn.lock
libs/**/*.js
- name: Install all yarn packages (ROOT)
run: yarn --frozen-lockfile

- name: Install all yarn packages
- name: Install all yarn packages (aws-lambda/content-origin-request)
working-directory: deployer/aws-lambda/content-origin-request
run: yarn --frozen-lockfile

- name: Install all yarn packages (aws-lambda/content-origin-response)
working-directory: deployer/aws-lambda/content-origin-response
run: yarn --frozen-lockfile

- name: Install all yarn packages (aws-lambda/tests)
working-directory: deployer/aws-lambda/tests
run: yarn --frozen-lockfile

- name: Lint prettier
Expand Down
4 changes: 2 additions & 2 deletions build/check-images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function checkImageReferences(doc, $, options, { url, rawContent }) {
// it now, we still want the full relative URL.
img.attr("src", absoluteURL.pathname);
} else {
let suggestion = null;
const suggestion = null;
addImageFlaw(img, src, {
explanation: "External image URL",
externalImage: true,
Expand All @@ -138,7 +138,7 @@ export function checkImageReferences(doc, $, options, { url, rawContent }) {

// What follows uses the same algorithm as Image.findByURLWithFallback
// but only adds a filePath if it exists for the DEFAULT_LOCALE
let filePath = Image.findByURL(finalSrc);
const filePath = Image.findByURL(finalSrc);
let enUSFallback = false;
if (
!filePath &&
Expand Down
3 changes: 1 addition & 2 deletions build/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { prompt } from "inquirer";
import { Document, slugToFolder, translationsOf } from "../content";
import { CONTENT_ROOT, CONTENT_TRANSLATED_ROOT } from "../libs/env";
import { VALID_LOCALES } from "../libs/constants";
// eslint-disable-next-line n/no-missing-require
import { renderHTML } from "../ssr/dist/main";
import options from "./build-options";
import { buildDocument, BuiltDocument, renderContributorsTxt } from ".";
Expand All @@ -26,7 +25,7 @@ import { humanFileSize } from "./utils";
export type DocumentBuild = SkippedDocumentBuild | InteractiveDocumentBuild;

export interface SkippedDocumentBuild {
doc: {};
doc: Record<string, never>;
skip: true;
}

Expand Down
9 changes: 4 additions & 5 deletions build/document-extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
Section,
SpecificationsSection,
} from "../libs/types";
import { BuiltDocument } from ".";
import specs from "browser-specs";
import web from "../kumascript/src/api/web";

Expand Down Expand Up @@ -357,9 +356,9 @@ function _addSingleSpecialSection(
}
}

let dataQuery: string = "";
let dataQuery = "";
let hasMultipleQueries = false;
let specURLsString: string = "";
let specURLsString = "";
let specialSectionType: string | null = null;
if ($.find("div.bc-data").length) {
specialSectionType = "browser_compatibility";
Expand Down Expand Up @@ -448,7 +447,7 @@ function _addSingleSpecialSection(
}

for (const block of _extractCompatBlocks(data)) {
for (let [browser, originalInfo] of Object.entries(block.support)) {
for (const [browser, originalInfo] of Object.entries(block.support)) {
// `originalInfo` here will be one of the following:
// - a single simple_support_statement:
// { version_added: 42 }
Expand Down Expand Up @@ -695,7 +694,7 @@ function _addSectionProse(
): SectionsAndFlaws {
let id: string | null = null;
let title: string | null = null;
let titleAsText: string = "";
let titleAsText = "";
let isH3 = false;

const flaws: string[] = [];
Expand Down
2 changes: 1 addition & 1 deletion build/flaws/broken-links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ export function getBrokenLinksFlaws(doc, $, { rawContent }, level) {
`/${doc.locale}/`,
`/${DEFAULT_LOCALE}/`
);
let enUSFound = Document.findByURL(enUSHrefNormalized);
const enUSFound = Document.findByURL(enUSHrefNormalized);
if (enUSFound) {
enUSFallbackURL = enUSFound.url;
} else {
Expand Down
4 changes: 3 additions & 1 deletion build/flaws/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ export interface Flaw {
difference?: any;
}

type GetFlawsFunction = (doc: any, $: any, document: any, level: any) => Flaw[];

export function injectFlaws(doc, $, options, document) {
const flawChecks: Array<[string, Function, boolean]> = [
const flawChecks: Array<[string, GetFlawsFunction, boolean]> = [
["unsafe_html", getUnsafeHTMLFlaws, false],
["broken_links", getBrokenLinksFlaws, true],
["bad_bcd_queries", getBadBCDQueriesFlaws, false],
Expand Down
4 changes: 3 additions & 1 deletion build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,9 @@ export async function buildDocument(
$,
document.rawBody
);
for (let { id, html, flaw } of liveSamplePages) {
for (const liveSamplePage of liveSamplePages) {
const { id, flaw } = liveSamplePage;
let { html } = liveSamplePage;
if (flaw) {
flaw.updateFileInfo(fileInfo);
if (flaw.name === "MacroLiveSampleError") {
Expand Down
3 changes: 1 addition & 2 deletions build/spas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
} from "../libs/env";
import { isValidLocale } from "../libs/locale-utils";
import { DocFrontmatter } from "../libs/types/document";
// eslint-disable-next-line n/no-missing-require
import { renderHTML } from "../ssr/dist/main";
import got from "got";
import { splitSections } from "./utils";
Expand Down Expand Up @@ -256,7 +255,7 @@ export async function buildSPAs(options) {
continue;
}

let featuredContributor = contributorSpotlightRoot
const featuredContributor = contributorSpotlightRoot
? await buildContributorSpotlight(locale, options)
: null;

Expand Down
6 changes: 5 additions & 1 deletion content/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
execGit,
urlToFolderPath,
toPrettyJSON,
MEMOIZE_INVALIDATE,
} from "./utils";
export { urlToFolderPath, MEMOIZE_INVALIDATE } from "./utils";
import * as Redirect from "./redirect";
Expand Down Expand Up @@ -423,7 +424,10 @@ export function update(url: string, rawBody: string, metadata) {
}
}

export function findByURL(url: string, ...args: (string | Symbol)[]) {
export function findByURL(
url: string,
...args: (string | typeof MEMOIZE_INVALIDATE)[]
) {
const [bareURL, hash = ""] = url.split("#", 2);
if (!bareURL.toLowerCase().includes("/docs/")) {
return;
Expand Down
2 changes: 1 addition & 1 deletion content/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function urlToFilePath(url) {
return path.join(locale.toLowerCase(), slugToFolder(slugParts.join("/")));
}

const find = memoize((relativePath) => {
const find = memoize((relativePath: string) => {
return ROOTS.map((root) => path.join(root, relativePath)).find(
(filePath) => fs.existsSync(filePath) && isImage(filePath)
);
Expand Down
2 changes: 1 addition & 1 deletion content/redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ function loadLocaleAndAdd(
validatePairs(updatePairs, locale, strict);

locale = locale.toLowerCase();
let root = getRoot(
const root = getRoot(
locale,
`trying to add redirects for ${locale} but CONTENT_TRANSLATED_ROOT not set`
);
Expand Down
10 changes: 6 additions & 4 deletions content/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function buildURL(locale, slug) {
return `/${locale}/docs/${slug}`;
}

function isPromise(p) {
function isPromise(p): p is Promise<unknown> {
return p && Object.prototype.toString.call(p) === "[object Promise]";
}

Expand All @@ -33,13 +33,15 @@ function isPromise(p) {
* Note: The parameter are turned into a cache key quite naively, so
* different object key order would lead to new cache entries.
*/
export function memoize(fn: Function): Function {
export function memoize<Args>(
fn: (...args: Args[]) => any
): (...args: (Args | typeof MEMOIZE_INVALIDATE)[]) => any {
if (process.env.NODE_ENV !== "production") {
return fn;
}

const cache = new LRU({ max: 2000 });
return (...args) => {
return (...args: (Args | typeof MEMOIZE_INVALIDATE)[]) => {
let invalidate = false;
if (args.includes(MEMOIZE_INVALIDATE)) {
args.splice(args.indexOf(MEMOIZE_INVALIDATE), 1);
Expand All @@ -55,7 +57,7 @@ export function memoize(fn: Function): Function {
}
}

const value = fn(...args);
const value = fn(...(args as Args[]));
if (isPromise(value)) {
return value.then((actualValue) => {
cache.set(key, actualValue);
Expand Down
2 changes: 0 additions & 2 deletions deployer/aws-lambda/content-origin-request/build.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable n/no-unpublished-require */
/* eslint-disable n/no-missing-require */
const { VALID_LOCALES } = require("@yari-internal/constants");
const fs = require("fs");
const path = require("path");
Expand Down
1 change: 0 additions & 1 deletion deployer/aws-lambda/content-origin-response/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable n/no-missing-require */
const { CSP_VALUE } = require("@yari-internal/constants");

exports.handler = async (event) => {
Expand Down
2 changes: 0 additions & 2 deletions deployer/aws-lambda/tests/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable n/no-unpublished-require */
/* eslint-disable n/no-missing-require */
const polka = require("polka");
const kleur = require("kleur");

Expand Down
1 change: 0 additions & 1 deletion deployer/aws-lambda/tests/server.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable n/no-unpublished-require */
const got = require("got");

const BASE_URL = process.env.SERVER_BASE_URL || "http://localhost:7000";
Expand Down
2 changes: 1 addition & 1 deletion filecheck/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ program
}
return runChecker(allFilePaths, options).catch((error) => {
console.error(error);
process.exit(1);
throw error;
});
});

Expand Down
2 changes: 1 addition & 1 deletion kumascript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const renderCache = new LRU<string, unknown>({ max: 2000 });

interface RenderOptions {
urlsSeen?: Set<string>;
selective_mode?: [boolean, string[]] | false;
selective_mode?: [string, string[]] | false;
invalidateCache?: boolean;
}

Expand Down
1 change: 1 addition & 0 deletions kumascript/tests/environment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ describe("Environment class", () => {
});

it("defines a template() function that renders templates", async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const mockRender = jest.fn((a, b) => "hello world");
const mockTemplates = { render: mockRender };
const environment = new Environment({}, mockTemplates);
Expand Down
2 changes: 1 addition & 1 deletion kumascript/tests/macros/httpheader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describeMacro("httpheader", function () {
);
});
itMacro("One unknown argument (en-US)", function (macro) {
macro.ctx.wiki.getPage = jest.fn(() => {});
macro.ctx.wiki.getPage = jest.fn();
return assert.eventually.equal(
macro.call("fleetwood-mac"),
`<a href="/en-US/docs/Web/HTTP/Headers/fleetwood-mac"><code>fleetwood-mac</code></a>`
Expand Down
4 changes: 2 additions & 2 deletions markdown/m2h/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ interface CliOptions {
verbose?: boolean;
}

function tryOrExit(f: Function) {
function tryOrExit(f: ({ options, ...args }) => Promise<void>) {
return async ({ options = {}, ...args }: { options: CliOptions }) => {
try {
await f({ options, ...args });
Expand Down Expand Up @@ -51,7 +51,7 @@ program
folderSearch: args.folder,
locales: buildLocaleMap(options.locale),
});
for (let doc of all.iter()) {
for (const doc of all.iter()) {
if (!doc.isMarkdown) {
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion markdown/m2h/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function getL10nCardMap(locale = DEFAULT_LOCALE) {
const listMsgObj = JSON.parse(fs.readFileSync(localeFilePath, "utf-8"))[
"translations"
][""];
let l10nCardMap = new Map();
const l10nCardMap = new Map();

Object.keys(listMsgObj).forEach((msgName) => {
l10nCardMap.set(
Expand Down
4 changes: 0 additions & 4 deletions server/react-app.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />

declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: "development" | "production" | "test";
Expand Down
4 changes: 2 additions & 2 deletions server/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,8 @@ app.get("/api/v1/plus/collection/", async (req, res) => {
// Return all (paginated)
const page = parseInt((req.query.page as string) || "1", 10);
const pageSize = 5;
let m = 0;
let n = pageSize;
const m = 0;
const n = pageSize;
res.json({
items: bookmarks.slice(m, n).map((bookmark) => {
return {
Expand Down
Loading

0 comments on commit 837e5d0

Please sign in to comment.