File size: 4,238 Bytes
7667cef
 
161cb23
 
 
 
 
 
 
 
 
5c265c1
 
161cb23
 
 
5c265c1
 
 
 
 
 
 
 
 
 
 
 
 
161cb23
 
5c265c1
161cb23
5c265c1
 
161cb23
 
 
 
 
 
 
 
 
 
 
 
5c265c1
7667cef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c265c1
 
7667cef
 
 
5c265c1
 
7667cef
5c265c1
161cb23
 
5c265c1
161cb23
 
 
 
5c265c1
161cb23
 
 
 
 
 
5c265c1
161cb23
 
 
 
 
 
 
 
 
5c265c1
161cb23
 
 
 
 
 
 
 
 
 
 
 
5c265c1
161cb23
 
 
 
 
 
 
 
 
 
 
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
import { createHash } from "node:crypto";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as esbuild from "esbuild";

const webDir = path.dirname(fileURLToPath(import.meta.url));
const srcDir = path.join(webDir, "src");
const distDir = path.join(webDir, "dist");
const vendorDir = path.join(webDir, "vendor");
const repoRoot = [path.resolve(webDir, "../.."), path.resolve(webDir, "../../..")]
  .find((dir) => existsSync(path.join(dir, "compile.py"))) ?? path.resolve(webDir, "../../..");
const SHARED_FILES = ["engine.js", "presets.json", "weights.npz"];
const watch = process.argv.includes("--watch");

function sharedPaths() {
  if (SHARED_FILES.every((name) => existsSync(path.join(vendorDir, name)))) {
    return {
      engine: path.join(vendorDir, "engine.js"),
      presets: path.join(vendorDir, "presets.json"),
      weights: path.join(vendorDir, "weights.npz"),
    };
  }
  return {
    engine: path.join(repoRoot, "codehygiene", "engine.js"),
    presets: path.resolve(webDir, "../presets.json"),
    weights: path.join(repoRoot, "codehygiene", "weights.npz"),
  };
}

function sharedFilesPlugin(shared) {
  const targets = {
    "shared:engine": shared.engine,
    "shared:presets": shared.presets,
  };
  return {
    name: "shared-files",
    setup(build) {
      build.onResolve({ filter: /^shared:/ }, (args) => {
        const target = targets[args.path];
        return target ? { path: target } : { errors: [{ text: `Unknown shared file ${args.path}` }] };
      });
    },
  };
}

const PAGES = { "board.html": "leaderboard", "privacy.html": "privacy" };
const HASHED_ASSETS = [
  "app.js",
  "board.js",
  "score-worker.js",
  "styles.css",
  "board.css",
  "privacy.css",
  "weights.npz",
];
const ASSET_TAG_RE = /(<(?:link|script)\b[^>]*?\b(?:href|src)=")((?:\.\.\/)?[a-z0-9-]+\.(?:css|js))(")/gi;

async function computeAssetVersion() {
  const hash = createHash("sha256");
  for (const name of HASHED_ASSETS) {
    const filePath = path.join(distDir, name);
    if (existsSync(filePath)) {
      hash.update(name);
      hash.update(await readFile(filePath));
    }
  }
  return hash.digest("hex").slice(0, 10);
}

async function writeVersionedHtml(srcHtmlPath, destHtmlPath, version) {
  const rawHtml = await readFile(srcHtmlPath, "utf8");
  const versioned = rawHtml.replace(ASSET_TAG_RE, `$1$2?v=${version}$3`);
  await writeFile(destHtmlPath, versioned, "utf8");
}

async function copyStatic(shared) {
  await copyFile(shared.weights, path.join(distDir, "weights.npz"));
  const version = await computeAssetVersion();
  await writeVersionedHtml(path.join(srcDir, "index.html"), path.join(distDir, "index.html"), version);
  for (const [page, folder] of Object.entries(PAGES)) {
    await mkdir(path.join(distDir, folder), { recursive: true });
    await writeVersionedHtml(path.join(srcDir, page), path.join(distDir, folder, "index.html"), version);
  }
}

const copyStaticPlugin = (shared) => ({
  name: "copy-static",
  setup(build) {
    build.onEnd(async (result) => {
      if (result.errors.length === 0) {
        await copyStatic(shared);
      }
    });
  },
});

async function main() {
  const shared = sharedPaths();
  await rm(distDir, { recursive: true, force: true });
  await mkdir(distDir, { recursive: true });

  const context = await esbuild.context({
    entryPoints: {
      app: path.join(srcDir, "main.js"),
      board: path.join(srcDir, "board.js"),
      "score-worker": path.join(srcDir, "score-worker.js"),
      styles: path.join(srcDir, "styles.css"),
      privacy: path.join(srcDir, "privacy.css"),
    },
    outdir: distDir,
    entryNames: "[name]",
    assetNames: "fonts/[name]-[hash]",
    bundle: true,
    format: "esm",
    target: ["es2022", "chrome123", "safari17.5", "firefox120"],
    minify: !watch,
    sourcemap: watch,
    legalComments: "none",
    loader: { ".woff2": "file" },
    logLevel: "info",
    plugins: [sharedFilesPlugin(shared), copyStaticPlugin(shared)],
  });

  if (watch) {
    await context.watch();
    return;
  }
  await context.rebuild();
  await context.dispose();
}

await main();