sw building seem to be working fine now?

This commit is contained in:
Henry Jameson 2026-06-02 23:01:39 +03:00
commit fead727d78
4 changed files with 9 additions and 164 deletions

View file

@ -16,22 +16,15 @@ const getSWMessagesAsText = async () => {
} }
const projectRoot = dirname(dirname(fileURLToPath(import.meta.url))) const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)))
const swEnvName = 'virtual:pleroma-fe/service_worker_env'
const swEnvNameResolved = '\0' + swEnvName
const getDevSwEnv = () => `self.serviceWorkerOption = { assets: [] };` const getDevSwEnv = () => `self.serviceWorkerOption = { assets: [] };`
const getProdSwEnv = ({ assets }) => const getProdSwEnv = ({ assets }) =>
`self.serviceWorkerOption = { assets: ${JSON.stringify(assets)} };` `self.serviceWorkerOption = { assets: ${JSON.stringify(assets)} };`
export const devSwPlugin = ({ swSrc, swDest, transformSW, alias }) => { export const devSwPlugin = ({ swSrc, swDest }) => {
const swFullSrc = resolve(projectRoot, swSrc) const swFullSrc = resolve(projectRoot, swSrc)
const esbuildAlias = {}
Object.entries(alias).forEach(([source, dest]) => {
esbuildAlias[source] = dest.startsWith('/') ? projectRoot + dest : dest
})
return { return {
name: 'dev-sw-plugin', name: 'dev-sw-plugin', apply: 'serve',
apply: 'serve',
configResolved() { configResolved() {
/* no-op */ /* no-op */
}, },
@ -39,150 +32,15 @@ export const devSwPlugin = ({ swSrc, swDest, transformSW, alias }) => {
const name = id.startsWith('/') ? id.slice(1) : id const name = id.startsWith('/') ? id.slice(1) : id
if (name === swDest) { if (name === swDest) {
return swFullSrc return swFullSrc
} else if (name === swEnvName) {
return swEnvNameResolved
} }
return null return null
}, },
async load(id) { async load(id) {
if (id === swFullSrc) { if (id === swFullSrc) {
return readFile(swFullSrc, 'utf-8') return readFile(swFullSrc, 'utf-8')
} else if (id === swEnvNameResolved) {
return getDevSwEnv()
} }
return null return null
}, },
/**
* vite does not bundle the service worker
* during dev, and firefox does not support ESM as service worker
* https://bugzilla.mozilla.org/show_bug.cgi?id=1360870
*/
async transform(code, id) {
if (id === swFullSrc && transformSW) {
const res = await esbuild.build({
entryPoints: [swSrc],
bundle: true,
write: false,
outfile: 'sw-pleroma.js',
alias: esbuildAlias,
plugins: [
{
name: 'vite-like-root-resolve',
setup(b) {
b.onResolve({ filter: new RegExp(/^\//) }, (args) => ({
path: resolve(projectRoot, args.path.slice(1)),
}))
},
},
{
name: 'sw-messages',
setup(b) {
b.onResolve(
{ filter: new RegExp('^' + swMessagesName + '$') },
(args) => ({
path: args.path,
namespace: 'sw-messages',
}),
)
b.onLoad(
{ filter: /.*/, namespace: 'sw-messages' },
async () => ({
contents: await getSWMessagesAsText(),
}),
)
},
},
{
name: 'sw-env',
setup(b) {
b.onResolve(
{ filter: new RegExp('^' + swEnvName + '$') },
(args) => ({
path: args.path,
namespace: 'sw-env',
}),
)
b.onLoad({ filter: /.*/, namespace: 'sw-env' }, () => ({
contents: getDevSwEnv(),
}))
},
},
],
})
const text = res.outputFiles[0].text
return text
}
},
}
}
// Idea taken from
// https://github.com/vite-pwa/vite-plugin-pwa/blob/main/src/plugins/build.ts
// rollup does not support compiling to iife if we want to code-split;
// however, we must compile the service worker to iife because of browser support.
// Run another vite build just for the service worker targeting iife at
// the end of the build.
export const buildSwPlugin = ({ swSrc, swDest }) => {
let config
return {
name: 'build-sw-plugin',
enforce: 'post',
apply: 'build',
configResolved(resolvedConfig) {
config = {
define: resolvedConfig.define,
resolve: resolvedConfig.resolve,
plugins: [swMessagesPlugin()],
publicDir: false,
build: {
...resolvedConfig.build,
lib: {
entry: swSrc,
formats: ['iife'],
name: 'sw_pleroma',
},
emptyOutDir: false,
rolldownOptions: {
output: {
entryFileNames: swDest,
},
},
},
configFile: false,
}
},
generateBundle: {
order: 'post',
sequential: true,
async handler(_, bundle) {
const assets = Object.keys(bundle)
.filter((name) => !/\.map$/.test(name))
.map((name) => '/' + name)
config.plugins.push({
name: 'build-sw-env-plugin',
resolveId(id) {
if (id === swEnvName) {
return swEnvNameResolved
}
return null
},
load(id) {
if (id === swEnvNameResolved) {
return getProdSwEnv({ assets })
}
return null
},
})
},
},
closeBundle: {
order: 'post',
sequential: true,
async handler() {
console.info('Building service worker for production')
await build(config)
},
},
} }
} }

