From c7bd5341264eaa52f73e26fc0210da47c9dd91f5 Mon Sep 17 00:00:00 2001 From: RomanYar Date: Mon, 23 Aug 2021 15:09:20 +0300 Subject: [PATCH 1/3] refactor(scripts): use parent to fetch config in entrypoint --- packages/scripts/src/create-entrypoint.ts | 74 ++++++++++++++++++++--- 1 file changed, 66 insertions(+), 8 deletions(-) diff --git a/packages/scripts/src/create-entrypoint.ts b/packages/scripts/src/create-entrypoint.ts index 9551a91f0..9169f4992 100644 --- a/packages/scripts/src/create-entrypoint.ts +++ b/packages/scripts/src/create-entrypoint.ts @@ -128,6 +128,7 @@ async function main() { const currentWindow = typeof self !== 'undefined' ? self : window; const topWindow = getTopWindow(currentWindow); const options = new URLSearchParams(topWindow.location.search); + const isMainEntrypoint = topWindow && currentWindow === topWindow; const publicPath = options.has('publicPath') ? options.get('publicPath') : ${typeof publicPath === 'string' ? JSON.stringify(publicPath) : '__webpack_public_path__' }; @@ -136,11 +137,9 @@ async function main() { const featureName = options.get('${FEATURE_QUERY_PARAM}') || ${stringify(featureName)}; const configName = options.get('${CONFIG_QUERY_PARAM}') || ${stringify(configName)}; const config = []; - - ${staticBuild ? importStaticConfigs() : ''} - ${staticBuild && config ? addOverrideConfig(config) : ''} - - ${publicConfigsRoute ? fetchConfigs(publicConfigsRoute, envName) : ''} + + ${populateConfig(envName, staticBuild, publicConfigsRoute, config)} + const rootFeatureLoader = featureLoaders.get(featureName); if(!rootFeatureLoader) { throw new Error("cannot find feature '" + featureName + "'. available features:\\n" + Array.from(featureLoaders.keys()).join('\\n')); @@ -362,10 +361,29 @@ function loadConfigFile(filePath: string, scopedName: string, configEnvName: str //#endregion //#region configs +function populateConfig(envName: string, staticBuild?: boolean, publicConfigsRoute?: string, config?: TopLevelConfig) { + return `${staticBuild ? importStaticConfigs() : ''} +${staticBuild && config ? addOverrideConfig(config) : ''} + +${publicConfigsRoute ? getRemoteConfigs(publicConfigsRoute, envName) : ''} + +${publicConfigsRoute ? `${addConfigsEventListenerForParentEnvironments(publicConfigsRoute)}` : ''}` +} + +function getRemoteConfigs(publicConfigsRoute: string, envName: string) { + return `config.push(...await (async () =>{ + if(!isMainEntrypoint) { + ${getConfigsFromParent(publicConfigsRoute, envName)} + } else { + ${fetchConfigs(publicConfigsRoute, envName)} + } + })());` +} + function fetchConfigs(publicConfigsRoute: string, envName: string) { - return `config.push(...await (await fetch('${normalizeRoute( + return `return (await fetch('${normalizeRoute( publicConfigsRoute - )!}' + configName + '?env=${envName}&feature=' + featureName)).json());`; + )!}' + configName + '?env=${envName}&feature=' + featureName)).json();`; } function addOverrideConfig(config: TopLevelConfig) { @@ -383,13 +401,53 @@ function importStaticConfigs() { }`; } +async (configName: string, envName: string, featureName: string, fetchedConfigs: Record) => { + const config = await (await fetch('configs/' + configName + '?env=' + envName + '&feature=' + featureName)).json() as string; + fetchedConfigs[envName] = config; +} + + +function addConfigsEventListenerForParentEnvironments(publicConfigsRoute: string) { + return `if(isMainEntrypoint) { + const fetchedConfigs = {}; + const configsEventListener = async ({ data: { id, envName }, source }) => { + if(source && id === '${publicConfigsRoute}') { + if(!fetchedConfigs[envName]) { + const config = await (await fetch('configs/' + configName + '?env=' + envName + '&feature=' + featureName)).json(); + fetchedConfigs[envName] = config; + } + source.postMessage({ + id, + config: fetchedConfigs[envName] + }); + } + } + currentWindow.addEventListener('message', configsEventListener); + }`; +} + +function getConfigsFromParent(publicConfigsRoute: string, envName: string) { + return `return new Promise((res) => { + const configsHandler = ({ data: { id, config } }) => { + if(id === '${publicConfigsRoute}') { + currentWindow.removeEventListener('message', configsHandler); + res(config); + } + }; + currentWindow.addEventListener('message', configsHandler) + topWindow.postMessage({ + id: '${publicConfigsRoute}', + envName: '${envName}' + }); + });`; +} + //#endregion //#region loading 3rd party features function loadExternalFeatures(target: 'web' | 'webworker' | 'electron-renderer', externalsFilePath: string) { return `self.runtimeFeatureLoader = featureLoader; const externalFeatures = []; - const isMainEntrypoint = topWindow && currentWindow === topWindow; ${addExternalsEventListenerForParentEnvironments(externalsFilePath)} From a304353edadaa7d3f64ac9687f6eb12f04bcef85 Mon Sep 17 00:00:00 2001 From: RomanYar Date: Mon, 23 Aug 2021 17:06:28 +0300 Subject: [PATCH 2/3] remove nonsence --- packages/scripts/src/create-entrypoint.ts | 75 ++++++++++------------- 1 file changed, 32 insertions(+), 43 deletions(-) diff --git a/packages/scripts/src/create-entrypoint.ts b/packages/scripts/src/create-entrypoint.ts index 06163958e..b2700ac3a 100644 --- a/packages/scripts/src/create-entrypoint.ts +++ b/packages/scripts/src/create-entrypoint.ts @@ -129,9 +129,8 @@ async function main() { const options = new URLSearchParams(topWindow.location.search); const isMainEntrypoint = topWindow && currentWindow === topWindow; - const publicPath = options.has('publicPath') ? options.get('publicPath') : ${ - typeof publicPath === 'string' ? JSON.stringify(publicPath) : '__webpack_public_path__' - }; + const publicPath = options.has('publicPath') ? options.get('publicPath') : ${typeof publicPath === 'string' ? JSON.stringify(publicPath) : '__webpack_public_path__' + }; __webpack_public_path__= publicPath; const featureName = options.get('${FEATURE_QUERY_PARAM}') || ${stringify(featureName)}; @@ -166,9 +165,8 @@ main().catch(console.error); //#region webpack import statements export function webpackImportStatement({ moduleIdentifier, filePath, eagerEntrypoint }: LoadStatementArguments) { - return `await import(/* webpackChunkName: "${moduleIdentifier}" */${ - eagerEntrypoint ? ` /* webpackMode: 'eager' */` : '' - } ${stringify(filePath)});`; + return `await import(/* webpackChunkName: "${moduleIdentifier}" */${eagerEntrypoint ? ` /* webpackMode: 'eager' */` : '' + } ${stringify(filePath)});`; } export function nodeImportStatement({ filePath }: LoadStatementArguments) { @@ -221,12 +219,12 @@ function loadEnvAndContextFiles({ usesResolvedContexts = true; loadStatements.push(`if (resolvedContexts[${JSON.stringify(envName)}] === ${JSON.stringify(childEnvName)}) { ${loadStatement({ - moduleIdentifier: name, - filePath: contextFilePath, - directoryPath, - packageName, - eagerEntrypoint, - })}; + moduleIdentifier: name, + filePath: contextFilePath, + directoryPath, + packageName, + eagerEntrypoint, + })}; }`); } const preloadFilePath = preloadFilePaths?.[`${envName}/${childEnvName}`]; @@ -235,12 +233,12 @@ function loadEnvAndContextFiles({ usesResolvedContexts = true; preloadStatements.push(`if (resolvedContexts[${stringify(envName)}] === ${stringify(childEnvName)}) { ${webpackImportStatement({ - directoryPath, - filePath: preloadFilePath, - moduleIdentifier: name, - packageName, - eagerEntrypoint, - })}; + directoryPath, + filePath: preloadFilePath, + moduleIdentifier: name, + packageName, + eagerEntrypoint, + })}; }`); } } @@ -288,17 +286,16 @@ function createLoaderInterface(args: WebpackFeatureLoaderArguments) { async load(${usesResolvedContexts ? 'resolvedContexts' : ''}) { ${loadStatements.length ? loadStatements.join(';\n') : ''} const featureModule = ${loadStatement({ - moduleIdentifier: `[feature]${name}`, - filePath, - directoryPath, - packageName, - eagerEntrypoint, - })}; - ${ - target !== 'node' - ? `self.${createExternalFeatureMapping(packageName, filePath)} = featureModule;` - : '' - } + moduleIdentifier: `[feature]${name}`, + filePath, + directoryPath, + packageName, + eagerEntrypoint, + })}; + ${target !== 'node' + ? `self.${createExternalFeatureMapping(packageName, filePath)} = featureModule;` + : '' + } return featureModule.default; }, async preload(${usesResolvedContexts ? 'resolvedContexts' : ''}) { @@ -355,11 +352,10 @@ function createConfigLoaders(configs: Record) { } function loadConfigFile(filePath: string, scopedName: string, configEnvName: string | undefined): string { - return `import(/* webpackChunkName: "[config]${scopedName}${ - configEnvName ?? '' - }" */ /* webpackMode: 'eager' */ ${JSON.stringify( - topLevelConfigLoaderPath + `?scopedName=${scopedName}&envName=${configEnvName!}!` + filePath - )})`; + return `import(/* webpackChunkName: "[config]${scopedName}${configEnvName ?? '' + }" */ /* webpackMode: 'eager' */ ${JSON.stringify( + topLevelConfigLoaderPath + `?scopedName=${scopedName}&envName=${configEnvName!}!` + filePath + )})`; } //#endregion @@ -404,12 +400,6 @@ function importStaticConfigs() { }`; } -async (configName: string, envName: string, featureName: string, fetchedConfigs: Record) => { - const config = await (await fetch('configs/' + configName + '?env=' + envName + '&feature=' + featureName)).json() as string; - fetchedConfigs[envName] = config; -} - - function addConfigsEventListenerForParentEnvironments(publicConfigsRoute: string) { return `if(isMainEntrypoint) { const fetchedConfigs = {}; @@ -454,11 +444,10 @@ function loadExternalFeatures(target: 'web' | 'webworker' | 'electron-renderer', ${addExternalsEventListenerForParentEnvironments(externalsFilePath)} - const fetchedExternalFeatures = ${ - target === 'electron-renderer' + const fetchedExternalFeatures = ${target === 'electron-renderer' ? fetchFeaturesFromElectronProcess(externalsFilePath) : fetchExternalFeaturesInBrowser(externalsFilePath) - }; + }; externalFeatures.push(...fetchedExternalFeatures) if(externalFeatures.length) { From 9381fa55214027c712e1954fa0ae027404a4a679 Mon Sep 17 00:00:00 2001 From: RomanYar Date: Mon, 23 Aug 2021 17:21:44 +0300 Subject: [PATCH 3/3] formatting --- packages/scripts/src/create-entrypoint.ts | 73 ++++++++++++----------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/packages/scripts/src/create-entrypoint.ts b/packages/scripts/src/create-entrypoint.ts index b2700ac3a..938225f39 100644 --- a/packages/scripts/src/create-entrypoint.ts +++ b/packages/scripts/src/create-entrypoint.ts @@ -129,8 +129,9 @@ async function main() { const options = new URLSearchParams(topWindow.location.search); const isMainEntrypoint = topWindow && currentWindow === topWindow; - const publicPath = options.has('publicPath') ? options.get('publicPath') : ${typeof publicPath === 'string' ? JSON.stringify(publicPath) : '__webpack_public_path__' - }; + const publicPath = options.has('publicPath') ? options.get('publicPath') : ${ + typeof publicPath === 'string' ? JSON.stringify(publicPath) : '__webpack_public_path__' + }; __webpack_public_path__= publicPath; const featureName = options.get('${FEATURE_QUERY_PARAM}') || ${stringify(featureName)}; @@ -165,8 +166,9 @@ main().catch(console.error); //#region webpack import statements export function webpackImportStatement({ moduleIdentifier, filePath, eagerEntrypoint }: LoadStatementArguments) { - return `await import(/* webpackChunkName: "${moduleIdentifier}" */${eagerEntrypoint ? ` /* webpackMode: 'eager' */` : '' - } ${stringify(filePath)});`; + return `await import(/* webpackChunkName: "${moduleIdentifier}" */${ + eagerEntrypoint ? ` /* webpackMode: 'eager' */` : '' + } ${stringify(filePath)});`; } export function nodeImportStatement({ filePath }: LoadStatementArguments) { @@ -219,12 +221,12 @@ function loadEnvAndContextFiles({ usesResolvedContexts = true; loadStatements.push(`if (resolvedContexts[${JSON.stringify(envName)}] === ${JSON.stringify(childEnvName)}) { ${loadStatement({ - moduleIdentifier: name, - filePath: contextFilePath, - directoryPath, - packageName, - eagerEntrypoint, - })}; + moduleIdentifier: name, + filePath: contextFilePath, + directoryPath, + packageName, + eagerEntrypoint, + })}; }`); } const preloadFilePath = preloadFilePaths?.[`${envName}/${childEnvName}`]; @@ -233,12 +235,12 @@ function loadEnvAndContextFiles({ usesResolvedContexts = true; preloadStatements.push(`if (resolvedContexts[${stringify(envName)}] === ${stringify(childEnvName)}) { ${webpackImportStatement({ - directoryPath, - filePath: preloadFilePath, - moduleIdentifier: name, - packageName, - eagerEntrypoint, - })}; + directoryPath, + filePath: preloadFilePath, + moduleIdentifier: name, + packageName, + eagerEntrypoint, + })}; }`); } } @@ -286,16 +288,17 @@ function createLoaderInterface(args: WebpackFeatureLoaderArguments) { async load(${usesResolvedContexts ? 'resolvedContexts' : ''}) { ${loadStatements.length ? loadStatements.join(';\n') : ''} const featureModule = ${loadStatement({ - moduleIdentifier: `[feature]${name}`, - filePath, - directoryPath, - packageName, - eagerEntrypoint, - })}; - ${target !== 'node' - ? `self.${createExternalFeatureMapping(packageName, filePath)} = featureModule;` - : '' - } + moduleIdentifier: `[feature]${name}`, + filePath, + directoryPath, + packageName, + eagerEntrypoint, + })}; + ${ + target !== 'node' + ? `self.${createExternalFeatureMapping(packageName, filePath)} = featureModule;` + : '' + } return featureModule.default; }, async preload(${usesResolvedContexts ? 'resolvedContexts' : ''}) { @@ -352,10 +355,11 @@ function createConfigLoaders(configs: Record) { } function loadConfigFile(filePath: string, scopedName: string, configEnvName: string | undefined): string { - return `import(/* webpackChunkName: "[config]${scopedName}${configEnvName ?? '' - }" */ /* webpackMode: 'eager' */ ${JSON.stringify( - topLevelConfigLoaderPath + `?scopedName=${scopedName}&envName=${configEnvName!}!` + filePath - )})`; + return `import(/* webpackChunkName: "[config]${scopedName}${ + configEnvName ?? '' + }" */ /* webpackMode: 'eager' */ ${JSON.stringify( + topLevelConfigLoaderPath + `?scopedName=${scopedName}&envName=${configEnvName!}!` + filePath + )})`; } //#endregion @@ -366,7 +370,7 @@ ${staticBuild && config ? addOverrideConfig(config) : ''} ${publicConfigsRoute ? getRemoteConfigs(publicConfigsRoute, envName) : ''} -${publicConfigsRoute ? `${addConfigsEventListenerForParentEnvironments(publicConfigsRoute)}` : ''}` +${publicConfigsRoute ? `${addConfigsEventListenerForParentEnvironments(publicConfigsRoute)}` : ''}`; } function getRemoteConfigs(publicConfigsRoute: string, envName: string) { @@ -376,7 +380,7 @@ function getRemoteConfigs(publicConfigsRoute: string, envName: string) { } else { ${fetchConfigs(publicConfigsRoute, envName)} } - })());` + })());`; } function fetchConfigs(publicConfigsRoute: string, envName: string) { @@ -444,10 +448,11 @@ function loadExternalFeatures(target: 'web' | 'webworker' | 'electron-renderer', ${addExternalsEventListenerForParentEnvironments(externalsFilePath)} - const fetchedExternalFeatures = ${target === 'electron-renderer' + const fetchedExternalFeatures = ${ + target === 'electron-renderer' ? fetchFeaturesFromElectronProcess(externalsFilePath) : fetchExternalFeaturesInBrowser(externalsFilePath) - }; + }; externalFeatures.push(...fetchedExternalFeatures) if(externalFeatures.length) {