From b91c61d23d390ce701f453930d3e9bcb091cc538 Mon Sep 17 00:00:00 2001
From: Cheng Shao <terrorjack@type.dance>
Date: Sun, 16 Mar 2025 20:44:24 +0000
Subject: [PATCH] wasm: fix post-link.mjs for browser

The wasm ghci browser mode needs to run dyld.mjs in the browser which
imports post-link.mjs. This script makes post-link.mjs runnable in the
browser by deferring node-specific module imports to their actual use
sites.

(cherry picked from commit efcebed66456b704654b6014bf0781109cea1c40)
---
 utils/jsffi/post-link.mjs | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/utils/jsffi/post-link.mjs b/utils/jsffi/post-link.mjs
index b5493f35817..fda430fe40a 100755
--- a/utils/jsffi/post-link.mjs
+++ b/utils/jsffi/post-link.mjs
@@ -7,10 +7,6 @@
 // foo.js", as well as an exported postLink function that takes a
 // WebAssembly.Module object and returns the ESM module content.
 
-import fs from "node:fs/promises";
-import path from "node:path";
-import util from "node:util";
-
 // Each record in the ghc_wasm_jsffi custom section are 3
 // NUL-terminated strings: name, binder, body. We try to parse the
 // body as an expression and fallback to statements, and return the
@@ -94,6 +90,9 @@ export function parseSections(mod) {
 // immediately invokes it by passing the right magic variables.
 
 export async function postLink(mod) {
+  const fs = (await import("node:fs/promises")).default;
+  const path = (await import("node:path")).default;
+
   let src = (
     await fs.readFile(path.join(import.meta.dirname, "prelude.mjs"), {
       encoding: "utf-8",
@@ -116,10 +115,17 @@ export async function postLink(mod) {
 }
 
 function isMain() {
+  if (!globalThis?.process?.versions?.node) {
+    return false;
+  }
+
   return import.meta.filename === process.argv[1];
 }
 
 async function main() {
+  const fs = (await import("node:fs/promises")).default;
+  const util = (await import("node:util")).default;
+
   const { input, output } = util.parseArgs({
     options: {
       input: {
-- 
GitLab