@modern-js/uni-builder 2.64.1 → 2.64.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4,8 +4,8 @@ import type { CreateUniBuilderOptions } from './types';
4
4
  import { type UniBuilderWebpackInstance } from './webpack';
5
5
  export { HtmlWebpackPlugin };
6
6
  export type { CreateUniBuilderOptions, UniBuilderInstance, UniBuilderWebpackInstance, };
7
- export type { UniBuilderConfig, UniBuilderPlugin, LooseRsbuildPlugin, BundlerType, MetaOptions, Stats, MultiStats, RspackConfig, } from './types';
7
+ export type { UniBuilderConfig, UniBuilderPlugin, LooseRsbuildPlugin, BundlerType, MetaOptions, Stats, MultiStats, RspackConfig, CacheGroup, } from './types';
8
8
  export declare function createUniBuilder(options: CreateUniBuilderOptions): Promise<UniBuilderInstance>;
9
- export { logger, type ConfigChain, type RsbuildPlugin, type ChainIdentifier, type RspackChain, type Rspack, type RsbuildContext, type RsbuildConfig, type RsbuildTarget, type NormalizedConfig, type CacheGroup, } from '@rsbuild/core';
9
+ export { logger, type ConfigChain, type RsbuildPlugin, type ChainIdentifier, type RspackChain, type Rspack, type RsbuildContext, type RsbuildConfig, type RsbuildTarget, type NormalizedConfig, } from '@rsbuild/core';
10
10
  export type { webpack, WebpackConfig } from '@rsbuild/webpack';
11
11
  export { RUNTIME_CHUNK_NAME, SERVICE_WORKER_ENVIRONMENT_NAME, isHtmlDisabled, castArray, } from './shared/utils';
@@ -35,9 +35,10 @@ module.exports = __toCommonJS(rspack_exports);
35
35
  var import_core = require("@rsbuild/core");
36
36
  var import_compatLegacyPlugin = require("../shared/compatLegacyPlugin");
37
37
  var import_parseCommonConfig = require("../shared/parseCommonConfig");
38
+ var import_rsbuild_rsc_plugin = require("../shared/rsc/plugins/rsbuild-rsc-plugin");
38
39
  var import_utils = require("../shared/utils");
39
40
  async function parseConfig(uniBuilderConfig, options) {
40
- var _uniBuilderConfig_experiments, _uniBuilderConfig_tools, _uniBuilderConfig_tools1;
41
+ var _uniBuilderConfig_experiments, _uniBuilderConfig_tools, _uniBuilderConfig_tools1, _uniBuilderConfig_server;
41
42
  const { rsbuildConfig, rsbuildPlugins } = await (0, import_parseCommonConfig.parseCommonConfig)(uniBuilderConfig, options);
42
43
  if ((_uniBuilderConfig_experiments = uniBuilderConfig.experiments) === null || _uniBuilderConfig_experiments === void 0 ? void 0 : _uniBuilderConfig_experiments.lazyCompilation) {
43
44
  rsbuildConfig.dev.lazyCompilation = uniBuilderConfig.experiments.lazyCompilation;
@@ -119,13 +120,24 @@ async function parseConfig(uniBuilderConfig, options) {
119
120
  }
120
121
  rsbuildPlugins.push(pluginStyledComponents(options2));
121
122
  }
123
+ var _uniBuilderConfig_server_rsc;
124
+ const enableRsc = (_uniBuilderConfig_server_rsc = (_uniBuilderConfig_server = uniBuilderConfig.server) === null || _uniBuilderConfig_server === void 0 ? void 0 : _uniBuilderConfig_server.rsc) !== null && _uniBuilderConfig_server_rsc !== void 0 ? _uniBuilderConfig_server_rsc : false;
125
+ if (enableRsc) {
126
+ const { rscClientRuntimePath, rscServerRuntimePath } = options;
127
+ rsbuildPlugins.push((0, import_rsbuild_rsc_plugin.rsbuildRscPlugin)({
128
+ appDir: options.cwd,
129
+ isRspack: true,
130
+ rscClientRuntimePath,
131
+ rscServerRuntimePath
132
+ }));
133
+ }
122
134
  return {
123
135
  rsbuildConfig,
124
136
  rsbuildPlugins
125
137
  };
126
138
  }
