Skip to content

Commit 227b026

Browse files
ascorbicTiffany Le-Nguyenkodiakhq[bot]
authored
chore: convert remaining source files to TypeScript (#939)
* chore: convert remaining source files to TypeScript * chore: apply suggestions from code review Co-authored-by: Tiffany Le-Nguyen <[email protected]> Co-authored-by: Tiffany Le-Nguyen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 84334eb commit 227b026

File tree

7 files changed

+133
-78
lines changed

7 files changed

+133
-78
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
"watch": "tsc --watch"
3434
},
3535
"config": {
36-
"eslint": "--cache --format=codeframe --max-warnings=0 \"{src,scripts,tests,.github}/**/*.{js,md,html}\" \"*.{js,md,html}\" \".*.{js,md,html}\"",
37-
"prettier": "--loglevel=warn \"{src,scripts,tests,.github}/**/*.{js,md,yml,json,html}\" \"*.{js,yml,json,html}\" \".*.{js,yml,json,html}\" \"!package-lock.json\""
36+
"eslint": "--cache --format=codeframe --max-warnings=0 \"{src,scripts,tests,.github}/**/*.{ts,js,md,html}\" \"*.{ts,js,md,html}\" \".*.{ts,js,md,html}\"",
37+
"prettier": "--loglevel=warn \"{src,scripts,tests,.github}/**/*.{ts,js,md,yml,json,html}\" \"*.{ts,js,yml,json,html}\" \".*.{ts,js,yml,json,html}\" \"!package-lock.json\""
3838
},
3939
"repository": {
4040
"type": "git",

src/constants.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export const CATCH_ALL_REGEX = /\/\[\.{3}(.*)](.json)?$/
2222
export const OPTIONAL_CATCH_ALL_REGEX = /\/\[{2}\.{3}(.*)]{2}(.json)?$/
2323
export const DYNAMIC_PARAMETER_REGEX = /\/\[(.*?)]/g
2424
export const MINIMUM_REVALIDATE_SECONDS = 60
25+
// 50MB, which is the documented max, though the hard max seems to be higher
26+
export const LAMBDA_MAX_SIZE = 1024 * 1024 * 50
2527

2628
export const DIVIDER = `
2729
────────────────────────────────────────────────────────────────

src/helpers/cache.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ export const saveCache = async ({ cache, publish }) => {
1919
} else {
2020
console.log('No Next.js cache to save.')
2121
}
22-
}
22+
}

src/helpers/files.js renamed to src/helpers/files.ts

Lines changed: 65 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,54 @@
11
/* eslint-disable max-lines */
2-
const { cpus } = require('os')
3-
4-
const { yellowBright } = require('chalk')
5-
const {
6-
existsSync,
7-
readJson,
8-
move,
9-
copy,
10-
writeJson,
11-
readFile,
12-
writeFile,
13-
ensureDir,
14-
readFileSync,
15-
} = require('fs-extra')
16-
const globby = require('globby')
17-
const { outdent } = require('outdent')
18-
const pLimit = require('p-limit')
19-
const { join } = require('pathe')
20-
const slash = require('slash')
21-
22-
const { MINIMUM_REVALIDATE_SECONDS, DIVIDER } = require('../constants')
2+
import { cpus } from 'os'
3+
4+
import { NetlifyConfig } from '@netlify/build'
5+
import { yellowBright } from 'chalk'
6+
import { existsSync, readJson, move, copy, writeJson, readFile, writeFile, ensureDir, readFileSync } from 'fs-extra'
7+
import globby from 'globby'
8+
import { PrerenderManifest } from 'next/dist/build'
9+
import { Redirect as NextRedirect } from 'next/dist/lib/load-custom-routes'
10+
import { outdent } from 'outdent'
11+
import pLimit from 'p-limit'
12+
import { join } from 'pathe'
13+
import slash from 'slash'
14+
15+
import { MINIMUM_REVALIDATE_SECONDS, DIVIDER } from '../constants'
16+
17+
import { NextConfig } from './config'
18+
19+
interface Redirect extends NextRedirect {
20+
regex: string
21+
internal?: boolean
22+
}
23+
24+
type Rewrites =
25+
| {
26+
fallback?: Array<Redirect>
27+
afterFiles?: Array<Redirect>
28+
beforeFiles?: Array<Redirect>
29+
}
30+
| Array<Redirect>
2331

2432
const TEST_ROUTE = /(|\/)\[[^/]+?](\/|\.html|$)/
2533

26-
const isDynamicRoute = (route) => TEST_ROUTE.test(route)
34+
export const isDynamicRoute = (route) => TEST_ROUTE.test(route)
2735

28-
const stripLocale = (rawPath, locales = []) => {
36+
export const stripLocale = (rawPath: string, locales: Array<string> = []) => {
2937
const [locale, ...segments] = rawPath.split('/')
3038
if (locales.includes(locale)) {
3139
return segments.join('/')
3240
}
3341
return rawPath
3442
}
3543

36-
const matchMiddleware = (middleware, filePath) =>
44+
export const matchMiddleware = (middleware: Array<string>, filePath: string): string | boolean =>
3745
middleware?.includes('') ||
3846
middleware?.find(
3947
(middlewarePath) =>
4048
filePath === middlewarePath || filePath === `${middlewarePath}.html` || filePath.startsWith(`${middlewarePath}/`),
4149
)
4250

43-
const matchesRedirect = (file, redirects) => {
51+
export const matchesRedirect = (file: string, redirects: Rewrites): boolean => {
4452
if (!Array.isArray(redirects)) {
4553
return false
4654
}
@@ -53,7 +61,7 @@ const matchesRedirect = (file, redirects) => {
5361
})
5462
}
5563

56-
const matchesRewrite = (file, rewrites) => {
64+
export const matchesRewrite = (file: string, rewrites: Rewrites): boolean => {
5765
if (Array.isArray(rewrites)) {
5866
return matchesRedirect(file, rewrites)
5967
}
@@ -63,14 +71,16 @@ const matchesRewrite = (file, rewrites) => {
6371
return matchesRedirect(file, rewrites.beforeFiles)
6472
}
6573

66-
exports.matchesRedirect = matchesRedirect
67-
exports.matchesRewrite = matchesRewrite
68-
exports.matchMiddleware = matchMiddleware
69-
exports.stripLocale = stripLocale
70-
exports.isDynamicRoute = isDynamicRoute
71-
7274
// eslint-disable-next-line max-lines-per-function
73-
exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
75+
export const moveStaticPages = async ({
76+
netlifyConfig,
77+
target,
78+
i18n,
79+
}: {
80+
netlifyConfig: NetlifyConfig
81+
target: 'server' | 'serverless' | 'experimental-serverless-trace'
82+
i18n: NextConfig['i18n']
83+
}): Promise<void> => {
7484
console.log('Moving static page files to serve from CDN...')
7585
const outputDir = join(netlifyConfig.build.publish, target === 'server' ? 'server' : 'serverless')
7686
const root = join(outputDir, 'pages')
@@ -87,12 +97,16 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
8797
}
8898
}
8999

90-
const prerenderManifest = await readJson(join(netlifyConfig.build.publish, 'prerender-manifest.json'))
91-
const { redirects, rewrites } = await readJson(join(netlifyConfig.build.publish, 'routes-manifest.json'))
100+
const prerenderManifest: PrerenderManifest = await readJson(
101+
join(netlifyConfig.build.publish, 'prerender-manifest.json'),
102+
)
103+
const { redirects, rewrites }: { redirects: Array<Redirect>; rewrites: Rewrites } = await readJson(
104+
join(netlifyConfig.build.publish, 'routes-manifest.json'),
105+
)
92106

93-
const isrFiles = new Set()
107+
const isrFiles = new Set<string>()
94108

95-
const shortRevalidateRoutes = []
109+
const shortRevalidateRoutes: Array<{ Route: string; Revalidate: number }> = []
96110

97111
Object.entries(prerenderManifest.routes).forEach(([route, { initialRevalidateSeconds }]) => {
98112
if (initialRevalidateSeconds) {
@@ -106,8 +120,8 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
106120
}
107121
})
108122

109-
const files = []
110-
const filesManifest = {}
123+
const files: Array<string> = []
124+
const filesManifest: Record<string, string> = {}
111125
const moveFile = async (file) => {
112126
const isData = file.endsWith('.json')
113127
const source = join(root, file)
@@ -268,7 +282,7 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
268282
}
269283
}
270284

271-
const patchFile = async ({ file, from, to }) => {
285+
const patchFile = async ({ file, from, to }: { file: string; from: string; to: string }): Promise<void> => {
272286
if (!existsSync(file)) {
273287
return
274288
}
@@ -299,7 +313,7 @@ const getServerFile = (root) => {
299313
return serverFile
300314
}
301315

302-
exports.patchNextFiles = async (root) => {
316+
export const patchNextFiles = async (root: string): Promise<void> => {
303317
const serverFile = getServerFile(root)
304318
console.log(`Patching ${serverFile}`)
305319
if (serverFile) {
@@ -311,15 +325,23 @@ exports.patchNextFiles = async (root) => {
311325
}
312326
}
313327

314-
exports.unpatchNextFiles = async (root) => {
328+
export const unpatchNextFiles = async (root: string): Promise<void> => {
315329
const serverFile = getServerFile(root)
316330
const origFile = `${serverFile}.orig`
317331
if (existsSync(origFile)) {
318332
await move(origFile, serverFile, { overwrite: true })
319333
}
320334
}
321335

322-
exports.movePublicFiles = async ({ appDir, outdir, publish }) => {
336+
export const movePublicFiles = async ({
337+
appDir,
338+
outdir,
339+
publish,
340+
}: {
341+
appDir: string
342+
outdir?: string
343+
publish: string
344+
}): Promise<void> => {
323345
// `outdir` is a config property added when using Next.js with Nx. It's typically
324346
// a relative path outside of the appDir, e.g. '../../dist/apps/<app-name>', and
325347
// the parent directory of the .next directory.

src/helpers/verification.js renamed to src/helpers/verification.ts

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,29 @@
1-
const { existsSync, promises } = require('fs')
2-
const path = require('path')
3-
const { relative } = require('path')
1+
import { existsSync, promises } from 'fs'
2+
import path, { relative } from 'path'
43

5-
const { yellowBright, greenBright, blueBright, redBright, reset } = require('chalk')
6-
const { async: StreamZip } = require('node-stream-zip')
7-
const outdent = require('outdent')
8-
const prettyBytes = require('pretty-bytes')
9-
const { satisfies } = require('semver')
4+
import { NetlifyPluginUtils } from '@netlify/build'
5+
import { yellowBright, greenBright, blueBright, redBright, reset } from 'chalk'
6+
import { async as StreamZip } from 'node-stream-zip'
7+
import { outdent } from 'outdent'
8+
import prettyBytes from 'pretty-bytes'
9+
import { satisfies } from 'semver'
10+
11+
import { LAMBDA_MAX_SIZE } from '../constants'
1012

1113
// This is when nft support was added
1214
const REQUIRED_BUILD_VERSION = '>=18.16.0'
1315

14-
exports.verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuild }) => {
16+
type FailBuild = NetlifyPluginUtils['build']['failBuild']
17+
18+
export const verifyNetlifyBuildVersion = ({
19+
IS_LOCAL,
20+
NETLIFY_BUILD_VERSION,
21+
failBuild,
22+
}: {
23+
IS_LOCAL: boolean
24+
NETLIFY_BUILD_VERSION: string
25+
failBuild: FailBuild
26+
}): void | never => {
1527
// We check for build version because that's what's available to us, but prompt about the cli because that's what they can upgrade
1628
if (IS_LOCAL && !satisfies(NETLIFY_BUILD_VERSION, REQUIRED_BUILD_VERSION, { includePrerelease: true })) {
1729
return failBuild(outdent`
@@ -21,7 +33,7 @@ exports.verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuil
2133
}
2234
}
2335

