Skip to content

Commit

Permalink
feat: Added fallback for webpack modules
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Oct 30, 2022
1 parent f3e63a0 commit b54a03b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
57 changes: 53 additions & 4 deletions src/webpack/index.ts
Expand Up @@ -55,6 +55,11 @@ export let webpackRequire: (<T = any>(moduleId: string) => T) & {
e: (id: string) => Promise<void>;
};

/**
* Fallback modules for forward compatibility
*/
export const fallbackModules: { [key: string]: any } = {};

export function injectLoader(): void {
if (isInjected) {
return;
Expand Down Expand Up @@ -173,6 +178,23 @@ export function searchId(
continue;
}
}

ids = Object.keys(fallbackModules);

for (const moduleId of ids) {
try {
const module = fallbackModules[moduleId];

if (condition(module, moduleId)) {
debug(`Fallback Module found: ${moduleId} - ${condition.toString()}`);
clearTimeout(timer);
return moduleId;
}
} catch (error) {
continue;
}
}

debug(`Module not found: ${condition.toString()}`);
return null;
}
Expand All @@ -188,11 +210,11 @@ export function search<T = any>(
): T | null {
const moduleId = searchId(condition, reverse);

if (moduleId) {
return webpackRequire(moduleId) as T;
if (!moduleId) {
return null;
}

return null;
return loadModule<T>(moduleId);
}
/**
* Return the webpack module from a search function
Expand All @@ -216,7 +238,7 @@ export function modules(
}

try {
const module = webpackRequire(moduleId);
const module = loadModule(moduleId);

if (!condition || condition(module, moduleId)) {
modules[moduleId] = module;
Expand All @@ -233,3 +255,30 @@ export function modules(

return modules;
}

export function loadModule<T = any>(moduleId: string) {
const module = /^\d+$/.test(moduleId)
? webpackRequire(moduleId)
: fallbackModules[moduleId];

return module as T;
}

/**
* Inject a new module content
* @param moduleId Module ID
* @param content The module content
* @returns
*/
export function injectFallbackModule(
moduleId: number | string,
content: any
): void {
moduleId = moduleId + '';

if (/^\d+$/.test(moduleId)) {
throw new Error('Invalid fallback ID');
}

fallbackModules[moduleId] = content;
}
4 changes: 2 additions & 2 deletions src/whatsapp/exportModule.ts
Expand Up @@ -68,7 +68,7 @@ export function exportModule(
return undefined;
}

const module = webpack.webpackRequire(moduleId);
const module = webpack.loadModule(moduleId);

if (Array.isArray(property)) {
for (const p of property) {
Expand Down Expand Up @@ -188,7 +188,7 @@ export function wrapModuleFunction<TFunc extends (...args: any[]) => any>(
return;
}

const module = webpack.webpackRequire(moduleId);
const module = webpack.loadModule(moduleId);

const functionPath = functionPathMap.get(func);

Expand Down

0 comments on commit b54a03b

Please sign in to comment.