View file

@ -18,8 +18,9 @@ function isPushSupported() {
function getOrCreateServiceWorker() { function getOrCreateServiceWorker() {
if (!isSWSupported()) return if (!isSWSupported()) return
const swType = process.env.HAS_MODULE_SERVICE_WORKER ? 'module' : 'classic' const swType = process.env.HAS_MODULE_SERVICE_WORKER ? 'module' : 'classic'
return navigator.serviceWorker return navigator
.register(import.meta.env.MODE === 'production' ? '/sw-pleroma.js' : '/dev-sw.js?dev-sw', { type: swType }) .serviceWorker
.register('/sw-pleroma.js', { type: swType })
.catch((err) => .catch((err) =>
console.error('Unable to get or create a service worker.', err), console.error('Unable to get or create a service worker.', err),
) )

View file

@ -12,6 +12,7 @@ import { getCommitHash } from './build/commit_hash.js'
import copyPlugin from './build/copy_plugin.js' import copyPlugin from './build/copy_plugin.js'
import emojisPlugin from './build/emojis_plugin.js' import emojisPlugin from './build/emojis_plugin.js'
import { import {
devSwPlugin,
swMessagesPlugin, swMessagesPlugin,
} from './build/sw_plugin.js' } from './build/sw_plugin.js'
import { VitePWA } from 'vite-plugin-pwa' import { VitePWA } from 'vite-plugin-pwa'
@ -109,7 +110,7 @@ export default defineConfig(async ({ mode, command }) => {
}, },
} }
const swSrc = 'src/sw-pleroma.js' const swSrc = 'src/sw.js'
const swDest = 'sw-pleroma.js' const swDest = 'sw-pleroma.js'
const alias = { const alias = {
src: '/src', src: '/src',
@ -160,23 +161,7 @@ export default defineConfig(async ({ mode, command }) => {
), ),
}), }),
swMessagesPlugin(), swMessagesPlugin(),
VitePWA({ devSwPlugin({ swSrc, swDest }),
strategies: 'injectManifest',
srcDir: 'src',
filename: 'sw-pleroma.js',
manifest: false,
injectRegister: null,
devOptions: {
enabled: true,
type: 'classic',
},
injectManifest: {
injectionPoint: undefined,
buildPlugins: {
vite: [swMessagesPlugin()],
},
}
}),
], ],
optimizeDeps: { optimizeDeps: {
// For unknown reasons, during vitest, vite will re-optimize the following // For unknown reasons, during vitest, vite will re-optimize the following
@ -221,6 +206,7 @@ export default defineConfig(async ({ mode, command }) => {
devtools: {}, // enable devtools mode devtools: {}, // enable devtools mode
input: { input: {
main: 'index.html', main: 'index.html',
sw: 'src/sw.js',
}, },
output: { output: {
entryFileNames(chunkInfo) { entryFileNames(chunkInfo) {