aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/watch.js
blob: 7ec07ff6422d615d59a810fac62fd13e7b541e1b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/usr/bin/env node

// @ts-check

const { spawn } = require('child_process');
const electronPath = require('electron');
const { build, createLogger, createServer } = require('vite');

/** @type string */
const mode = process.env.MODE = process.env.MODE || 'development';

/** @type {import('vite').LogLevel} */
const LOG_LEVEL = 'info';

/** @type {import('vite').InlineConfig} */
const sharedConfig = {
  mode,
  build: {
    watch: {},
  },
  logLevel: LOG_LEVEL,
};

/**
 * Messages on stderr that match any of the contained patterns will be stripped from output
 *
 * @type RegExp[]
 */
const stderrFilterPatterns = [
  // warning about devtools extension
  // https://github.com/cawa-93/vite-electron-builder/issues/492
  // https://github.com/MarshallOfSound/electron-devtools-installer/issues/143
  /ExtensionLoadWarning/,
  // GPU sandbox error with the mesa GLSL cache
  // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=918433
  /InitializeSandbox\(\) called with multiple threads in process gpu-process/,
];

/**
 * @param {{name: string; configFile: string; writeBundle: import('rollup').OutputPlugin['writeBundle'] }} config
 * @returns {Promise<import('rollup').RollupOutput | Array<import('rollup').RollupOutput> | import('rollup').RollupWatcher>}
 */
function getWatcher({name, configFile, writeBundle}) {
  return build({
    ...sharedConfig,
    configFile,
    plugins: [
      {
        name,
        writeBundle,
      },
    ],
  });
}

/**
 * Start or restart App when source files are changed.
 *
 * @param {import('vite').ViteDevServer} viteDevServer
 * @returns {Promise<import('rollup').RollupOutput | Array<import('rollup').RollupOutput> | import('rollup').RollupWatcher>}
 */
function setupMainPackageWatcher(viteDevServer) {
  // Write a value to an environment variable to pass it to the main process.
  const protocol = `http${viteDevServer.config.server.https ? 's' : ''}:`;
  const host = viteDevServer.config.server.host || 'localhost';
  const port = viteDevServer.config.server.port;
  const path = '/';
  process.env.VITE_DEV_SERVER_URL = `${protocol}//${host}:${port}${path}`;

  const logger = createLogger(
    LOG_LEVEL,
    {
      prefix: '[main]',
    },
  );

  /** @type {import('child_process').ChildProcessWithoutNullStreams | null} */
  let spawnProcess = null;

  return getWatcher({
    name: 'reload-app-on-main-package-change',
    configFile: 'packages/main/vite.config.js',
    writeBundle() {
      if (spawnProcess !== null) {
        spawnProcess.kill('SIGINT');
        spawnProcess = null;
      }

      spawnProcess = spawn(String(electronPath), ['.']);

      spawnProcess.stdout.on('data', (data) => {
        if (data.toString().trim() !== '') {
          logger.warn(data.toString(), {timestamp: true})
        }
      });

      spawnProcess.stderr.on('data', (data) => {
        const trimmedData = data.toString().trim();
        if (trimmedData === '') {
          return;
        }
        const mayIgnore = stderrFilterPatterns.some((r) => r.test(data));
        if (mayIgnore) {
          return;
        }
        logger.error(data, { timestamp: true });
      });
    },
  });
}

/**
 * Start or restart App when source files are changed.
 *
 * @param {import('vite').ViteDevServer} viteDevServer
 * @returns {Promise<import('rollup').RollupOutput | Array<import('rollup').RollupOutput> | import('rollup').RollupWatcher>}
 */
function setupPreloadPackageWatcher(viteDevServer) {
  return getWatcher({
    name: 'reload-page-on-preload-package-change',
    configFile: 'packages/preload/vite.config.js',
    writeBundle() {
      viteDevServer.ws.send({
        type: 'full-reload',
      });
    },
  });
}

/**
 * @returns Promise<void>
 */
async function setupDevEnvironment() {
  const viteDevServer = await createServer({
    ...sharedConfig,
    configFile: 'packages/renderer/vite.config.js',
  });

  await viteDevServer.listen();

  await setupPreloadPackageWatcher(viteDevServer);
  return setupMainPackageWatcher(viteDevServer);
}

setupDevEnvironment().catch((err) => {
  console.error(err);
  process.exit(1);
});