Skip to content

Commit

Permalink
chore: fix linting errors (#116)
Browse files Browse the repository at this point in the history
* chore: fix linting errors

* chore: fix linting errors

* chore: add general eslint override for test files

* chore: switch fs promises to fs-extra so tests lint correctly
  • Loading branch information
orinokai committed Apr 14, 2022
1 parent aa21da6 commit 5b9d6a3
Show file tree
Hide file tree
Showing 8 changed files with 1,798 additions and 1,812 deletions.
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,14 @@ module.exports = {
env: {
jest: true,
},
overrides: [
{
// Tests use lots of nested callbacks
files: ['**/__tests__/*.ts'],
rules: {
'max-nested-callbacks': 'off',
'import/first': 'off',
},
},
],
}
6 changes: 4 additions & 2 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const rules = require('@netlify/eslint-config-node/.prettierrc.json')

module.exports = {
...require("@netlify/eslint-config-node/.prettierrc.json"),
endOfLine: "auto",
...rules,
endOfLine: 'auto',
}
43 changes: 19 additions & 24 deletions src/__tests__/gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,25 @@
jest.mock('../plugin-data', () => {
return {
__esModule: true,
default: jest.fn().mockReturnValue({
publicFolder: jest.fn().mockReturnValue('mock-file-path'),
}),
}
})
jest.mock('../build-headers-program', () => {
return {
__esModule: true,
default: jest.fn(),
}
})
jest.mock('fs-extra', () => {
return {
__esModule: true,
default: jest.fn(),
existsSync: jest.fn(),
readFile: jest.fn(),
writeFile: jest.fn(),
}
})
jest.mock('../plugin-data', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
publicFolder: jest.fn().mockReturnValue('mock-file-path'),
}),
}))
jest.mock('../build-headers-program', () => ({
__esModule: true,
default: jest.fn(),
}))
jest.mock('fs-extra', () => ({
__esModule: true,
default: jest.fn(),
existsSync: jest.fn(),
readFile: jest.fn(),
writeFile: jest.fn(),
}))

// Importing writeFile here gives us access to the mocked method to assert the correct content is written to the file within test cases
import { writeFile } from 'fs-extra'
import { testPluginOptionsSchema } from 'gatsby-plugin-utils'

import { pluginOptionsSchema, onPostBuild } from '../gatsby-node'