127
139
  async function createRspackBuilder(options) {
128
- const { cwd = process.cwd(), config, ...rest } = options;
140
+ const { cwd = process.cwd(), config, rscClientRuntimePath, rscServerRuntimePath, ...rest } = options;
129
141
  const { rsbuildConfig, rsbuildPlugins } = await parseConfig(config, {
130
142
  ...rest,
131
143
  cwd
@@ -36,13 +36,22 @@ const pluginFrameworkConfig = (configPath) => ({
36
36
  name: "uni-builder:framework-config",
37
37
  setup(api) {
38
38
  api.modifyBundlerChain((chain) => {
39
- if (!import_node_fs.default.existsSync(configPath)) {
39
+ if (!import_node_fs.default.existsSync(configPath) || api.context.bundlerType !== "webpack") {
40
40
  return;
41
41
  }
42
42
  const cache = chain.get("cache");
43
43
  if (!cache) {
44
44
  return;
45
45
  }
46
+ if (cache === true) {
47
+ chain.cache({
48
+ buildDependencies: {
49
+ frameworkConfig: [
50
+ configPath
51
+ ]
52
+ }
53
+ });
54
+ }
46
55
  cache.buildDependencies = {
47
56
  ...cache.buildDependencies,
48
57
  frameworkConfig: [
@@ -0,0 +1,22 @@
1
+ export type { ClientReference, ImportManifestEntry, ModuleLoading, SSRManifest, SSRModuleMap, ClientReferencesMap, ServerReferencesMap, ServerManifest, ServerReferencesModuleInfo, ClientManifest, } from '@modern-js/types/server';
2
+ import { type Module } from '@swc/core';
3
+ import type { LoaderDefinitionFunction, ModuleGraph, NormalModule, Module as WebpackModule } from 'webpack';
4
+ export declare const webpackRscLayerName = "react-server";
5
+ export type SourceMap = Parameters<LoaderDefinitionFunction>[1];
6
+ export declare const MODERN_RSC_INFO = "modernRscInfo";
7
+ export declare const sharedData: {
8
+ store: Map<string, any>;
9
+ get<T>(key: string): T | undefined;
10
+ set<T_1>(key: string, value: T_1): void;
11
+ clear(): void;
12
+ };
13
+ export declare function setBuildInfo(mod: WebpackModule, property: Record<string, any>): void;
14
+ export declare function setRscBuildInfo(mod: WebpackModule, property: Record<string, any>): void;
15
+ export declare function removeRscBuildInfo(mod: WebpackModule): void;
16
+ export declare function getRscBuildInfo(mod: WebpackModule): any;
17
+ export declare function isCssModule(mod: WebpackModule): any;
18
+ export declare const parseSource: (source: string) => Promise<Module>;
19
+ export declare const getExportNames: (ast: Module, collectFuncOnly?: boolean) => Promise<string[]>;
20
+ export declare const isServerModule: (ast: Module) => Promise<boolean>;
21
+ export declare const isClientModule: (ast: Module) => Promise<boolean>;
22
+ export declare function findRootIssuer(modulegraph: ModuleGraph, module: NormalModule): NormalModule;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var common_exports = {};
20
+ __export(common_exports, {
21
+ MODERN_RSC_INFO: () => MODERN_RSC_INFO,
22
+ findRootIssuer: () => findRootIssuer,
23
+ getExportNames: () => getExportNames,
24
+ getRscBuildInfo: () => getRscBuildInfo,
25
+ isClientModule: () => isClientModule,
26
+ isCssModule: () => isCssModule,
27
+ isServerModule: () => isServerModule,
28
+ parseSource: () => parseSource,
29
+ removeRscBuildInfo: () => removeRscBuildInfo,
30
+ setBuildInfo: () => setBuildInfo,
31
+ setRscBuildInfo: () => setRscBuildInfo,
32
+ sharedData: () => sharedData,
33
+ webpackRscLayerName: () => webpackRscLayerName
34
+ });
35
+ module.exports = __toCommonJS(common_exports);
36
+ var import_utils = require("@modern-js/utils");
37
+ var import_core = require("@swc/core");
38
+ const webpackRscLayerName = `react-server`;
39
+ const MODERN_RSC_INFO = "modernRscInfo";
40
+ const sharedData = {
41
+ store: /* @__PURE__ */ new Map(),
42
+ get(key) {
43
+ return this.store.get(key);
44
+ },
45
+ set(key, value) {
46
+ this.store.set(key, value);
47
+ },
48
+ clear() {
49
+ this.store.clear();
50
+ }
51
+ };
52
+ function setBuildInfo(mod, property) {
53
+ mod.buildInfo = mod.buildInfo || {};
54
+ Object.assign(mod.buildInfo, property);
55
+ }
56
+ function setRscBuildInfo(mod, property) {
57
+ mod.buildInfo = mod.buildInfo || {};
58
+ const rscBuildInfo = mod.buildInfo[MODERN_RSC_INFO] || {};
59
+ Object.assign(rscBuildInfo, property);
60
+ setBuildInfo(mod, {
61
+ [MODERN_RSC_INFO]: rscBuildInfo
62
+ });
63
+ }
64
+ function removeRscBuildInfo(mod) {
65
+ var _mod_buildInfo;
66
+ (_mod_buildInfo = mod.buildInfo) === null || _mod_buildInfo === void 0 ? true : delete _mod_buildInfo[MODERN_RSC_INFO];
67
+ }
68
+ function getRscBuildInfo(mod) {
69
+ var _mod_buildInfo;
70
+ return (_mod_buildInfo = mod.buildInfo) === null || _mod_buildInfo === void 0 ? void 0 : _mod_buildInfo[MODERN_RSC_INFO];
71
+ }
72
+ function isCssModule(mod) {
73
+ var _getRscBuildInfo;
74
+ if (!mod)
75
+ return false;
76
+ return (_getRscBuildInfo = getRscBuildInfo(mod)) === null || _getRscBuildInfo === void 0 ? void 0 : _getRscBuildInfo.isCssModule;
77
+ }
78
+ const parseSource = async (source) => {
79
+ return await (0, import_core.parse)(source, {
80
+ syntax: "typescript",
81
+ tsx: true,
82
+ dynamicImport: true
83
+ });
84
+ };
85
+ const getExportNames = async (ast, collectFuncOnly = false) => {
86
+ const exportNames = [];
87
+ ast.body.forEach((node) => {
88
+ if (node.type === "ExportNamedDeclaration") {
89
+ const namedExport = node;
90
+ namedExport.specifiers.forEach((specifier) => {
91
+ if (specifier.type === "ExportSpecifier") {
92
+ var _specifier_exported;
93
+ exportNames.push(((_specifier_exported = specifier.exported) === null || _specifier_exported === void 0 ? void 0 : _specifier_exported.value) || specifier.orig.value);
94
+ }
95
+ });
96
+ }
97
+ if (node.type === "ExportDeclaration") {
98
+ if (node.declaration.type === "VariableDeclaration") {
99
+ node.declaration.declarations.forEach((decl) => {
100
+ if (decl.id.type === "Identifier") {
101
+ if (!collectFuncOnly) {
102
+ exportNames.push(decl.id.value);
103
+ } else {
104
+ var _decl_init, _decl_init1;
105
+ if (((_decl_init = decl.init) === null || _decl_init === void 0 ? void 0 : _decl_init.type) === "FunctionExpression" || ((_decl_init1 = decl.init) === null || _decl_init1 === void 0 ? void 0 : _decl_init1.type) === "ArrowFunctionExpression") {
106
+ exportNames.push(decl.id.value);
107
+ }
108
+ }
109
+ }
110
+ });
111
+ }
112
+ if (node.declaration.type === "ClassDeclaration" || node.declaration.type === "FunctionDeclaration") {
113
+ if (node.declaration.identifier) {
114
+ exportNames.push(node.declaration.identifier.value);
115
+ }
116
+ }
117
+ }
118
+ if (node.type === "ExportDefaultExpression" || node.type === "ExportDefaultDeclaration") {
119
+ exportNames.push("default");
120
+ }
121
+ });
122
+ return exportNames;
123
+ };
124
+ const checkDirective = async (ast, directive) => {
125
+ try {
126
+ for (let i = 0; i < ast.body.length; i++) {
127
+ const node = ast.body[i];
128
+ if (node.type !== "ExpressionStatement") {
129
+ break;
130
+ }
131
+ if (node.expression.type === "StringLiteral" && node.expression.value === directive) {
132
+ return true;
133
+ }
134
+ }
135
+ } catch (e) {
136
+ import_utils.logger.error(e);
137
+ return false;
138
+ }
139
+ return false;
140
+ };
141
+ const isServerModule = async (ast) => {
142
+ return checkDirective(ast, "use server");
143
+ };
144
+ const isClientModule = async (ast) => {
145
+ return checkDirective(ast, "use client");
146
+ };
147
+ function findRootIssuer(modulegraph, module2) {
148
+ const currentModule = module2;
149
+ const issuer = modulegraph.getIssuer(currentModule);
150
+ if (!issuer) {
151
+ return currentModule;
152
+ }
153
+ return findRootIssuer(modulegraph, issuer);
154
+ }
155
+ // Annotate the CommonJS export names for ESM import in node:
156
+ 0 && (module.exports = {
157
+ MODERN_RSC_INFO,
158
+ findRootIssuer,
159
+ getExportNames,
160
+ getRscBuildInfo,
161
+ isClientModule,
162
+ isCssModule,
163
+ isServerModule,
164
+ parseSource,
165
+ removeRscBuildInfo,
166
+ setBuildInfo,
167
+ setRscBuildInfo,
168
+ sharedData,
169
+ webpackRscLayerName
170
+ });
@@ -0,0 +1,2 @@
1
+ export { RscClientPlugin } from './plugins/rsc-client-plugin';
2
+ export { RscServerPlugin } from './plugins/rsc-server-plugin';
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var rsc_exports = {};
20
+ __export(rsc_exports, {
21
+ RscClientPlugin: () => import_rsc_client_plugin.RscClientPlugin,
22
+ RscServerPlugin: () => import_rsc_server_plugin.RscServerPlugin
23
+ });
24
+ module.exports = __toCommonJS(rsc_exports);
25
+ var import_rsc_client_plugin = require("./plugins/rsc-client-plugin");
26
+ var import_rsc_server_plugin = require("./plugins/rsc-server-plugin");
27
+ // Annotate the CommonJS export names for ESM import in node:
28
+ 0 && (module.exports = {
29
+ RscClientPlugin,
30
+ RscServerPlugin
31
+ });
@@ -0,0 +1,7 @@
1
+ import type { RsbuildPlugin } from '@rsbuild/core';
2
+ export declare const rsbuildRscPlugin: ({ appDir, isRspack, rscClientRuntimePath, rscServerRuntimePath, }: {
3
+ appDir: string;
4
+ isRspack?: boolean | undefined;
5
+ rscClientRuntimePath?: string | undefined;
6
+ rscServerRuntimePath?: string | undefined;
7
+ }) => RsbuildPlugin;
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var rsbuild_rsc_plugin_exports = {};
30
+ __export(rsbuild_rsc_plugin_exports, {
31
+ rsbuildRscPlugin: () => rsbuildRscPlugin
32
+ });
33
+ module.exports = __toCommonJS(rsbuild_rsc_plugin_exports);
34
+ var import_common = require("../common");
35
+ var import_rsc_client_plugin = require("./rsc-client-plugin");
36
+ var import_rsc_server_plugin = require("./rsc-server-plugin");
37
+ var import_rspack_rsc_client_plugin = require("./rspack-rsc-client-plugin");
38
+ var import_rspack_rsc_server_plugin = require("./rspack-rsc-server-plugin");
39
+ const CSS_RULE_NAMES = [
40
+ "less",
41
+ "css",
42
+ "scss",
43
+ "sass"
44
+ ];
45
+ const rsbuildRscPlugin = ({ appDir, isRspack = true, rscClientRuntimePath, rscServerRuntimePath }) => ({
46
+ name: "uni-builder:rsc-rsbuild-plugin",
47
+ setup(api) {
48
+ api.modifyBundlerChain({
49
+ handler: async (chain, { isServer, CHAIN_ID }) => {
50
+ const entryPath2Name = /* @__PURE__ */ new Map();
51
+ for (const [name, entry] of Object.entries(chain.entryPoints.entries())) {
52
+ entry.values().forEach((value) => {
53
+ entryPath2Name.set(value, name);
54
+ });
55
+ }
56
+ const jsHandler = () => {
57
+ const originalJsRule = chain.module.rules.get(CHAIN_ID.RULE.JS);
58
+ const useBabel = originalJsRule.uses.has(CHAIN_ID.USE.BABEL);
59
+ const JSRule = useBabel ? CHAIN_ID.USE.BABEL : CHAIN_ID.USE.SWC;
60
+ if (originalJsRule) {
61
+ const jsLoaderOptions = originalJsRule.use(JSRule).get("options");
62
+ const jsLoaderPath = originalJsRule.use(JSRule).get("loader");
63
+ originalJsRule.uses.delete(JSRule);
64
+ chain.module.rule(CHAIN_ID.RULE.JS).oneOf("rsc-server").issuerLayer(import_common.webpackRscLayerName).use("rsc-server-loader").loader(require.resolve("../rsc-server-loader")).options({
65
+ entryPath2Name,
66
+ appDir,
67
+ runtimePath: rscServerRuntimePath
68
+ }).end().use(JSRule).loader(jsLoaderPath).options(jsLoaderOptions).end().end().oneOf("rsc-ssr").use("rsc-ssr-loader").loader(require.resolve("../rsc-ssr-loader")).options({
69
+ entryPath2Name
70
+ }).end().use(JSRule).loader(jsLoaderPath).options(jsLoaderOptions).end().end();
71
+ }
72
+ };
73
+ const layerHandler = () => {
74
+ chain.experiments({
75
+ ...chain.experiments,
76
+ layers: true
77
+ });
78
+ chain.module.rule("server-module").resource([
79
+ /render[/\\].*[/\\]server[/\\]rsc/,
80
+ /AppProxy/
81
+ ]).layer(import_common.webpackRscLayerName).end();
82
+ chain.module.rule(import_common.webpackRscLayerName).issuerLayer(import_common.webpackRscLayerName).resolve.conditionNames.add(import_common.webpackRscLayerName).add("...");
83
+ };
84
+ const flightCssHandler = () => {
85
+ CSS_RULE_NAMES.forEach((ruleName) => {
86
+ const rule = chain.module.rules.get(ruleName);
87
+ if (rule) {
88
+ chain.module.rule(ruleName).use("custom-loader").before("ignore-css").loader(require.resolve("../rsc-css-loader"));
89
+ }
90
+ });
91
+ };
92
+ const addServerRscPlugin = () => {
93
+ const ServerPlugin = isRspack ? import_rspack_rsc_server_plugin.RscServerPlugin : import_rsc_server_plugin.RscServerPlugin;
94
+ chain.plugin("rsc-server-plugin").use(ServerPlugin, [
95
+ {
96
+ entryPath2Name
97
+ }
98
+ ]);
99
+ };
100
+ const addRscClientLoader = () => {
101
+ chain.module.rule("js").use("rsc-client-loader").loader(require.resolve("../rsc-client-loader")).before("babel").options({
102
+ callServerImport: rscClientRuntimePath,
103
+ registerImport: rscClientRuntimePath
104
+ }).end();
105
+ };
106
+ const addRscClientPlugin = () => {
107
+ const ClientPlugin = isRspack ? import_rspack_rsc_client_plugin.RspackRscClientPlugin : import_rsc_client_plugin.RscClientPlugin;
108
+ chain.plugin("rsc-client-plugin").use(ClientPlugin);
109
+ };
110
+ const configureRuntimeChunk = () => {
111
+ chain.optimization.runtimeChunk({
112
+ name: (entrypoint) => `runtime-${entrypoint.name}`
113
+ });
114
+ };
115
+ if (isServer) {
116
+ chain.name("server");
117
+ layerHandler();
118
+ flightCssHandler();
119
+ jsHandler();
120
+ addServerRscPlugin();
121
+ } else {
122
+ chain.name("client");
123
+ chain.dependencies([
124
+ "server"
125
+ ]);
126
+ addRscClientLoader();
127
+ addRscClientPlugin();
128
+ configureRuntimeChunk();
129
+ }
130
+ },
131
+ order: "post"
132
+ });
133
+ }
134
+ });
135
+ // Annotate the CommonJS export names for ESM import in node:
136
+ 0 && (module.exports = {
137
+ rsbuildRscPlugin
138
+ });
@@ -0,0 +1,13 @@
1
+ import type Webpack from 'webpack';
2
+ export interface RscClientPluginOptions {
3
+ readonly clientManifestFilename?: string;
4
+ readonly ssrManifestFilename?: string;
5
+ }
6
+ export declare class RscClientPlugin {
7
+ private clientReferencesMap;
8
+ private clientManifestFilename;
9
+ private ssrManifestFilename;
10
+ private styles?;
11
+ constructor(options?: RscClientPluginOptions);
12
+ apply(compiler: Webpack.Compiler): void;
13
+ }
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var rsc_client_plugin_exports = {};
20
+ __export(rsc_client_plugin_exports, {
21
+ RscClientPlugin: () => RscClientPlugin
22
+ });
23
+ module.exports = __toCommonJS(rsc_client_plugin_exports);
24
+ var import_common = require("../common");
25
+ class RscClientPlugin {
26
+ apply(compiler) {
27
+ const { AsyncDependenciesBlock, RuntimeGlobals, WebpackError, dependencies: { ModuleDependency, NullDependency }, sources: { RawSource } } = compiler.webpack;
28
+ const ssrManifest = {
29
+ moduleMap: {},
30
+ moduleLoading: null,
31
+ styles: []
32
+ };
33
+ class ClientReferenceDependency extends ModuleDependency {
34
+ get type() {
35
+ return `client-reference`;
36
+ }
37
+ }
38
+ const getEntryModule = (compilation) => {
39
+ const entryModules = [];
40
+ for (const [, entryValue] of compilation.entries.entries()) {
41
+ const entryDependency = entryValue.dependencies.find((dependency) => dependency.constructor.name === `EntryDependency`);
42
+ if (!entryDependency) {
43
+ compilation.errors.push(new WebpackError(`Could not find an entry dependency.`));
44
+ continue;
45
+ }
46
+ const resolvedModule = compilation.moduleGraph.getResolvedModule(entryDependency);
47
+ if (resolvedModule) {
48
+ entryModules.push(resolvedModule);
49
+ }
50
+ }
51
+ if (entryModules.length === 0) {
52
+ compilation.errors.push(new WebpackError(`Could not find any entries in the compilation.`));
53
+ return [];
54
+ }
55
+ return entryModules;
56
+ };
57
+ const addClientReferencesChunks = (entryModule) => {
58
+ [
59
+ ...this.clientReferencesMap.keys()
60
+ ].forEach((resourcePath, index) => {
61
+ const chunkName = `client${index}`;
62
+ const block = new AsyncDependenciesBlock({
63
+ name: chunkName
64
+ }, void 0, resourcePath);
65
+ block.addDependency(new ClientReferenceDependency(resourcePath));
66
+ entryModule.addBlock(block);
67
+ });
68
+ if (this.styles && this.styles.size > 0) {
69
+ for (const style of this.styles) {
70
+ const dep = new ClientReferenceDependency(style);
71
+ entryModule.addDependency(dep);
72
+ }
73
+ }
74
+ };
75
+ compiler.hooks.finishMake.tap(RscClientPlugin.name, (compilation) => {
76
+ if (compiler.watchMode) {
77
+ const entryModules = getEntryModule(compilation);
78
+ for (const entryModule of entryModules) {
79
+ entryModule.blocks = entryModule.blocks.filter((block) => block.dependencies.some((dependency) => !(dependency instanceof ClientReferenceDependency) || this.clientReferencesMap.has(dependency.request)));
80
+ addClientReferencesChunks(entryModule);
81
+ }
82
+ }
83
+ });
84
+ compiler.hooks.compilation.tap(RscClientPlugin.name, (compilation, { normalModuleFactory }) => {
85
+ compilation.dependencyFactories.set(ClientReferenceDependency, normalModuleFactory);
86
+ compilation.dependencyTemplates.set(ClientReferenceDependency, new NullDependency.Template());
87
+ class EntryNameRuntimeModule extends compiler.webpack.RuntimeModule {
88
+ generate() {
89
+ return `window.__MODERN_JS_ENTRY_NAME="${this.entryName}";`;
90
+ }
91
+ constructor(entryName) {
92
+ super("entry-name", 10);
93
+ this.entryName = entryName;
94
+ }
95
+ }
96
+ compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.ensureChunk).tap(RscClientPlugin.name, (chunk, set) => {
97
+ Array.from(compilation.entrypoints.entries()).forEach(([entryName, entrypoint]) => {
98
+ if (entrypoint.chunks.includes(chunk)) {
99
+ compilation.addRuntimeModule(chunk, new EntryNameRuntimeModule(entryName));
100
+ }
101
+ });
102
+ });
103
+ });
104
+ compiler.hooks.thisCompilation.tap(RscClientPlugin.name, (compilation, { normalModuleFactory }) => {
105
+ this.styles = import_common.sharedData.get("styles");
106
+ this.clientReferencesMap = import_common.sharedData.get("clientReferencesMap");
107
+ const onNormalModuleFactoryParser = (parser) => {
108
+ parser.hooks.program.tap(RscClientPlugin.name, () => {
109
+ const entryModules = getEntryModule(compilation);
110
+ for (const entryModule of entryModules) {
111
+ if (entryModule === parser.state.module) {
112
+ addClientReferencesChunks(entryModule);
113
+ }
114
+ }
115
+ });
116
+ };
117
+ normalModuleFactory.hooks.parser.for(`javascript/auto`).tap(`HarmonyModulesPlugin`, onNormalModuleFactoryParser);
118
+ normalModuleFactory.hooks.parser.for(`javascript/dynamic`).tap(`HarmonyModulesPlugin`, onNormalModuleFactoryParser);
119
+ normalModuleFactory.hooks.parser.for(`javascript/esm`).tap(`HarmonyModulesPlugin`, onNormalModuleFactoryParser);
120
+ compilation.hooks.additionalTreeRuntimeRequirements.tap(RscClientPlugin.name, (_chunk, runtimeRequirements) => {
121
+ runtimeRequirements.add(RuntimeGlobals.ensureChunk);
122
+ runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
123
+ });
124
+ compilation.hooks.processAssets.tap(RscClientPlugin.name, () => {
125
+ const clientManifest = {};
126
+ const { chunkGraph, moduleGraph, modules } = compilation;
127
+ for (const module2 of modules) {
128
+ const resourcePath = module2.nameForCondition();
129
+ const clientReferences = resourcePath ? this.clientReferencesMap.get(resourcePath) : void 0;
130
+ if (clientReferences) {
131
+ const moduleId = chunkGraph.getModuleId(module2);
132
+ const ssrModuleMetaData = {};
133
+ for (const { id, exportName, ssrId } of clientReferences) {
134
+ const clientExportName = exportName;
135
+ const ssrExportName = exportName;
136
+ const chunksSet = /* @__PURE__ */ new Set();
137
+ for (const chunk of chunkGraph.getModuleChunksIterable(module2)) {
138
+ chunksSet.add(chunk);
139
+ }
140
+ for (const connection of moduleGraph.getOutgoingConnections(module2)) {
141
+ for (const chunk of chunkGraph.getModuleChunksIterable(connection.module)) {
142
+ chunksSet.add(chunk);
143
+ }
144
+ }
145
+ const chunks = [];
146
+ const styles = [];
147
+ for (const chunk of chunksSet) {
148
+ if (chunk.id && !chunk.isOnlyInitial()) {
149
+ for (const file of chunk.files) {
150
+ if (file.endsWith(".js")) {
151
+ chunks.push(chunk.id, file);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ clientManifest[id] = {
157
+ id: moduleId,
158
+ name: clientExportName,
159
+ chunks,
160
+ styles
161
+ };
162
+ if (ssrId) {
163
+ ssrModuleMetaData[clientExportName] = {
164
+ id: ssrId,
165
+ name: ssrExportName,
166
+ chunks: []
167
+ };
168
+ }
169
+ }
170
+ ssrManifest.moduleMap[moduleId] = ssrModuleMetaData;
171
+ }
172
+ }
173
+ compilation.emitAsset(this.clientManifestFilename, new RawSource(JSON.stringify(clientManifest, null, 2), false));
174
+ const { crossOriginLoading, publicPath = `` } = compilation.outputOptions;
175
+ var _compilation_hash;
176
+ ssrManifest.moduleLoading = {
177
+ // https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/PublicPathRuntimeModule.js#L30-L32
178
+ prefix: compilation.getPath(publicPath, {
179
+ hash: (_compilation_hash = compilation.hash) !== null && _compilation_hash !== void 0 ? _compilation_hash : `XXXX`
180
+ }),
181
+ crossOrigin: crossOriginLoading ? crossOriginLoading === `use-credentials` ? crossOriginLoading : `` : void 0
182
+ };
183
+ if (this.styles && this.styles.size > 0) {
184
+ const assets = compilation.getAssets();
185
+ const cssAsset = assets.find((asset) => {
186
+ return asset.name.endsWith(".css");
187
+ });
188
+ if (cssAsset) {
189
+ ssrManifest.styles.push(cssAsset.name);
190
+ }
191
+ }
192
+ compilation.emitAsset(this.ssrManifestFilename, new RawSource(JSON.stringify(ssrManifest, null, 2), false));
193
+ });
194
+ });
195
+ }
196
+ constructor(options) {
197
+ this.clientReferencesMap = /* @__PURE__ */ new Map();
198
+ this.clientManifestFilename = (options === null || options === void 0 ? void 0 : options.clientManifestFilename) || `react-client-manifest.json`;
199
+ this.ssrManifestFilename = (options === null || options === void 0 ? void 0 : options.ssrManifestFilename) || `react-ssr-manifest.json`;
200
+ }
201
+ }
202
+ // Annotate the CommonJS export names for ESM import in node:
203
+ 0 && (module.exports = {
204
+ RscClientPlugin
205
+ });