aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/config/graphvizUMDVitePlugin.ts
blob: ab726e4fb0638069857d3667df29469974a56aba (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
/*
 * SPDX-FileCopyrightText: 2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import { readFile } from 'node:fs/promises';
import path from 'node:path';

import pnpapi from 'pnpapi';
import type { PluginOption, ResolvedConfig } from 'vite';

// Use a CJS file as the PnP resolution issuer to force resolution to a non-ESM export.
const issuerFileName = 'worker.cjs';

export default function graphvizUMDVitePlugin(): PluginOption {
  let command: ResolvedConfig['command'] = 'build';
  let root: string | undefined;
  let url: string | undefined;

  return {
    name: 'graphviz-umd',
    enforce: 'post',
    configResolved(config) {
      ({ command, root } = config);
    },
    async buildStart() {
      const issuer =
        root === undefined ? issuerFileName : path.join(root, issuerFileName);
      const resolvedPath = pnpapi.resolveRequest(
        '@hpcc-js/wasm/graphviz',
        issuer,
      );
      if (resolvedPath === null) {
        return;
      }
      if (command === 'serve') {
        url = `/@fs/${resolvedPath}`;
      } else {
        const content = await readFile(resolvedPath, null);
        url = this.emitFile({
          name: path.basename(resolvedPath),
          type: 'asset',
          source: content,
        });
      }
    },
    renderStart() {
      if (url !== undefined && command !== 'serve') {
        url = this.getFileName(url);
      }
    },
    transformIndexHtml() {
      if (url === undefined) {
        return undefined;
      }
      return [
        {
          tag: 'script',
          attrs: {
            src: url,
            type: 'javascript/worker',
          },
          injectTo: 'head',
        },
      ];
    },
  };
}