describe(`gatsby-node.js`, () => {
Expand All @@ -46,7 +41,7 @@ describe(`gatsby-node.js`, () => {
mergeSecurityHeaders: `this should be a boolean`,
mergeLinkHeaders: `this should be a boolean`,
mergeCachingHeaders: `this should be a boolean`,
transformHeaders: (too, many, args) => ``,
transformHeaders: (too, many, args) => [too, many, args],
generateMatchPathRewrites: `this should be a boolean`,
})

Expand Down
14 changes: 8 additions & 6 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import _ from "lodash"
import _ from 'lodash'

// Gatsby values
export const BUILD_HTML_STAGE = `build-html`
Expand All @@ -7,17 +7,19 @@ export const BUILD_CSS_STAGE = `build-css`
// Plugin values
export const NETLIFY_HEADERS_FILENAME = `_headers`

// Default options including transform to manipulate headers for
// sorting and rewrites for client only paths
export const DEFAULT_OPTIONS = {
headers: {},
mergeSecurityHeaders: true,
mergeLinkHeaders: true,
mergeCachingHeaders: true,
transformHeaders: _.identity, // optional transform for manipulating headers for sorting, etc
generateMatchPathRewrites: true, // generate rewrites for client only paths
transformHeaders: _.identity,
generateMatchPathRewrites: true,
}

export const SECURITY_HEADERS = {
"/*": [
'/*': [
`X-Frame-Options: DENY`,
`X-XSS-Protection: 1; mode=block`,
`X-Content-Type-Options: nosniff`,
Expand All @@ -28,8 +30,8 @@ export const SECURITY_HEADERS = {
export const IMMUTABLE_CACHING_HEADER = `Cache-Control: public, max-age=31536000, immutable`

export const CACHING_HEADERS = {
"/static/*": [IMMUTABLE_CACHING_HEADER],
"/sw.js": [`Cache-Control: no-cache`],
'/static/*': [IMMUTABLE_CACHING_HEADER],
'/sw.js': [`Cache-Control: no-cache`],
}

export const LINK_REGEX = /^(Link: <\/)(.+)(>;.+)/
Expand Down
9 changes: 2 additions & 7 deletions src/create-redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ export default async function writeRedirectsFile(pluginData: any, redirects: any
const value = rest[key]

if (typeof value === `string` && value.includes(` `)) {
console.warn(
`Invalid redirect value "${value}" specified for key "${key}". ` + `Values should not contain spaces.`,
)
console.warn(`Invalid redirect value "${value}" specified for key "${key}". Values should not contain spaces.`)
} else if (NETLIFY_REDIRECT_KEYWORDS_ALLOWLIST.has(key)) {
pieces.push(`${key}=${value}`)
}
Expand All @@ -49,10 +47,7 @@ export default async function writeRedirectsFile(pluginData: any, redirects: any
return pieces.join(` `)
})

rewrites = rewrites.map(({
fromPath,
toPath
}: any) => `${fromPath} ${toPath} 200`)
rewrites = rewrites.map(({ fromPath, toPath }: any) => `${fromPath} ${toPath} 200`)

let commentFound = false

Expand Down
20 changes: 5 additions & 15 deletions src/gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// https://www.netlify.com/docs/headers-and-basic-auth/

import { promises as fs } from 'fs'
import { join } from 'path'

import { writeFile } from 'fs-extra'
import { generatePageDataPath } from 'gatsby-core-utils'
import WebpackAssetsManifest from 'webpack-assets-manifest'

Expand All @@ -14,9 +13,7 @@ import makePluginData from './plugin-data'
const assetsManifest = {}

/** @type {import("gatsby").GatsbyNode["pluginOptionsSchema"]} */
export const pluginOptionsSchema = ({
Joi
}: any) => {
export const pluginOptionsSchema = ({ Joi }: any) => {
const MATCH_ALL_KEYS = /^/

// headers is a specific type used by Netlify: https://www.gatsbyjs.com/plugins/gatsby-plugin-netlify/#headers
Expand Down Expand Up @@ -44,10 +41,7 @@ export const pluginOptionsSchema = ({
// Inject a webpack plugin to get the file manifests so we can translate all link headers
/** @type {import("gatsby").GatsbyNode["onCreateWebpackConfig"]} */

export const onCreateWebpackConfig = ({
actions,
stage
}: any) => {
export const onCreateWebpackConfig = ({ actions, stage }: any) => {
if (stage !== BUILD_HTML_STAGE && stage !== BUILD_CSS_STAGE) {
return
}
Expand All @@ -63,11 +57,7 @@ export const onCreateWebpackConfig = ({
}

/** @type {import("gatsby").GatsbyNode["onPostBuild"]} */
export const onPostBuild = async ({
store,
pathPrefix,
reporter
}: any, userPluginOptions: any) => {
export const onPostBuild = async ({ store, pathPrefix, reporter }: any, userPluginOptions: any) => {
const pluginData = makePluginData(store, assetsManifest, pathPrefix)
const pluginOptions = { ...DEFAULT_OPTIONS, ...userPluginOptions }

Expand Down Expand Up @@ -113,7 +103,7 @@ export const onPostBuild = async ({

if (!needsFunctions) {
reporter.info(`[gatsby-plugin-netlify] No Netlify functions needed. Skipping...`)
await fs.writeFile(join(program.directory, `.cache`, `.nf-skip-gatsby-functions`), ``)
await writeFile(join(program.directory, `.cache`, `.nf-skip-gatsby-functions`), ``)
}

await Promise.all([
Expand Down
14 changes: 9 additions & 5 deletions src/plugin-data.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import path from "path"
import path from 'path'

export function buildPrefixer(prefix: any, ...paths: any[]) {
return (...subpaths: any[]) => path.join(prefix, ...paths, ...subpaths);
}
const buildPrefixer =
(prefix: any, ...paths: any[]) =>
(...subpaths: any[]) =>
path.join(prefix, ...paths, ...subpaths)

// This function assembles data across the manifests and store to match a similar
// shape of `static-entry.js`. With it, we can build headers that point to the correct
// hashed filenames and ensure we pull in the componentChunkName.
export default function makePluginData(store: any, assetsManifest: any, pathPrefix: any) {
const makePluginData = (store: any, assetsManifest: any, pathPrefix: any) => {
const { program, pages, components } = store.getState()
const publicFolder = buildPrefixer(program.directory, `public`)
// eslint-disable-next-line node/global-require, import/no-dynamic-require, @typescript-eslint/no-var-requires
const stats = require(publicFolder(`webpack.stats.json`))
// Get all the files, not just the first
const chunkManifest = stats.assetsByChunkName
Expand All @@ -25,3 +27,5 @@ export default function makePluginData(store: any, assetsManifest: any, pathPref
publicFolder,
}
}

export { makePluginData as default, buildPrefixer }
Loading

0 comments on commit 5b9d6a3

Please sign in to comment.