aboutsummaryrefslogtreecommitdiff
path: root/packages/bun-inspector-frontend/build.ts
blob: b45a3549f6a570e4153ea0a36d55f3557c2e70c4 (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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { build } from "esbuild";
import { copyFileSync, mkdirSync, readdirSync, rmSync, statSync } from "fs";
import { join } from "path";

try {
  const basePath = join(import.meta.dir, "../../src/bun.js/WebKit/Source/WebInspectorUI/UserInterface");
  const htmlPath = join(basePath, "Main.html");
  const backendCommands = join(
    import.meta.dir,
    "../../src/bun.js/WebKit/WebKitBuild/Release/JavaScriptCore/DerivedSources/inspector/InspectorBackendCommands.js",
  );
  const scriptsToBundle = [];
  const stylesToBundle = [];
  const jsReplacementId = crypto.randomUUID() + ".js";
  const cssReplacementId = crypto.randomUUID() + ".css";
  const html = new HTMLRewriter()
    .on("script", {
      element(element) {
        const src = element.getAttribute("src");
        if (
          src &&
          !src?.includes("External") &&
          !src?.includes("WebKitAdditions") &&
          !src.includes("DOMUtilities.js")
        ) {
          if (scriptsToBundle.length === 0) {
            element.replace("<script>var WI = {};\n</script>", { html: true });
          } else {
            element.remove();
          }

          scriptsToBundle.push(src);
        }
      },
    })
    .on("script:not([src])", {
      element(element) {
        element.remove();
      },
    })
    .on("head", {
      element(element) {
        element.prepend(
          `
          <script type="text/javascript">
        if (!Element.prototype.scrollIntoViewIfNeeded) {
          Element.prototype.scrollIntoViewIfNeeded = function (centerIfNeeded) {
            centerIfNeeded = arguments.length === 0 ? true : !!centerIfNeeded;
        
            var parent = this.parentNode,
                parentComputedStyle = window.getComputedStyle(parent, null),
                parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')),
                parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')),
                overTop = this.offsetTop - parent.offsetTop < parent.scrollTop,
                overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight),
                overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft,
                overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth),
                alignWithTop = overTop && !overBottom;
        
            if ((overTop || overBottom) && centerIfNeeded) {
              parent.scrollTop = this.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + this.clientHeight / 2;
            }
        
            if ((overLeft || overRight) && centerIfNeeded) {
              parent.scrollLeft = this.offsetLeft - parent.offsetLeft - parent.clientWidth / 2 - parentBorderLeftWidth + this.clientWidth / 2;
            }
        
            if ((overTop || overBottom || overLeft || overRight) && !centerIfNeeded) {
              this.scrollIntoView(alignWithTop);
            }
          };
        }
        </script>
        <base href="/" /> `,
          { html: true },
        );

        element.append(
          `
        <style>
            body {
                --undocked-title-area-height: 0px !important;
            }
        </style>
        <script src="${jsReplacementId}"></script>

        <script type="text/javascript">
            WI.sharedApp = new WI.AppController;
            WI.sharedApp.initialize();
        </script>`,
          { html: true },
        );
      },
    })
    //   .on("link[rel=stylesheet]", {
    //     element(element) {
    //       const href = element.getAttribute("href");
    //       if (href && !href?.includes("External") && !href?.includes("WebKitAdditions")) {
    //         element.remove();
    //         stylesToBundle.push(href);
    //       }
    //     },
    //   })
    .transform(new Response(Bun.file(htmlPath)));
  let htmlText = await html.text();
  rmSync(join(import.meta.dir, "out"), { recursive: true, force: true });
  mkdirSync(join(import.meta.dir, "out", "Protocol"), { recursive: true });

  const javascript = scriptsToBundle.map(a => `import '${join(basePath, a)}';`).join("\n") + "\n";
  // const css = stylesToBundle.map(a => `@import "${join(basePath, a)}";`).join("\n") + "\n";
  await Bun.write(join(import.meta.dir, "out/manifest.js"), javascript);
  mkdirSync("out/WebKitAdditions/WebInspectorUI/", { recursive: true });
  await Bun.write(join(import.meta.dir, "out/WebKitAdditions/WebInspectorUI/WebInspectorUIAdditions.js"), "");
  await Bun.write(join(import.meta.dir, "out/WebKitAdditions/WebInspectorUI/WebInspectorUIAdditions.css"), "");
  // await Bun.write(join(import.meta.dir, "manifest.css"), css);
  const jsBundle = await Bun.build({
    entrypoints: [join(import.meta.dir, "out/manifest.js")],
    outdir: "out",
    minify: true,
  });
  const jsFilename = "manifest-" + jsBundle.outputs[0].hash + ".js";
  // const cssBundle = await build({
  //   bundle: true,
  //   minify: true,
  //   write: false,
  //   entryPoints: [join(import.meta.dir, "manifest.css")],
  //   outdir: "out",
  //   loader: {
  //     ".css": "css",
  //     ".svg": "dataurl",
  //   },
  //   external: ["*.png"],
  //   plugins: [
  //     {
  //       name: "css",
  //       setup(build) {
  //         build.onResolve({ filter: new RegExp("/Images/Warning.svg") }, args => ({
  //           path: join(basePath, "Images/Warning.svg"),
  //         }));
  //       },
  //     },
  //   ],
  // });

  // const cssFilename = "manifest-" + cssBundle.outputFiles[0].hash.replaceAll("/", "_") + ".css";
  htmlText = htmlText.replace(jsReplacementId, jsFilename);
  // htmlText = htmlText.replace(cssReplacementId, cssFilename);
  await Bun.write(join(import.meta.dir, "out", jsFilename), jsBundle.outputs[0]);
  // await Bun.write(join(import.meta.dir, "out", cssFilename), cssBundle.outputFiles[0].text);
  await Bun.write(join(import.meta.dir, "out", "index.html"), htmlText);
  await Bun.write(join(import.meta.dir, "out", "index.html"), htmlText);
  await Bun.write(join(import.meta.dir, "out", "Protocol", "InspectorBackendCommands.js"), Bun.file(backendCommands));

  function recursiveCopy(src, dest) {
    readdirSync(src).forEach(file => {
      const srcPath = join(src, file);
      const destPath = join(dest, file);
      if (statSync(srcPath).isDirectory()) {
        mkdirSync(destPath, { recursive: true });
        recursiveCopy(srcPath, destPath);
      } else {
        rmSync(destPath, { force: true });
        copyFileSync(srcPath, destPath);
      }
    });
  }

  recursiveCopy(basePath, join(import.meta.dir, "out"));
} catch (e) {
  console.error("Failed to build. Please make sure you've ran `make jsc` locally.");
  throw e;
}