atagen

malice

public
Star0
Watch0
544a170ead2c7f632e7957c1ed729ba50c80ec51
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/vite.config.tsTypescript101 lines3.1 KB
1
import { readdirSync, readFileSync } from 'node:fs';
2
import { join } from 'node:path';
3
import { fileURLToPath } from 'node:url';
4
import { defineConfig } from 'vite';
5
import { svelte, vitePreprocess } from '@sveltejs/vite-plugin-svelte';
6
7
/**
8
 * The page isn't SW-controlled on first launch, so the worker chunk and the
9
 * wasm can bypass fetch interception entirely and never get cached. Instead
10
 * of relying on runtime fetches, prepend the full list of emitted files
11
 * (chunks, assets, wasm) to sw.js as a global so install() can precache all
12
 * of it directly, no separate request needed.
13
 */
14
function precacheManifestPlugin(): import('vite').Plugin {
15
  return {
16
    name: 'malice-sw-precache-manifest',
17
    generateBundle(_options, bundle) {
18
      const urls = Object.keys(bundle)
19
        .filter(
20
          (fileName) => fileName !== 'sw.js' && fileName !== '.vite/manifest.json' && !fileName.startsWith('twemoji/')
21
        )
22
        .map((fileName) => `/${fileName}`);
23
      const swChunk = bundle['sw.js'];
24
      if (swChunk && swChunk.type === 'chunk') {
25
        swChunk.code = `self.__MALICE_PRECACHE__=${JSON.stringify(urls)};\n${swChunk.code}`;
26
      }
27
    }
28
  };
29
}
30
31
function twemojiPlugin(): import('vite').Plugin {
32
  const dir = fileURLToPath(new URL('./node_modules/@twemoji/svg', import.meta.url));
33
  const svgs = () => readdirSync(dir).filter((f) => f.endsWith('.svg'));
34
  return {
35
    name: 'malice-twemoji',
36
    configureServer(server) {
37
      server.middlewares.use('/twemoji', (req, res, next) => {
38
        const name = decodeURIComponent((req.url ?? '').split('?')[0]).replace(/^\//, '');
39
        if (!/^[0-9a-f-]+\.svg$/.test(name)) return next();
40
        try {
41
          res.setHeader('Content-Type', 'image/svg+xml');
42
          res.end(readFileSync(join(dir, name)));
43
        } catch {
44
          res.statusCode = 404;
45
          res.end();
46
        }
47
      });
48
    },
49
    generateBundle() {
50
      for (const file of svgs()) {
51
        this.emitFile({ type: 'asset', fileName: `twemoji/${file}`, source: readFileSync(join(dir, file)) });
52
      }
53
    }
54
  };
55
}
56
57
export default defineConfig(({ mode }) => {
58
  const device = mode === 'device';
59
  return {
60
    plugins: [svelte({ preprocess: vitePreprocess() }), twemojiPlugin(), ...(device ? [precacheManifestPlugin()] : [])],
61
    assetsInclude: ['**/*.wasm'],
62
    resolve: {
63
      alias: {
64
        'malice:device-transport': device ? '/src/lib/device-transport.ts' : '/src/lib/device-transport.stub.ts'
65
      }
66
    },
67
    server: {
68
      host: '127.0.0.1',
69
      port: 5173,
70
      proxy: {
71
        '/api': 'http://localhost:3000'
72
      }
73
    },
74
    preview: {
75
      host: '127.0.0.1',
76
      port: 4173,
77
      proxy: {
78
        '/api': 'http://localhost:3000'
79
      }
80
    },
81
    build: device
82
      ? {
83
          outDir: 'dist-device',
84
          emptyOutDir: true,
85
          manifest: true,
86
          rollupOptions: {
87
            input: {
88
              main: 'index.html',
89
              sw: 'src/sw.ts'
90
            },
91
            output: {
92
              entryFileNames: (chunk) => (chunk.name === 'sw' ? 'sw.js' : 'assets/[name]-[hash].js')
93
            }
94
          }
95
        }
96
      : {
97
          outDir: 'dist',
98
          emptyOutDir: true
99
        }
100
  };
101
});