zenparsing / node-web-modules

Web Modules for Node.js
8 stars 0 forks source link

Consider moving node native module virtualization to MVP #8

Open zenparsing opened 5 years ago

zenparsing commented 5 years ago

There are various use cases for mutating node's built-in modules. For example, an application may want to instrument all calls to require('https').request and may do so by overwriting the "request" property of the export object associated with the "https" module. Since that exports object is shared by all module that require "https", modifications will be visible.

It would be desirable to support similar virtualization capabilities for web modules. The option currently implemented in node is to replace the exports object with a proxy. The proxy is then responsible for notifying the ES "shim" that a property has been changed. The ES "shim" then updates it's internal variable bindings to reflect the changes.

It's not clear to me that replacing buit-in exports objects is backward compatible. In addition, I think that the virtualization problem space needs more thought. For instance, using the proxy approach, built-ins can only be virtualized from CommonJS modules. They cannot be virtualized from ES modules.

Should built-in virtualization be brought into MVP?

zenparsing commented 5 years ago

What is the workaround if we do not support virtualization in the MVP?

In order for the native module's ESM shim to see overwritten properties, virtualization must happen before the evaluation phase of the native module's ESM shim.

Virtualizing code can be run in preload scripts (with the --require flag):

node -r virtualizer -m main.js

or within an ES module that is imported before any native modules import declarations in the application's main file:

import 'virtualizer'; // Must be first import in app main
import { readFile } from 'fs';

Are these workarounds sufficient for MVP?