Skip to content

Commit

Permalink
Merge pull request #352 from errendir/fix-custom-worker-buildtime-rac…
Browse files Browse the repository at this point in the history
…e-condition

Avoid a race between reading from and writing to the `importScripts` array
  • Loading branch information
shadowwalker committed Jun 6, 2022
2 parents 8c8d68f + 7eccd14 commit 86a4c18
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
15 changes: 10 additions & 5 deletions build-custom-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')

const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, success, minify }) => {
const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, minify }) => {
let workerDir = undefined

if (fs.existsSync(path.join(basedir, customWorkerDir))) {
Expand All @@ -15,14 +15,19 @@ const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, suc
workerDir = path.join(basedir, 'src', customWorkerDir)
}

if (!workerDir) return
if (!workerDir) return null

const name = `worker-${id}.js`
const customWorkerEntries = ['ts', 'js']
.map(ext => path.join(workerDir, `index.${ext}`))
.filter(entry => fs.existsSync(entry))

if (customWorkerEntries.length !== 1) return
if (customWorkerEntries.length === 0) return null

if (customWorkerEntries.length > 1) {
console.warn(`> [PWA] WARNING: More than one custom worker found (${customWorkerEntries.join(",")}), not building a custom worker`)
return null
}

const customWorkerEntry = customWorkerEntries[0]
console.log(`> [PWA] Custom worker found: ${customWorkerEntry}`)
Expand Down Expand Up @@ -102,10 +107,10 @@ const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, suc
console.error(`> [PWA] Failed to build custom worker`)
console.error(status.toString({ colors: true }))
process.exit(-1)
} else {
success({ name })
}
})

return name
}

module.exports = buildCustomWorker
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,19 @@ module.exports = (nextConfig = {}) => ({

if (!options.isServer) {
const _dest = path.join(options.dir, dest)
buildCustomWorker({
const customWorkerScriptName = buildCustomWorker({
id: buildId,
basedir: options.dir,
customWorkerDir,
destdir: _dest,
plugins: config.plugins.filter(plugin => plugin instanceof webpack.DefinePlugin),
success: ({ name }) => importScripts.unshift(name),
minify: !dev
})

if (customWorkerScriptName !== null) {
importScripts.unshift(customWorkerScriptName)
}

if (register) {
console.log(`> [PWA] Auto register service worker with: ${path.resolve(registerJs)}`)
} else {
Expand Down

0 comments on commit 86a4c18

Please sign in to comment.