mirror of
https://github.com/hanzoai/msw.git
synced 2026-09-24 17:00:34 +00:00
54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
import { until } from 'until-async'
|
|
|
|
/**
|
|
* Copies the given Service Worker source file into the destination.
|
|
* Injects the integrity checksum into the destination file.
|
|
*/
|
|
export default async function copyServiceWorker(
|
|
sourceFilePath: string,
|
|
destFilePath: string,
|
|
checksum: string,
|
|
): Promise<void> {
|
|
// eslint-disable-next-line no-console
|
|
console.log('Compiling Service Worker...')
|
|
|
|
const [readFileError, readFileResult] = await until(() =>
|
|
fs.promises.readFile(sourceFilePath, 'utf8'),
|
|
)
|
|
|
|
if (readFileError) {
|
|
throw new Error('Failed to read file.\n${readError.message}')
|
|
}
|
|
|
|
const destFileDirectory = path.dirname(destFilePath)
|
|
// eslint-disable-next-line no-console
|
|
console.log('Checking if "%s" path exists...', destFileDirectory)
|
|
|
|
if (!fs.existsSync(destFileDirectory)) {
|
|
// eslint-disable-next-line no-console
|
|
console.log('Destination directory does not exist, creating...')
|
|
await fs.promises.mkdir(destFileDirectory, { recursive: true })
|
|
}
|
|
|
|
const packageJson = JSON.parse(
|
|
fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
|
|
)
|
|
|
|
const nextFileContent = readFileResult
|
|
.replace('<INTEGRITY_CHECKSUM>', checksum)
|
|
.replace('<PACKAGE_VERSION>', packageJson.version)
|
|
|
|
const [writeFileError] = await until(() =>
|
|
fs.promises.writeFile(destFilePath, nextFileContent),
|
|
)
|
|
|
|
if (writeFileError) {
|
|
throw new Error(`Failed to write file.\n${writeFileError.message}`)
|
|
}
|
|
|
|
// eslint-disable-next-line no-console
|
|
console.log('Service Worker copied to: %s', destFilePath)
|
|
}
|