24-
exports.checkForOldFunctions = async ({ functions }) => {
36+
export const checkForOldFunctions = async ({ functions }: Pick<NetlifyPluginUtils, 'functions'>): Promise<void> => {
2537
const allOldFunctions = await functions.list()
2638
const oldFunctions = allOldFunctions.filter(({ name }) => name.startsWith('next_'))
2739
if (oldFunctions.length !== 0) {
@@ -41,7 +53,13 @@ exports.checkForOldFunctions = async ({ functions }) => {
4153
}
4254
}
4355

44-
exports.checkNextSiteHasBuilt = ({ publish, failBuild }) => {
56+
export const checkNextSiteHasBuilt = ({
57+
publish,
58+
failBuild,
59+
}: {
60+
publish: string
61+
failBuild: FailBuild
62+
}): void | never => {
4563
if (!existsSync(path.join(publish, 'BUILD_ID'))) {
4664
return failBuild(outdent`
4765
The directory "${path.relative(
@@ -61,7 +79,13 @@ exports.checkNextSiteHasBuilt = ({ publish, failBuild }) => {
6179
}
6280
}
6381

64-
exports.checkForRootPublish = ({ publish, failBuild }) => {
82+
export const checkForRootPublish = ({
83+
publish,
84+
failBuild,
85+
}: {
86+
publish: string
87+
failBuild: FailBuild
88+
}): void | never => {
6589
if (path.resolve(publish) === path.resolve('.')) {
6690
failBuild(outdent`
6791
Your publish directory is pointing to the base directory of your site. This is not supported for Next.js sites, and is probably a mistake.
@@ -70,10 +94,7 @@ exports.checkForRootPublish = ({ publish, failBuild }) => {
7094
}
7195
}
7296

73-
// 50MB, which is the documented max, though the hard max seems to be higher
74-
const LAMBDA_MAX_SIZE = 1024 * 1024 * 50
75-
76-
exports.checkZipSize = async (file, maxSize = LAMBDA_MAX_SIZE) => {
97+
export const checkZipSize = async (file: string, maxSize: number = LAMBDA_MAX_SIZE): Promise<void> => {
7798
if (!existsSync(file)) {
7899
console.warn(`Could not check zip size because ${file} does not exist`)
79100
return
@@ -111,7 +132,7 @@ exports.checkZipSize = async (file, maxSize = LAMBDA_MAX_SIZE) => {
111132
)
112133
}
113134

114-
exports.logBetaMessage = () =>
135+
export const logBetaMessage = () =>
115136
console.log(
116137
greenBright(
117138
outdent`

src/index.js renamed to src/index.ts

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
1-
const { join, relative } = require('path')
2-
3-
const { ODB_FUNCTION_NAME } = require('./constants')
4-
const { restoreCache, saveCache } = require('./helpers/cache')
5-
const { getNextConfig, configureHandlerFunctions } = require('./helpers/config')
6-
const { moveStaticPages, movePublicFiles, patchNextFiles, unpatchNextFiles } = require('./helpers/files')
7-
const { generateFunctions, setupImageFunction, generatePagesResolver } = require('./helpers/functions')
8-
const { generateRedirects } = require('./helpers/redirects')
9-
const {
1+
import { join, relative } from 'path'
2+
3+
import { NetlifyPlugin } from '@netlify/build'
4+
5+
import { ODB_FUNCTION_NAME } from './constants'
6+
import { restoreCache, saveCache } from './helpers/cache'
7+
import { getNextConfig, configureHandlerFunctions } from './helpers/config'
8+
import { moveStaticPages, movePublicFiles, patchNextFiles, unpatchNextFiles } from './helpers/files'
9+
import { generateFunctions, setupImageFunction, generatePagesResolver } from './helpers/functions'
10+
import { generateRedirects } from './helpers/redirects'
11+
import {
1012
verifyNetlifyBuildVersion,
1113
checkNextSiteHasBuilt,
1214
checkForRootPublish,
1315
logBetaMessage,
1416
checkZipSize,
1517
checkForOldFunctions,
16-
} = require('./helpers/verification')
18+
} from './helpers/verification'
1719

18-
/** @type import("@netlify/build").NetlifyPlugin */
19-
module.exports = {
20+
const plugin: NetlifyPlugin = {
2021
async onPreBuild({
2122
constants,
2223
netlifyConfig,
@@ -71,7 +72,7 @@ module.exports = {
7172
}
7273

7374
if (!process.env.SERVE_STATIC_FILES_FROM_ORIGIN) {
74-
await moveStaticPages({ target, failBuild, netlifyConfig, i18n })
75+
await moveStaticPages({ target, netlifyConfig, i18n })
7576
}
7677

7778
await setupImageFunction({ constants, imageconfig: images, netlifyConfig, basePath })
@@ -82,7 +83,15 @@ module.exports = {
8283
})
8384
},
8485

85-
async onPostBuild({ netlifyConfig, utils: { cache, functions, failBuild }, constants: { FUNCTIONS_DIST } }) {
86+
async onPostBuild({
87+
netlifyConfig,
88+
utils: {
89+
cache,
90+
functions,
91+
build: { failBuild },
92+
},
93+
constants: { FUNCTIONS_DIST },
94+
}) {
8695
await saveCache({ cache, publish: netlifyConfig.build.publish })
8796
await checkForOldFunctions({ functions })
8897
await checkZipSize(join(FUNCTIONS_DIST, `${ODB_FUNCTION_NAME}.zip`))
@@ -93,3 +102,4 @@ module.exports = {
93102
logBetaMessage()
94103
},
95104
}
105+
module.exports = plugin

src/templates/handlerUtils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ export const augmentFsModule = ({
133133
return readfileOrig(file, options)
134134
}) as typeof promises.readFile
135135

136-
promises.stat = (async (file, options) => {
136+
promises.stat = ((file, options) => {
137137
// We only care about page files
138138
if (file.startsWith(pageRoot)) {
139139
// We only want the part after `pages/`

0 commit comments

Comments
 (0)