Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: fix dynamic import error in .cjs
  • Loading branch information
sahar-fehri committed Oct 6, 2024
commit d106c7fe457e11c9839aeaed710c832d19c2e7aa
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
diff --git a/dist/assetsUtil.cjs b/dist/assetsUtil.cjs
index e90a1b6767bc8ac54b7a4d580035cf5db6861dca..cbda9aba94bff918ef2ff56466f0239ce053d441 100644
--- a/dist/assetsUtil.cjs
+++ b/dist/assetsUtil.cjs
@@ -2,6 +2,7 @@
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
+function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchTokenContractExchangeRates = exports.reduceInBatchesSerially = exports.divideIntoBatches = exports.ethersBigNumberToBN = exports.addUrlProtocolPrefix = exports.getFormattedIpfsUrl = exports.getIpfsCIDv1AndPath = exports.removeIpfsProtocolPrefix = exports.isTokenListSupportedForNetwork = exports.isTokenDetectionSupportedForNetwork = exports.SupportedTokenDetectionNetworks = exports.formatIconUrlWithProxy = exports.formatAggregatorNames = exports.hasNewCollectionFields = exports.compareNftMetadata = exports.TOKEN_PRICES_BATCH_SIZE = void 0;
const controller_utils_1 = require("@metamask/controller-utils");
@@ -221,7 +222,7 @@ async function getIpfsCIDv1AndPath(ipfsUrl) {
const index = url.indexOf('/');
const cid = index !== -1 ? url.substring(0, index) : url;
const path = index !== -1 ? url.substring(index) : undefined;
- const { CID } = await import("multiformats");
+ const { CID } = await Promise.resolve().then(() => _interopRequireWildcard(require("multiformats")));
Copy link
Contributor

@MajorLift MajorLift Oct 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The await import() call being left in there was intentional. Not only is await import() available to commonjs in node v12+, passing an ESM-only module like multiformats into require also crashes node or otherwise may cause undefined behavior.

The import call causing failed test runs is also expected, because dynamic import is only available behind a NODE_OPTIONS=--experimental-vm-modules flag. This is why we've added that to all of our core test scripts (https://github.com/MetaMask/core/blob/main/packages/assets-controllers/package.json#L44-L47). We'll probably need to do the same in extension and mobile.

I guess the question here is whether we can be sure that _interopRequireWildcard is actually executing the CID import correctly, or if it's masking broken behavior.

Another question would be how to handle similar scenarios (upstream ESM-only modules) going forward. Consistently using await import() is the only way that makes sense to me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MajorLift thnx a lot for looking into this 🙏 I have added some logs with this current patch and it looks like its working fine, its able to fetch CID and display the NFT media;

Without the patch, i can see the error __import__ is not defined in console again and its not displaying the images correctly;
Screenshot 2024-10-07 at 19 05 08

Thanks for referencing the related test script update on core 🙏 this is not only related to tests, correct? since im able to see the error when running the app locally?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The browser uses only ESM, so that's a really weird error message. Maybe it's coming from selenium or some other node process? I tried adding the flag to the e2e test build scripts (#27675) but I'm still getting the same error.

Since you verified that the import is working correctly I think we can move forward with the current patch. Thanks for being on top of that.

Would be nice to figure this error out for the future though. I'll do some more digging.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is running under lavamoat and dynamic import is deliberately not supported - hence a transform changing all functions named import into __import__

We currently can't have dynamic import work inside compartments. It's not feasible to intercept it the way we'd need to. Since the bundler we use doesn't support it, the dynamic import would be called directly in the browser and "multiformats" is not a URL to a script file, so it would fail with a different error even if LavaMoat transforms weren't there to prevent it.
I recommend addressing this somehow in a minor refactor of the assets controller if it's intended for use in MetaMask.

When we switch to webpack with LavaMoat webpack plugin it's possible webpack will transform the dynamic import into its own syntax if configured for that, but that's the only hope for using dynamic require I see for now. Didn't check how that behaves yet. I can get back to you later.

Copy link
Contributor

@MajorLift MajorLift Oct 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@naugtur Thanks for the insight! I wasn't aware that Lavamoat did this. I'll have to look into what else it blocks.

Unfortunately this a language-level CJS/ESM interop issue that isn't specific to assets-controllers and multiformats -- it applies to any ESM-only module in our dependency tree.

Most of our modules are natively CJS. We use ESM syntax because we write in TypeScript, but we expose dual CJS/ESM builds and our manifests do not specify the "module": "type" property. Because of this, the only way for our modules to handle ESM imports in a CJS-compatible manner is with dynamic import syntax i.e. require doesn't work, and neither does static import syntax that transpiles down to require.

True CommonJS modules can require an ESM-transpiled-to-CJS module, since they’re both CommonJS at runtime. But in Node.js, require crashes if it resolves to an ES module. This means published libraries cannot migrate from transpiled modules to true ESM without breaking their CommonJS (true or transpiled) consumers:

// @Filename: node_modules/dependency/index.js
export function doSomething() { /* ... */ }
// @Filename: dependent.js
import { doSomething } from "dependency";
// ✅ Works if dependent and dependency are both transpiled
// ✅ Works if dependent and dependency are both true ESM
// ✅ Works if dependent is true ESM and dependency is transpiled
// 💥 Crashes if dependent is transpiled and dependency is true ESM

https://www.typescriptlang.org/docs/handbook/modules/appendices/esm-cjs-interop.html#cannot-require-a-true-es-module

This issue was previously masked by our usage of the outdated { module: "commonjs", moduleResolution: "node10" } tsconfig options. However, the core and snaps repos recently updated to "node16" for both options, which enforces sound module resolution restrictions and therefore prohibits ESM-only modules from being passed into require calls. This update is expected to propagate to all of our TypeScript repos.

In this specific case, we can use the patch as is because multiformats happens to work with require calls without breaking things, but this is a coincidence we can't rely on for all ESM packages in general.

To preserve the ban on dynamic import syntax I see three possibilities:

  1. Remove all ESM-only modules from all of our dependency trees, or replace them with CJS-compatible forks (we've done this before e.g. @metamask/superstruct).
  2. Convert all of our modules to "true ESM".
  3. Start using a bundler like Webpack in all of our repos to generate builds (assuming it can be set up to generate dual builds for dependencies in a way that would sidestep this issue).

All of these would be major, if not prohibitive, undertakings.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 and 2 are not options we're fond of.
With the exception of: until we have a lavamoat-node that supports ESM (we're working on it) we might sometimes have to eliminate esm-only packages from builds that run under lavamoat.

We should be able to switch to webpack in the foreseeable future. LavaMoat Webpack plugin is reaching 1.0 by the end of this year and we're wery close to getting a working MetaMask build out of it. 3rdparty audit is finishing too.

Meanwhile,
Joyee has made it possible to require(esm) in Node.js
https://nodejs.org/api/esm.html#interoperability-with-commonjs
https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/

So we're looking for a solution to the typescript situation that we can live with for limited time.

Copy link
Contributor

@MajorLift MajorLift Oct 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that 1, 2 aren't the most ideal options. ;)

I wasn't aware of --experimental-require-module, but it looks like a great stopgap. Fingers crossed that we don't run into an ESM package with top-level await.

Based on anecdotal experience from applying Node16 to core and snaps, our usage of CJS-incompatible packages is uncommon enough that we should be able to handle them on a case-by-case basis, at least for the time being.

However, the few exceptions can have an outsized impact. Migrating from superstruct to @metamask/superstruct ended up being a massive undertaking because it required us to update and release basically all transitive dependents. Removing the imports for such a widely used package will probably present difficulties as well. Hopefully we don't come across such a scenario again any time soon.

Anyway, it's very good to know that there are fundamental fixes on the way, and thank you for your work on that! Especially excited to potentially have lavamoat-node directly applied to our upstream libraries.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Going back to the change itself:

The await on an empty promise before running synchronous require seems unnecessary. Does anything depend on this step being asynchronous? Doesn't seem so.

Suggested change
+ const { CID } = await Promise.resolve().then(() => _interopRequireWildcard(require("multiformats")));
+ const { CID } = _interopRequireWildcard(require("multiformats"));

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think in v37 this change was introduced:
BREAKING: getIpfsCIDv1AndPath, getFormattedIpfsUrl are now async functions (MetaMask/core#3645)

This patch update matches the generated build after the V37 update;

Copy link
Contributor

@MajorLift MajorLift Oct 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The await is necessary in the CJS source code since we're forced to use a dynamic import. But in the build output that we're patching we definitely don't need to both then and await the synchronous _interopRequireWildcard call.

@naugtur's suggestion looks good to me, although I'd feel better with another manual check on whether CID is sourced at runtime.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @MajorLift and @naugtur 🙏 i have removed the empty promise; could you please approve again and we merge this 🙏

// We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)
// because most cid v0s appear to be incompatible with IPFS subdomains
return {
2 changes: 1 addition & 1 deletion lavamoat/browserify/beta/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,6 @@
"Headers": true,
"URL": true,
"URLSearchParams": true,
"__import__": true,
"clearInterval": true,
"clearTimeout": true,
"console.error": true,
Expand All @@ -694,6 +693,7 @@
"setTimeout": true
},
"packages": {
"@ensdomains/content-hash>multicodec>uint8arrays>multiformats": true,
"@ethereumjs/tx>@ethereumjs/util": true,
"@ethersproject/contracts": true,
"@ethersproject/providers": true,
Expand Down
2 changes: 1 addition & 1 deletion lavamoat/browserify/flask/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,6 @@
"Headers": true,
"URL": true,
"URLSearchParams": true,
"__import__": true,
"clearInterval": true,
"clearTimeout": true,
"console.error": true,
Expand All @@ -694,6 +693,7 @@
"setTimeout": true
},
"packages": {
"@ensdomains/content-hash>multicodec>uint8arrays>multiformats": true,
"@ethereumjs/tx>@ethereumjs/util": true,
"@ethersproject/contracts": true,
"@ethersproject/providers": true,
Expand Down
2 changes: 1 addition & 1 deletion lavamoat/browserify/main/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,6 @@
"Headers": true,
"URL": true,
"URLSearchParams": true,
"__import__": true,
"clearInterval": true,
"clearTimeout": true,
"console.error": true,
Expand All @@ -694,6 +693,7 @@
"setTimeout": true
},
"packages": {
"@ensdomains/content-hash>multicodec>uint8arrays>multiformats": true,
"@ethereumjs/tx>@ethereumjs/util": true,
"@ethersproject/contracts": true,
"@ethersproject/providers": true,
Expand Down
2 changes: 1 addition & 1 deletion lavamoat/browserify/mmi/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,6 @@
"Headers": true,
"URL": true,
"URLSearchParams": true,
"__import__": true,
"clearInterval": true,
"clearTimeout": true,
"console.error": true,
Expand All @@ -786,6 +785,7 @@
"setTimeout": true
},
"packages": {
"@ensdomains/content-hash>multicodec>uint8arrays>multiformats": true,
"@ethereumjs/tx>@ethereumjs/util": true,
"@ethersproject/contracts": true,
"@ethersproject/providers": true,
Expand Down
10 changes: 9 additions & 1 deletion lavamoat/build-system/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -2117,7 +2117,8 @@
"chokidar>normalize-path": true,
"chokidar>readdirp": true,
"del>is-glob": true,
"eslint>glob-parent": true
"eslint>glob-parent": true,
"tsx>fsevents": true
}
},
"chokidar>anymatch": {
Expand Down Expand Up @@ -8888,6 +8889,13 @@
"typescript": true
}
},
"tsx>fsevents": {
"globals": {
"console.assert": true,
"process.platform": true
},
"native": true
},
"typescript": {
"builtin": {
"buffer.Buffer": true,
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@
"@metamask/address-book-controller": "^6.0.0",
"@metamask/announcement-controller": "^7.0.0",
"@metamask/approval-controller": "^7.0.0",
"@metamask/assets-controllers": "^38.2.0",
"@metamask/assets-controllers": "patch:@metamask/assets-controllers@npm%3A38.2.0#~/.yarn/patches/@metamask-assets-controllers-npm-38.2.0-40af2afaa7.patch",
"@metamask/base-controller": "^7.0.0",
"@metamask/bitcoin-wallet-snap": "^0.6.0",
"@metamask/browser-passworder": "^4.3.0",
Expand Down
3 changes: 2 additions & 1 deletion privacy-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,12 @@
"static.cx.metamask.io",
"swap.api.cx.metamask.io",
"test.metamask-phishing.io",
"thumb.canalplus.pro",
"token.api.cx.metamask.io",
"tokens.api.cx.metamask.io",
"tx-sentinel-ethereum-mainnet.api.cx.metamask.io",
"unresponsive-rpc.test",
"unresponsive-rpc.url",
"user-storage.api.cx.metamask.io",
"www.4byte.directory"
]
]
42 changes: 40 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4861,7 +4861,7 @@ __metadata:
languageName: node
linkType: hard

"@metamask/assets-controllers@npm:^38.2.0":
"@metamask/assets-controllers@npm:38.2.0":
version: 38.2.0
resolution: "@metamask/assets-controllers@npm:38.2.0"
dependencies:
Expand Down Expand Up @@ -4899,6 +4899,44 @@ __metadata:
languageName: node
linkType: hard

"@metamask/assets-controllers@patch:@metamask/assets-controllers@npm%3A38.2.0#~/.yarn/patches/@metamask-assets-controllers-npm-38.2.0-40af2afaa7.patch":
version: 38.2.0
resolution: "@metamask/assets-controllers@patch:@metamask/assets-controllers@npm%3A38.2.0#~/.yarn/patches/@metamask-assets-controllers-npm-38.2.0-40af2afaa7.patch::version=38.2.0&hash=781868"
dependencies:
"@ethereumjs/util": "npm:^8.1.0"
"@ethersproject/address": "npm:^5.7.0"
"@ethersproject/bignumber": "npm:^5.7.0"
"@ethersproject/contracts": "npm:^5.7.0"
"@ethersproject/providers": "npm:^5.7.0"
"@metamask/abi-utils": "npm:^2.0.3"
"@metamask/base-controller": "npm:^7.0.1"
"@metamask/contract-metadata": "npm:^2.4.0"
"@metamask/controller-utils": "npm:^11.3.0"
"@metamask/eth-query": "npm:^4.0.0"
"@metamask/metamask-eth-abis": "npm:^3.1.1"
"@metamask/polling-controller": "npm:^10.0.1"
"@metamask/rpc-errors": "npm:^6.3.1"
"@metamask/utils": "npm:^9.1.0"
"@types/bn.js": "npm:^5.1.5"
"@types/uuid": "npm:^8.3.0"
async-mutex: "npm:^0.5.0"
bn.js: "npm:^5.2.1"
cockatiel: "npm:^3.1.2"
immer: "npm:^9.0.6"
lodash: "npm:^4.17.21"
multiformats: "npm:^13.1.0"
single-call-balance-checker-abi: "npm:^1.0.0"
uuid: "npm:^8.3.2"
peerDependencies:
"@metamask/accounts-controller": ^18.0.0
"@metamask/approval-controller": ^7.0.0
"@metamask/keyring-controller": ^17.0.0
"@metamask/network-controller": ^21.0.0
"@metamask/preferences-controller": ^13.0.0
checksum: 10/0e6f0e7e6e11e2cc7e0c4603f76992a658fd0e0104e4331bf0086e173677a70a32aedf26a5fd75703b35ef799f4f23721fb11b7709595e27feb2e11d10973a31
languageName: node
linkType: hard

"@metamask/auto-changelog@npm:^2.1.0":
version: 2.6.1
resolution: "@metamask/auto-changelog@npm:2.6.1"
Expand Down Expand Up @@ -26079,7 +26117,7 @@ __metadata:
"@metamask/announcement-controller": "npm:^7.0.0"
"@metamask/api-specs": "npm:^0.9.3"
"@metamask/approval-controller": "npm:^7.0.0"
"@metamask/assets-controllers": "npm:^38.2.0"
"@metamask/assets-controllers": "patch:@metamask/assets-controllers@npm%3A38.2.0#~/.yarn/patches/@metamask-assets-controllers-npm-38.2.0-40af2afaa7.patch"
"@metamask/auto-changelog": "npm:^2.1.0"
"@metamask/base-controller": "npm:^7.0.0"
"@metamask/bitcoin-wallet-snap": "npm:^0.6.0"
Expand Down