Skip to content

Commit

Permalink
chore(gatsby): Begin the great TypeScript migration!
Browse files Browse the repository at this point in the history
  • Loading branch information
Blaine Kasten authored and blainekasten committed Dec 2, 2019
1 parent dd222d5 commit a361d9b
Show file tree
Hide file tree
Showing 19 changed files with 437 additions and 897 deletions.
1 change: 1 addition & 0 deletions .babelrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ if (process.env.NODE_ENV !== `test`) {
module.exports = {
sourceMaps: true,
presets: ["babel-preset-gatsby-package"],
plugins: [["@babel/plugin-transform-typescript", { isTSX: true }]],
ignore,
}
9 changes: 9 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@ jobs:
- run: yarn lint:other
- run: yarn check-repo-fields

typecheck:
executor: node
steps:
- <<: *attach_to_bootstrap
- run: yarn test:check

unit_tests_node8:
executor:
name: node
Expand Down Expand Up @@ -453,6 +459,9 @@ workflows:
jobs:
- windows_unit_tests
- bootstrap
- typecheck:
requires:
- bootstrap
- lint:
requires:
- bootstrap
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
"@lerna/prompt": "3.18.5",
"@typescript-eslint/eslint-plugin": "^2.9.0",
"@typescript-eslint/parser": "^2.9.0",
"@types/jest": "^24.0.23",
"@types/express": "^4.17.2",
"@types/node": "^12.12.11",
"babel-eslint": "^10.0.3",
"babel-jest": "^24.9.0",
"chalk": "^2.4.2",
Expand Down Expand Up @@ -70,7 +73,7 @@
},
"husky": {
"hooks": {
"pre-commit": "lint-staged || node scripts/on-lint-error.js"
"pre-commit": "lint-staged || node scripts/on-lint-error.js && yarn test:check"
}
},
"scripts": {
Expand Down Expand Up @@ -99,6 +102,7 @@
"publish-canary": "lerna publish --canary --yes",
"publish-next": "lerna publish --npm-tag=next --bump=prerelease",
"test": "npm-run-all -s lint jest",
"test:check": "node ./scripts/check-ts",
"test:coverage": "jest --coverage",
"test:update": "jest --updateSnapshot",
"test:watch": "jest --watch",
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@
"build:internal-plugins": "copyfiles -u 1 src/internal-plugins/**/package.json dist",
"build:rawfiles": "copyfiles -u 1 src/internal-plugins/**/raw_* dist",
"build:cjs": "babel cache-dir --out-dir cache-dir/commonjs --ignore **/__tests__",
"build:src": "babel src --out-dir dist --source-maps --verbose --ignore **/gatsby-cli.js,src/internal-plugins/dev-404-page/raw_dev-404-page.js,**/__tests__",
"build:src": "babel src --out-dir dist --source-maps --verbose --ignore **/gatsby-cli.js,src/internal-plugins/dev-404-page/raw_dev-404-page.js,**/__tests__ --extensions \".ts,.js\"",
"clean-test-bundles": "find test/ -type f -name bundle.js* -exec rm -rf {} +",
"prebuild": "rimraf dist && rimraf cache-dir/commonjs",
"postinstall": "node scripts/postinstall.js",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
/* @flow */

const url = require(`url`)
const glob = require(`glob`)
const fs = require(`fs`)
const openurl = require(`better-opn`)
const chokidar = require(`chokidar`)
const express = require(`express`)

import express from "express"
const graphqlHTTP = require(`express-graphql`)
const graphqlPlayground = require(`graphql-playground-middleware-express`)
.default
Expand Down Expand Up @@ -47,6 +46,27 @@ const {
structureWebpackErrors,
} = require(`../utils/webpack-error-utils`)

type Cert = {
keyPath: string
certPath: string
key: string
cert: string
}

type Program = {
useYarn: boolean
open: boolean
openTracingConfigFile: string
port: number
host: string
[`cert-file`]?: string
[`key-file`]?: string
directory: string
https?: boolean
sitePackageJson: { name: string } // TODO make this into package json spec
ssl?: Cert
}

// const isInteractive = process.stdout.isTTY

// Watch the static directory and copy files to public as they're added or
Expand All @@ -61,7 +81,7 @@ onExit(() => {
})

const waitJobsFinished = () =>
new Promise((resolve, reject) => {
new Promise(resolve => {
const onEndJob = () => {
if (store.getState().jobs.active.length === 0) {
resolve()
Expand All @@ -72,7 +92,7 @@ const waitJobsFinished = () =>
onEndJob()
})

async function startServer(program) {
async function startServer(program: Program) {
const indexHTMLActivity = report.phantomActivity(`building index.html`, {})
indexHTMLActivity.start()
const directory = program.directory
Expand Down Expand Up @@ -172,7 +192,7 @@ async function startServer(program) {
context: {},
customContext: schemaCustomization.context,
}),
customFormatErrorFn(err) {
customFormatErrorFn(err: Error) {
return {
...formatError(err),
stack: err.stack ? err.stack.split(`\n`) : [],
Expand Down Expand Up @@ -260,7 +280,7 @@ async function startServer(program) {
.on(`response`, response =>
res.writeHead(response.statusCode, response.headers)
)
.on(`error`, (err, _, response) => {
.on(`error`, (err: Error, _: any, response) => {
if (response) {
res.writeHead(response.statusCode, response.headers)
} else {
Expand All @@ -281,12 +301,12 @@ async function startServer(program) {
// This fixes "Unexpected token < in JSON at position 0" runtime
// errors after restarting development server and
// cause automatic hard refresh in the browser.
app.use(/.*\.hot-update\.json$/i, (req, res) => {
app.use(/.*\.hot-update\.json$/i, (_, res) => {
res.status(404).end()
})

// Render an HTML page and serve it.
app.use((req, res, next) => {
app.use((_, res) => {
res.sendFile(directoryPath(`public/index.html`), err => {
if (err) {
res.status(500).end()
Expand All @@ -306,19 +326,23 @@ async function startServer(program) {
websocketManager.init({ server, directory: program.directory })
const socket = websocketManager.getSocket()

const listener = server.listen(program.port, program.host, err => {
if (err) {
if (err.code === `EADDRINUSE`) {
// eslint-disable-next-line max-len
report.panic(
`Unable to start Gatsby on port ${program.port} as there's already a process listening on that port.`
)
return
}
const listener = server.listen(
program.port,
program.host,
(err?: Error & { code: string }) => {
if (err) {
if (err.code === `EADDRINUSE`) {
// eslint-disable-next-line max-len
report.panic(
`Unable to start Gatsby on port ${program.port} as there's already a process listening on that port.`
)
return
}

report.panic(`There was a problem starting the development server`, err)
report.panic(`There was a problem starting the development server`, err)
}
}
})
)

// Register watcher that rebuilds index.html every time html.js changes.
const watchGlobs = [`src/html.js`, `plugins/**/gatsby-ssr.js`].map(path =>
Expand All @@ -333,7 +357,7 @@ async function startServer(program) {
return { compiler, listener, webpackActivity }
}

module.exports = async (program: any) => {
module.exports = async (program: Program) => {
initTracer(program.openTracingConfigFile)
report.pendingActivity({ id: `webpack-develop` })
telemetry.trackCli(`DEVELOP_START`)
Expand Down Expand Up @@ -400,15 +424,15 @@ module.exports = async (program: any) => {

let { compiler, webpackActivity } = await startServer(program)

function prepareUrls(protocol, host, port) {
const formatUrl = hostname =>
function prepareUrls(protocol: "http" | "https", host: string, port: number) {
const formatUrl = (hostname: string) =>
url.format({
protocol,
hostname,
port,
pathname: `/`,
})
const prettyPrintUrl = hostname =>
const prettyPrintUrl = (hostname: string) =>
url.format({
protocol,
hostname,
Expand Down Expand Up @@ -458,7 +482,10 @@ module.exports = async (program: any) => {
}
}

function printInstructions(appName, urls, useYarn) {
function printInstructions(
appName: string,
urls: any // TODO
) {
console.log()
console.log(`You can now view ${chalk.bold(appName)} in the browser.`)
console.log()
Expand Down Expand Up @@ -508,7 +535,10 @@ module.exports = async (program: any) => {
}

function printDeprecationWarnings() {
const deprecatedApis = [`boundActionCreators`, `pathContext`]
const deprecatedApis: (`boundActionCreators` | `pathContext`)[] = [
`boundActionCreators`,
`pathContext`,
]
const fixMap = {
boundActionCreators: {
newName: `actions`,
Expand All @@ -519,15 +549,17 @@ module.exports = async (program: any) => {
docsLink: `https://gatsby.dev/pathContext`,
},
}
const deprecatedLocations = {}
deprecatedApis.forEach(api => (deprecatedLocations[api] = []))
const deprecatedLocations = {
boundActionCreators: [] as string[],
pathContext: [] as string[],
}

glob
.sync(`{,!(node_modules|public)/**/}*.js`, { nodir: true })
.forEach(file => {
.forEach((file: string) => {
const fileText = fs.readFileSync(file)
const matchingApis = deprecatedApis.filter(api =>
fileText.includes(api)
const matchingApis = deprecatedApis.filter(
api => fileText.indexOf(api) !== -1
)
matchingApis.forEach(api => deprecatedLocations[api].push(file))
})
Expand All @@ -554,7 +586,10 @@ module.exports = async (program: any) => {
// console.log(`set invalid`, args, this)
// })

compiler.hooks.watchRun.tapAsync(`log compiling`, function(args, done) {
compiler.hooks.watchRun.tapAsync(`log compiling`, function(
_: any,
done: () => void
) {
if (webpackActivity) {
webpackActivity.end()
}
Expand All @@ -570,8 +605,8 @@ module.exports = async (program: any) => {
// "done" event fires when Webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event.
compiler.hooks.done.tapAsync(`print gatsby instructions`, function(
stats,
done
stats: any, // TODO webpack stats
done: () => void
) {
// We have switched off the default Webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present
Expand All @@ -585,10 +620,10 @@ module.exports = async (program: any) => {
const isSuccessful = !messages.errors.length

if (isSuccessful && isFirstCompile) {
printInstructions(program.sitePackageJson.name, urls, program.useYarn)
printInstructions(program.sitePackageJson.name, urls, true)
printDeprecationWarnings()
if (program.open) {
Promise.resolve(openurl(urls.localUrlForBrowser)).catch(err =>
Promise.resolve(openurl(urls.localUrlForBrowser)).catch(() =>
console.log(
`${chalk.yellow(
`warn`
Expand Down
31 changes: 15 additions & 16 deletions packages/gatsby/src/query/file-parser.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @flow
const fs = require(`fs-extra`)
const crypto = require(`crypto`)
const _ = require(`lodash`)
Expand All @@ -15,7 +14,7 @@ const {

const report = require(`gatsby-cli/lib/reporter`)

import type { DocumentNode } from "graphql"
// import type { DocumentNode } from "graphql"
import { babelParseToAst } from "../utils/babel-parse-to-ast"
import { codeFrameColumns } from "@babel/code-frame"

Expand Down Expand Up @@ -116,21 +115,21 @@ const warnForGlobalTag = file =>
file
)

type GraphQLDocumentInFile = {
filePath: string,
doc: DocumentNode,
templateLoc: string,
text: string,
hash: string,
isHook: boolean,
isStaticQuery: boolean,
}
// type GraphQLDocumentInFile = {
// filePath: string,
// doc: DocumentNode,
// templateLoc: string,
// text: string,
// hash: string,
// isHook: boolean,
// isStaticQuery: boolean,
// }

async function findGraphQLTags(
file,
text,
{ parentSpan, addError } = {}
): Promise<Array<GraphQLDocumentInFile>> {
) /*: Promise<Array<GraphQLDocumentInFile>>*/ {
return new Promise((resolve, reject) => {
parseToAst(file, text, { parentSpan, addError })
.then(ast => {
Expand Down Expand Up @@ -365,7 +364,7 @@ export default class FileParser {
this.parentSpan = parentSpan
}

async parseFile(file: string, addError): Promise<?DocumentNode> {
async parseFile(file /*: string*/, addError) /*: Promise<?DocumentNode>*/ {
let text
try {
text = await fs.readFile(file, `utf8`)
Expand Down Expand Up @@ -488,10 +487,10 @@ export default class FileParser {
}

async parseFiles(
files: Array<string>,
files /*: Array<string>*/,
addError
): Promise<Array<DocumentNode>> {
const documents = []
) /*: Promise<Array<DocumentNode>> */ {
const documents = new Map()

return Promise.all(
files.map(file =>
Expand Down
Loading

0 comments on commit a361d9b

Please sign in to comment.