Skip to content
15 changes: 14 additions & 1 deletion packages/data-prefetch/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import path from 'path';
import fs from 'fs-extra';

import {
bindLoggerToCompiler,
createInfrastructureLogger,
createLogger,
encodeName,
moduleFederationPlugin,
MFPrefetchCommon,
Expand All @@ -18,6 +21,15 @@ const { RuntimeGlobals, Template } = require(
normalizeWebpackPath('webpack'),
) as typeof import('webpack');

const createBundlerLogger: typeof createLogger =
typeof createInfrastructureLogger === 'function'
? (createInfrastructureLogger as unknown as typeof createLogger)
: createLogger;

const logger = createBundlerLogger(
'[ Module Federation Data Prefetch Plugin ]',
);

export function getFederationGlobalScope(
runtimeGlobals: typeof RuntimeGlobals,
): string {
Expand All @@ -35,6 +47,7 @@ export class PrefetchPlugin implements WebpackPluginInstance {

// eslint-disable-next-line max-lines-per-function
apply(compiler: Compiler) {
bindLoggerToCompiler(logger, compiler, 'PrefetchPlugin');
const { name, exposes } = this.options;
if (!exposes) {
return;
Expand All @@ -54,7 +67,7 @@ export class PrefetchPlugin implements WebpackPluginInstance {
}
if (this.options.shareStrategy !== SHARED_STRATEGY) {
this.options.shareStrategy = SHARED_STRATEGY;
console.warn(
logger.warn(
`[Module Federation Data Prefetch]: Your shared strategy is set to '${SHARED_STRATEGY}', this is a necessary condition for data prefetch`,
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/dts-plugin/src/plugins/ConsumeTypesPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from '@module-federation/sdk';
import { infrastructureLogger as logger } from '@module-federation/sdk';
import {
normalizeOptions,
type moduleFederationPlugin,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

'use strict';
import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
import { logger } from '@module-federation/sdk';
import { infrastructureLogger as logger } from '@module-federation/sdk';
import {
getShortErrorMsg,
buildDescMap,
Expand Down
10 changes: 8 additions & 2 deletions packages/enhanced/src/lib/container/ModuleFederationPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { DtsPlugin } from '@module-federation/dts-plugin';
import { ContainerManager, utils } from '@module-federation/managers';
import { StatsPlugin } from '@module-federation/manifest';
import {
bindLoggerToCompiler,
composeKeyWithSeparator,
type moduleFederationPlugin,
logger,
infrastructureLogger,
} from '@module-federation/sdk';
import { PrefetchPlugin } from '@module-federation/data-prefetch/cli';
import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
Expand Down Expand Up @@ -102,6 +103,11 @@ class ModuleFederationPlugin implements WebpackPluginInstance {
* @returns {void}
*/
apply(compiler: Compiler): void {
bindLoggerToCompiler(
infrastructureLogger,
compiler,
'EnhancedModuleFederationPlugin',
);
const { _options: options } = this;
// must before ModuleFederationPlugin
(new RemoteEntryPlugin(options) as unknown as WebpackPluginInstance).apply(
Expand Down Expand Up @@ -175,7 +181,7 @@ class ModuleFederationPlugin implements WebpackPluginInstance {
if (err instanceof Error) {
err.message = `[ ModuleFederationPlugin ]: Manifest will not generate, because: ${err.message}`;
}
logger.warn(err);
infrastructureLogger.warn(err);
disableManifest = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import fs from 'fs';
import path from 'path';
import { ConcatSource } from 'webpack-sources';
import { transformSync } from '@swc/core';
import { logger } from '@module-federation/sdk';
import { infrastructureLogger as logger } from '@module-federation/sdk';

const { RuntimeModule, Template, RuntimeGlobals } = require(
normalizeWebpackPath('webpack'),
Expand Down
45 changes: 42 additions & 3 deletions packages/enhanced/test/ConfigTestCases.template.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,40 @@ const captureStdio = require('./helpers/captureStdio');
const asModule = require('./helpers/asModule');
const filterInfraStructureErrors = require('./helpers/infrastructureLogErrors');

const stripAllowedInfrastructureLogs = (stderrOutput) => {
if (!stderrOutput) {
return '';
}
const remaining = [];
const lines = stderrOutput.split(/\r?\n/);
let skippingStack = false;
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) {
skippingStack = false;
continue;
}
if (filterInfraStructureErrors.isAllowedLog(trimmed)) {
skippingStack = true;
continue;
}
if (
skippingStack &&
(/^\s*(at\s|\()/i.test(line) || /^<[^>]+>\s*(at\s|\()/i.test(line))
) {
continue;
}
skippingStack = false;
remaining.push(line);
}
const result = remaining.join('\n');
if (process.env.DEBUG_INFRA_LOG === '1' && result) {
// eslint-disable-next-line no-console
console.warn('[infra stderr]', result);
}
return result;
};

const casesPath = path.join(__dirname, 'configCases');
const categories = fs.readdirSync(casesPath).map((cat) => {
return {
Expand Down Expand Up @@ -216,7 +250,9 @@ const describeCases = (config) => {
fs.mkdirSync(outputDirectory, { recursive: true });
infraStructureLog.length = 0;
require('webpack')(options, (err) => {
const infrastructureLogging = stderr.toString();
const infrastructureLogging = stripAllowedInfrastructureLogs(
stderr.toString(),
);
if (infrastructureLogging) {
return done(
new Error(
Expand Down Expand Up @@ -261,7 +297,8 @@ const describeCases = (config) => {
errorsCount: true,
});
if (errorsCount === 0) {
const infrastructureLogging = stderr.toString();
const infrastructureLogging =
stripAllowedInfrastructureLogs(stderr.toString());
if (infrastructureLogging) {
return done(
new Error(
Expand Down Expand Up @@ -363,7 +400,9 @@ const describeCases = (config) => {
) {
return;
}
const infrastructureLogging = stderr.toString();
const infrastructureLogging = stripAllowedInfrastructureLogs(
stderr.toString(),
);
if (infrastructureLogging) {
return done(
new Error(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
let warnings = [];
let oldWarn;

const shouldIgnoreWarning = (warning) =>
typeof warning === 'string' && warning.startsWith('[ Federation Runtime ]');

const captureWarning = (...args) => {
const [message] = args;
if (shouldIgnoreWarning(message)) {
return;
}
warnings.push(message);
};

beforeEach((done) => {
oldWarn = console.warn;
console.warn = (m) => warnings.push(m);
console.warn = captureWarning;
done();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
let warnings = [];
let oldWarn;

const shouldIgnoreWarning = (warning) =>
typeof warning === 'string' && warning.startsWith('[ Federation Runtime ]');

const captureWarning = (...args) => {
const [message] = args;
if (shouldIgnoreWarning(message)) {
return;
}
warnings.push(message);
};

beforeEach((done) => {
oldWarn = console.warn;
console.warn = (m) => warnings.push(m);
console.warn = captureWarning;
done();
});

Expand Down
37 changes: 37 additions & 0 deletions packages/enhanced/test/helpers/infrastructureLogErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,38 @@ const PERSISTENCE_CACHE_INVALIDATE_ERROR = (log, config) => {
return `Pack got invalid because of write to: ${match[1].trim()}`;
}
};
const ALLOWED_PREFIXES = [
'[ Module Federation ]',
'[ Federation Runtime ]',
'[ Module Federation Manifest Plugin ]',
'[ Module Federation Bridge React ]',
'[ Module Federation Bridge Vue3 ]',
'[ Module Federation Bridge ]',
'[Module Federation Manifest Plugin]',
'[Module Federation Bridge React]',
'[Module Federation Bridge Vue3]',
'[Module Federation Bridge]',
];

const normalizeLogEntry = (log) => {
let normalized;
if (typeof log === 'string') normalized = log;
else if (Array.isArray(log)) normalized = log.join(' ');
else if (log && typeof log.message === 'string') normalized = log.message;
else normalized = String(log ?? '');

return normalized.replace(/\u001b\[[0-9;]*m/g, '');
};

const isAllowedLog = (log) => {
const normalized = normalizeLogEntry(log).trim();
if (!normalized) {
return true;
}
const sanitized = normalized.replace(/^<[^>]+>\s*/, '');
return ALLOWED_PREFIXES.some((prefix) => sanitized.startsWith(prefix));
};

const errorsFilter = [PERSISTENCE_CACHE_INVALIDATE_ERROR];

/**
Expand All @@ -20,10 +52,15 @@ const errorsFilter = [PERSISTENCE_CACHE_INVALIDATE_ERROR];
module.exports = function filterInfraStructureErrors(logs, config) {
const results = [];
for (const log of logs) {
if (isAllowedLog(log)) {
continue;
}
for (const filter of errorsFilter) {
const result = filter(log, config);
if (result) results.push({ message: result });
}
}
return results;
};

module.exports.isAllowedLog = (log) => isAllowedLog(log);
6 changes: 5 additions & 1 deletion packages/manifest/src/StatsPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Compiler, WebpackPluginInstance } from 'webpack';
import { moduleFederationPlugin } from '@module-federation/sdk';
import {
bindLoggerToCompiler,
moduleFederationPlugin,
} from '@module-federation/sdk';
import { ManifestManager } from './ManifestManager';
import { StatsManager } from './StatsManager';
import { PLUGIN_IDENTIFIER } from './constants';
Expand Down Expand Up @@ -40,6 +43,7 @@ export class StatsPlugin implements WebpackPluginInstance {
}

apply(compiler: Compiler): void {
bindLoggerToCompiler(logger, compiler, PLUGIN_IDENTIFIER);
if (!this._enable) {
return;
}
Expand Down
12 changes: 10 additions & 2 deletions packages/manifest/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import chalk from 'chalk';
import { createLogger } from '@module-federation/sdk';
import {
createInfrastructureLogger,
createLogger,
} from '@module-federation/sdk';
import { PLUGIN_IDENTIFIER } from './constants';

const logger = createLogger(chalk.cyan(`[ ${PLUGIN_IDENTIFIER} ]`));
const createBundlerLogger: typeof createLogger =
typeof createInfrastructureLogger === 'function'
? (createInfrastructureLogger as unknown as typeof createLogger)
: createLogger;

const logger = createBundlerLogger(chalk.cyan(`[ ${PLUGIN_IDENTIFIER} ]`));

export default logger;
13 changes: 13 additions & 0 deletions packages/nextjs-mf/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {
createInfrastructureLogger,
createLogger,
} from '@module-federation/sdk';

const createBundlerLogger: typeof createLogger =
typeof createInfrastructureLogger === 'function'
? (createInfrastructureLogger as unknown as typeof createLogger)
: createLogger;

const logger = createBundlerLogger('[ nextjs-mf ]');

export default logger;
5 changes: 4 additions & 1 deletion packages/nextjs-mf/src/plugins/CopyFederationPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { promises as fs } from 'fs';
import path from 'path';
import type { Compilation, Compiler, WebpackPluginInstance } from 'webpack';
import { bindLoggerToCompiler } from '@module-federation/sdk';
import logger from '../logger';

/**
* Plugin to copy build output files.
Expand All @@ -23,6 +25,7 @@ class CopyBuildOutputPlugin implements WebpackPluginInstance {
* @method
*/
apply(compiler: Compiler): void {
bindLoggerToCompiler(logger, compiler, 'CopyBuildOutputPlugin');
/**
* Copies files from source to destination.
* @param {string} source - The source directory.
Expand Down Expand Up @@ -78,7 +81,7 @@ class CopyBuildOutputPlugin implements WebpackPluginInstance {
await copyFiles(sourcePath, serverLoc);
} catch (error) {
// If the promise rejects, the file does not exist.
console.error(`File at ${sourcePath} does not exist.`);
logger.error(`File at ${sourcePath} does not exist.`);
}
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ChunkCorrelationPlugin } from '@module-federation/node';
import InvertedContainerPlugin from '../container/InvertedContainerPlugin';
import type { moduleFederationPlugin } from '@module-federation/sdk';
import type { NextFederationPluginExtraOptions } from './next-fragments';
import logger from '../../logger';

/**
* Applies client-specific plugins.
Expand Down Expand Up @@ -37,12 +38,12 @@ export function applyClientPlugins(

// Log a warning if automatic page stitching is enabled, as it is disabled in v7
if (extraOptions.automaticPageStitching) {
console.warn('[nextjs-mf]', 'automatic page stitching is disabled in v7');
logger.warn('automatic page stitching is disabled in v7');
}

// Log an error if a custom library is set, as it is not allowed
if (options.library) {
console.error('[nextjs-mf] you cannot set custom library');
logger.error('you cannot set custom library');
}

// Set the library option to be a window object with the name of the module federation plugin
Expand Down
Loading