Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: replace module interceptor with guarded require #871

Merged
merged 4 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/loud-bats-retire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@callstack/repack": patch
---

Add error boundary around webpack's require function to match Metro's error handling behavior more closely
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,18 @@ jest.mock('../NativeScriptManager', () => ({
},
}));

globalThis.__webpack_require__ = {
i: [],
l: () => {},
u: (id: string) => `${id}.chunk.bundle`,
p: () => '',
repack: {
shared: { scriptManager: undefined },
},
const webpackRequire = () => [];

webpackRequire.i = [] as any[];
webpackRequire.l = () => {};
webpackRequire.u = (id: string) => `${id}.chunk.bundle`;
webpackRequire.p = () => '';
webpackRequire.repack = {
shared: { scriptManager: undefined },
};

globalThis.__webpack_require__ = webpackRequire;

class FakeCache {
data: Record<string, string> = {};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type {
Compiler,
RuntimeModule as RuntimeModuleType,
} from '@rspack/core';

interface GuardedRequireRuntimeModuleConfig {
globalObject: string;
}

// runtime module class is generated dynamically based on the compiler instance
// this way it's compatible with both webpack and rspack
export const makeGuardedRequireRuntimeModule = (
compiler: Compiler,
moduleConfig: GuardedRequireRuntimeModuleConfig
): RuntimeModuleType => {
const Template = compiler.webpack.Template;
const RuntimeModule = compiler.webpack.RuntimeModule;

const GuardedRequireRuntimeModule = class extends RuntimeModule {
constructor(private config: GuardedRequireRuntimeModuleConfig) {
super('repack/guarded require', RuntimeModule.STAGE_NORMAL);
}

generate() {
return Template.asString([
Template.getFunctionContent(
require('./implementation/guardedRequire.js')
).replaceAll('$globalObject$', this.config.globalObject),
]);
}
};

return new GuardedRequireRuntimeModule(moduleConfig);
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const makeInitRuntimeModule = (

const InitRuntimeModule = class extends RuntimeModule {
constructor(private config: InitRuntimeModuleConfig) {
super('repack/init', RuntimeModule.STAGE_BASIC);
super('repack/init', RuntimeModule.STAGE_NORMAL);
}

generate() {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'node:path';
import type { Compilation, Compiler, RspackPluginInstance } from '@rspack/core';
import type { RuntimeModule as WebpackRuntimeModule } from 'webpack';
import { makeGuardedRequireRuntimeModule } from './GuardedRequireRuntimeModule.js';
import { makeInitRuntimeModule } from './InitRuntimeModule.js';
import { makeLoadScriptRuntimeModule } from './LoadScriptRuntimeModule.js';
import { makeModuleErrorHandlerRuntimeModule } from './ModuleErrorHandlerRuntimeModule.js';

type RspackRuntimeModule = Parameters<
Compilation['hooks']['runtimeModule']['call']
Expand Down Expand Up @@ -62,11 +62,6 @@ export class RepackTargetPlugin implements RspackPluginInstance {
compiler.options.output.chunkFormat = 'array-push';
compiler.options.output.globalObject = globalObject;

// Disable built-in strict module error handling
// this is handled through an interceptor in the
// init module added to __webpack_require__.i array
compiler.options.output.strictModuleErrorHandling = false;

// Normalize global object.
new compiler.webpack.BannerPlugin({
raw: true,
Expand Down Expand Up @@ -104,12 +99,12 @@ export class RepackTargetPlugin implements RspackPluginInstance {
(chunk) => {
compilation.addRuntimeModule(
chunk,
makeInitRuntimeModule(compiler, { globalObject })
makeGuardedRequireRuntimeModule(compiler, { globalObject })
);

compilation.addRuntimeModule(
chunk,
makeModuleErrorHandlerRuntimeModule(compiler, { globalObject })
makeInitRuntimeModule(compiler, { globalObject })
);
}
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
var $globalObject$: Record<string, any>;

module.exports = function () {
// This flag prevents nested error handling when __webpack_require__
// is called from within another __webpack_require__ call.
var inGuard = false;
var originalWebpackRequire = __webpack_require__;

// wrap __webpack_require__ calls to forward errors to global.ErrorUtils
// aligned with `guardedLoadModule` behaviour in Metro
// https://github.com/facebook/metro/blob/a4cb0b0e483748ef9f1c760cb60c57e3a84c1afd/packages/metro-runtime/src/polyfills/require.js#L329
function guardedWebpackRequire(moduleId: string) {
if (!inGuard && $globalObject$.ErrorUtils) {
inGuard = true;
let exports;
try {
exports = originalWebpackRequire(moduleId);
} catch (e) {
// exposed as global early on, part of `@react-native/js-polyfills` error-guard
// https://github.com/facebook/react-native/blob/4dac99cf6d308e804efc098b37f5c24c1eb611cf/packages/polyfills/error-guard.js#L121
$globalObject$.ErrorUtils.reportFatalError(e);
}
inGuard = false;
return exports;
} else {
return originalWebpackRequire(moduleId);
}
}

// Copy all properties from the original function to the wrapped function
Object.getOwnPropertyNames(originalWebpackRequire).forEach((key) => {
// @ts-ignore
guardedWebpackRequire[key] = originalWebpackRequire[key];
});

// @ts-ignore
// replace __webpack_require__ with the wrapped version
__webpack_require__ = guardedWebpackRequire;
};

This file was deleted.

1 change: 1 addition & 0 deletions packages/repack/src/types/runtime-globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ declare namespace RepackRuntimeGlobals {
declare type WebpackGetChunkScriptFilename = (id: string) => string;

declare type WebpackRequire = {
(moduleId: string): ModuleExports;
i: WebpackModuleExecutionInterceptor;
l: WebpackLoadScript;
p: WebpackPublicPath;
Expand Down
Loading