react-cosmos-plugin-rspack 1.0.3 → 2.0.1

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.
@@ -1,701 +0,0 @@
1
- // src/server/rspackConfigPlugin.ts
2
- import * as path from "path";
3
-
4
- // src/server/rspackConfig/constants.ts
5
- var RENDERER_FILENAME = "renderer.html";
6
-
7
- // src/server/rspackConfigPlugin.ts
8
- async function rspackConfigPlugin({
9
- cosmosConfig
10
- }) {
11
- if (cosmosConfig.rendererUrl) {
12
- return cosmosConfig;
13
- }
14
- return {
15
- ...cosmosConfig,
16
- rendererUrl: path.join(cosmosConfig.publicUrl, RENDERER_FILENAME)
17
- };
18
- }
19
-
20
- // src/server/rspackDevServerPlugin.ts
21
- import * as path8 from "path";
22
- import { serveStaticDir } from "react-cosmos";
23
- import webpackHotMiddleware from "webpack-hot-middleware";
24
-
25
- // src/server/cosmosConfig/createRspackCosmosConfig.ts
26
- import * as path3 from "path";
27
- import { fileExists } from "react-cosmos";
28
-
29
- // src/server/utils/resolveLoose.ts
30
- import * as path2 from "path";
31
-
32
- // src/server/utils/isNodeError.ts
33
- function isNodeError(err) {
34
- return err && err.stack && err.message;
35
- }
36
-
37
- // src/server/utils/resolve.ts
38
- import { createRequire } from "module";
39
- function resolve(moduleId) {
40
- const require2 = createRequire(import.meta.url);
41
- return require2.resolve(moduleId);
42
- }
43
- function resolveFrom(fromDirectory, moduleId) {
44
- const require2 = createRequire(import.meta.url);
45
- return require2.resolve(moduleId, { paths: [fromDirectory] });
46
- }
47
-
48
- // src/server/utils/resolveSilent.ts
49
- function resolveFromSilent(fromDirectory, moduleId) {
50
- try {
51
- return resolveFrom(fromDirectory, moduleId);
52
- } catch (err) {
53
- if (!isNodeError(err) || err.code !== "MODULE_NOT_FOUND") console.log(err);
54
- return null;
55
- }
56
- }
57
-
58
- // src/server/utils/resolveLoose.ts
59
- function resolveLoose(fromDirectory, moduleId) {
60
- return path2.isAbsolute(moduleId) ? moduleId : resolveFromSilent(fromDirectory, moduleId) || // Final attempt: Resolve relative paths that don't either
61
- // 1. Don't start with ./
62
- // 2. Don't point to an existing file
63
- path2.join(fromDirectory, moduleId);
64
- }
65
-
66
- // src/server/cosmosConfig/createRspackCosmosConfig.ts
67
- function createRspackCosmosConfig(cosmosConfig) {
68
- const { rootDir } = cosmosConfig;
69
- const configInput = cosmosConfig.rspack || {};
70
- return {
71
- configPath: getRspackConfigPath(configInput, rootDir),
72
- overridePath: getRspackOverridePath(configInput, rootDir),
73
- includeHashInOutputFilename: getIncludeHashInOutputFilename(configInput),
74
- hotReload: getHotReload(configInput),
75
- reloadOnFail: getReloadOnFail(configInput)
76
- };
77
- }
78
- function getRspackConfigPath({ configPath }, rootDir) {
79
- if (typeof configPath === "undefined") {
80
- return resolveLoose(rootDir, "rspack.config.js");
81
- }
82
- if (!configPath) {
83
- return null;
84
- }
85
- const absPath = resolveLoose(rootDir, configPath);
86
- if (!fileExists(absPath)) {
87
- const relPath = path3.relative(process.cwd(), absPath);
88
- throw new Error(`rspack config not found at path: ${relPath}`);
89
- }
90
- return absPath;
91
- }
92
- function getRspackOverridePath({ overridePath }, rootDir) {
93
- if (typeof overridePath === "undefined") {
94
- return resolveLoose(rootDir, "rspack.override.js");
95
- }
96
- if (!overridePath) {
97
- return null;
98
- }
99
- const absPath = resolveLoose(rootDir, overridePath);
100
- if (!fileExists(absPath)) {
101
- const relPath = path3.relative(process.cwd(), absPath);
102
- throw new Error(`rspack override module not found at path: ${relPath}`);
103
- }
104
- return absPath;
105
- }
106
- function getIncludeHashInOutputFilename({
107
- includeHashInOutputFilename = false
108
- }) {
109
- return includeHashInOutputFilename;
110
- }
111
- function getHotReload({ hotReload = true }) {
112
- return hotReload;
113
- }
114
- function getReloadOnFail({ reloadOnFail = false }) {
115
- return reloadOnFail;
116
- }
117
-
118
- // src/server/utils/requireModule.ts
119
- import { createRequire as createRequire2 } from "module";
120
- import * as path4 from "path";
121
- function requireFrom(fromDirectory, moduleId) {
122
- const require2 = createRequire2(path4.resolve(fromDirectory, "noop.js"));
123
- return require2(moduleId);
124
- }
125
-
126
- // src/server/utils/requireSilent.ts
127
- function requireFromSilent(fromDirectory, moduleId) {
128
- try {
129
- return requireFrom(fromDirectory, moduleId);
130
- } catch (err) {
131
- if (!isNodeError(err) || err.code !== "MODULE_NOT_FOUND") {
132
- console.log(err);
133
- }
134
- }
135
- }
136
-
137
- // src/server/getRspack.ts
138
- function getRspack(rootDir) {
139
- const userRspack = requireFromSilent(
140
- rootDir,
141
- "@rspack/core"
142
- );
143
- if (!userRspack) {
144
- console.warn("[Cosmos] rspack dependency missing!");
145
- console.log(
146
- 'Install using "yarn add --dev @rspack/core" or "npm install --save-dev @rspack/core"'
147
- );
148
- return;
149
- }
150
- return userRspack.rspack;
151
- }
152
-
153
- // src/server/rspackConfig/getDevRspackConfig.ts
154
- import * as path7 from "path";
155
-
156
- // src/server/rspackConfig/getUserRspackConfig.ts
157
- import * as path5 from "path";
158
- import {
159
- getCliArgs,
160
- importModule,
161
- moduleExists
162
- } from "react-cosmos";
163
-
164
- // src/server/rspackConfig/getDefaultRspackConfig.ts
165
- import rspack from "@rspack/core";
166
-
167
- // src/server/rspackConfig/getRspackNodeEnv.ts
168
- function getRspackNodeEnv() {
169
- return process.env.NODE_ENV === "production" ? "production" : "development";
170
- }
171
-
172
- // src/server/rspackConfig/getDefaultRspackConfig.ts
173
- function getDefaultRspackConfig(rootDir) {
174
- const postcssLoaderPath = resolveFromSilent(rootDir, "postcss-loader");
175
- const mdxLoaderPath = resolveFromSilent(rootDir, "@mdx-js/loader");
176
- const rules = [];
177
- const plugins = [];
178
- rules.push({
179
- test: /\.(j|t)s$/,
180
- exclude: [/[\\/]node_modules[\\/]/],
181
- loader: "builtin:swc-loader",
182
- options: {
183
- sourceMaps: true,
184
- jsc: { parser: { syntax: "typescript" } }
185
- },
186
- type: "javascript/auto"
187
- });
188
- rules.push({
189
- test: /\.(j|t)sx$/,
190
- loader: "builtin:swc-loader",
191
- exclude: [/[\\/]node_modules[\\/]/],
192
- options: {
193
- sourceMaps: true,
194
- jsc: {
195
- parser: {
196
- syntax: "typescript",
197
- tsx: true
198
- },
199
- transform: { react: { runtime: "automatic" } }
200
- }
201
- },
202
- type: "javascript/auto"
203
- });
204
- rules.push({
205
- test: /\.css$/,
206
- use: postcssLoaderPath ? [{ loader: postcssLoaderPath }] : [{ loader: "builtin:lightningcss-loader" }],
207
- type: "css/auto"
208
- });
209
- if (mdxLoaderPath) {
210
- rules.push({
211
- test: /\.mdx$/,
212
- loader: mdxLoaderPath,
213
- exclude: [/[\\/]node_modules[\\/]/]
214
- });
215
- }
216
- plugins.push(
217
- new rspack.HtmlRspackPlugin({
218
- title: "React Cosmos",
219
- filename: RENDERER_FILENAME
220
- })
221
- );
222
- const config = {
223
- // Besides other advantages, cheap-module-source-map is compatible with
224
- // React.componentDidCatch https://github.com/facebook/react/issues/10441
225
- devtool: "cheap-module-source-map",
226
- resolve: {
227
- extensionAlias: {
228
- ".js": [".ts", ".tsx", ".js"]
229
- },
230
- extensions: [".js", ".jsx", ".ts", ".tsx"]
231
- },
232
- module: {
233
- rules
234
- },
235
- plugins,
236
- stats: {
237
- preset: "errors-only",
238
- builtAt: true
239
- },
240
- infrastructureLogging: { level: "warn" },
241
- experiments: {
242
- topLevelAwait: true
243
- }
244
- };
245
- return {
246
- ...config,
247
- mode: getRspackNodeEnv(),
248
- optimization: {
249
- // Cosmos reads component names at run-time, so it is crucial to not
250
- // minify even when building with production env (ie. when exporting)
251
- // https://github.com/react-cosmos/react-cosmos/issues/701
252
- minimize: false
253
- }
254
- };
255
- }
256
-
257
- // src/server/rspackConfig/getUserRspackConfig.ts
258
- async function getUserRspackConfig(cosmosConfig) {
259
- const baseRspackConfig = await getBaseRspackConfig(cosmosConfig);
260
- const { overridePath } = createRspackCosmosConfig(cosmosConfig);
261
- if (!overridePath || !moduleExists(overridePath)) {
262
- console.log(
263
- `[Cosmos] Learn how to override rspack config for cosmos: https://github.com/react-cosmos/react-cosmos/tree/main/docs#webpack-config-override`
264
- );
265
- return baseRspackConfig;
266
- }
267
- const relPath = path5.relative(process.cwd(), overridePath);
268
- console.log(`[Cosmos] Overriding rspack config at ${relPath}`);
269
- const module = await importModule(overridePath);
270
- const rspackOverride = module.default;
271
- return rspackOverride(baseRspackConfig, getRspackNodeEnv());
272
- }
273
- async function getBaseRspackConfig(cosmosConfig) {
274
- const { rootDir } = cosmosConfig;
275
- const { configPath } = createRspackCosmosConfig(cosmosConfig);
276
- if (!configPath || !moduleExists(configPath)) {
277
- console.log("[Cosmos] Using default rspack config");
278
- return getDefaultRspackConfig(rootDir);
279
- }
280
- const relPath = path5.relative(process.cwd(), configPath);
281
- console.log(`[Cosmos] Using rspack config found at ${relPath}`);
282
- const module = await importModule(configPath);
283
- const rspackConfig = module.default;
284
- const cliArgs = getCliArgs();
285
- return typeof rspackConfig === "function" ? (
286
- // When cliargs.env is falsey, react-cosmos-plugin-webpack passes the result
287
- // of getRspackNodeEnv() which is the string "production" or "development"
288
- // but that doesn't seem to be what webpack does:
289
- //
290
- // https://github.com/webpack/webpack-cli/blob/79a969fb02c870667d8a3b7035405566d2b4d088/packages/webpack-cli/src/webpack-cli.ts#L1903C35-L1903C43
291
- await rspackConfig(cliArgs.env || {}, cliArgs)
292
- ) : rspackConfig;
293
- }
294
-
295
- // src/server/rspackConfig/resolveRspackClientPath.ts
296
- import { createRequire as createRequire3 } from "module";
297
- function resolveRspackClientPath(relPath) {
298
- const require2 = createRequire3(import.meta.url);
299
- return require2.resolve(`../client/${relPath}`);
300
- }
301
-
302
- // src/server/rspackConfig/resolveRspackLoaderPath.ts
303
- import { createRequire as createRequire4 } from "module";
304
- function resolveRspackLoaderPath() {
305
- const require2 = createRequire4(import.meta.url);
306
- return require2.resolve("./userImportsLoader.cjs");
307
- }
308
-
309
- // src/server/rspackConfig/getRspackConfigModule.ts
310
- function getRspackConfigModule(cosmosConfig, rspackConfig) {
311
- return {
312
- ...rspackConfig.module,
313
- rules: getRules(cosmosConfig, rspackConfig)
314
- };
315
- }
316
- function getRules(cosmosConfig, { module }) {
317
- const existingRules = module && module.rules || [];
318
- return [...existingRules, getUserImportsLoaderRule(cosmosConfig)];
319
- }
320
- function getUserImportsLoaderRule(cosmosConfig) {
321
- return {
322
- include: resolveRspackClientPath("userImports"),
323
- use: {
324
- loader: resolveRspackLoaderPath(),
325
- options: { cosmosConfig }
326
- }
327
- };
328
- }
329
-
330
- // src/server/rspackConfig/getRspackConfigResolve.ts
331
- import * as path6 from "path";
332
- function getRspackConfigResolve(cosmosConfig, rspackConfig) {
333
- return resolveLocalReactDeps(cosmosConfig, rspackConfig.resolve);
334
- }
335
- function resolveLocalReactDeps(cosmosConfig, resolve6 = {}) {
336
- const { rootDir } = cosmosConfig;
337
- let alias = resolve6.alias || {};
338
- let reactAlias = hasAlias(alias, "react");
339
- let reactDomAlias = hasAlias(alias, "react-dom");
340
- if (reactAlias && reactDomAlias) {
341
- console.log("[Cosmos] React and React DOM aliases found in rspack config");
342
- return resolve6;
343
- }
344
- if (reactAlias) {
345
- console.log("[Cosmos] React alias found in rspack config");
346
- } else {
347
- const reactPath = resolveFromSilent(rootDir, "react");
348
- if (!reactPath)
349
- throw new Error(`[Cosmos] Local dependency not found: react`);
350
- alias = addAlias(alias, "react", path6.dirname(reactPath));
351
- }
352
- if (reactDomAlias) {
353
- console.log("[Cosmos] React DOM alias found in rspack config");
354
- } else {
355
- const reactDomPath = resolveFromSilent(rootDir, "react-dom");
356
- if (!reactDomPath)
357
- throw new Error(`[Cosmos] Local dependency not found: react-dom`);
358
- alias = addAlias(alias, "react-dom", path6.dirname(reactDomPath));
359
- }
360
- return { ...resolve6, alias };
361
- }
362
- function hasAlias(alias, name) {
363
- if (!alias) return false;
364
- const exactName = `${name}$`;
365
- const keys = Object.keys(alias);
366
- return keys.includes(name) || keys.includes(exactName);
367
- }
368
- function addAlias(alias, name, value) {
369
- return { ...alias, [name]: value };
370
- }
371
-
372
- // src/server/rspackConfig/htmlPlugin.ts
373
- import rspack2 from "@rspack/core";
374
-
375
- // src/server/utils/omit.ts
376
- function omit(o, fields) {
377
- const result = { ...o };
378
- for (const field of fields) {
379
- delete result[field];
380
- }
381
- return result;
382
- }
383
-
384
- // src/server/rspackConfig/plugins.ts
385
- function getGlobalsPlugin({ publicUrl }, userRspack, devServerOn) {
386
- const cleanPublicUrl = removeTrailingSlash(publicUrl);
387
- return new userRspack.DefinePlugin({
388
- // "if (__DEV__)" blocks get stripped when compiling a static export build
389
- __DEV__: JSON.stringify(devServerOn),
390
- "process.env.NODE_ENV": JSON.stringify(getRspackNodeEnv()),
391
- "process.env.PUBLIC_URL": JSON.stringify(cleanPublicUrl)
392
- });
393
- }
394
- function hasPlugin(plugins, pluginName) {
395
- return plugins && plugins.filter((p) => isInstanceOfRspackPlugin(p, pluginName)).length > 0;
396
- }
397
- function isInstanceOfRspackPlugin(plugin, constructorName) {
398
- return plugin.constructor && plugin.constructor.name === constructorName;
399
- }
400
- function ignoreEmptyRspackPlugins(plugins = []) {
401
- return plugins.filter(Boolean);
402
- }
403
- function removeTrailingSlash(url) {
404
- return url.replace(/\/$/, "");
405
- }
406
-
407
- // src/server/rspackConfig/htmlPlugin.ts
408
- function ensureHtmlPlugin(plugins) {
409
- if (hasPlugin(plugins, "HtmlWebpackPlugin")) {
410
- return plugins.map(
411
- (plugin) => isHtmlWebpackPlugin(plugin) ? changeHtmlPluginFilename(plugin) : plugin
412
- );
413
- }
414
- const htmlRspackPlugin = plugins.find(isHtmlRspackPlugin);
415
- if (htmlRspackPlugin) {
416
- const options = htmlRspackPlugin._args[0];
417
- const safeOptions = omit(options, ["chunks"]);
418
- return [
419
- ...plugins.filter((plugin) => plugin !== htmlRspackPlugin),
420
- new rspack2.HtmlRspackPlugin({
421
- ...safeOptions,
422
- filename: RENDERER_FILENAME
423
- })
424
- ];
425
- }
426
- return [
427
- ...plugins,
428
- new rspack2.HtmlRspackPlugin({
429
- title: "React Cosmos",
430
- filename: RENDERER_FILENAME
431
- })
432
- ];
433
- }
434
- function isHtmlWebpackPlugin(plugin) {
435
- return isInstanceOfRspackPlugin(plugin, "HtmlWebpackPlugin");
436
- }
437
- function isHtmlRspackPlugin(plugin) {
438
- return isInstanceOfRspackPlugin(plugin, "HtmlRspackPlugin");
439
- }
440
- function changeHtmlPluginFilename(htmlPlugin) {
441
- if (!isIndexHtmlWebpackPlugin(htmlPlugin)) {
442
- return htmlPlugin;
443
- }
444
- const options = htmlPlugin.userOptions || htmlPlugin.options;
445
- const safeOptions = omit(options, ["chunks"]);
446
- return new htmlPlugin.constructor({
447
- ...safeOptions,
448
- filename: RENDERER_FILENAME
449
- });
450
- }
451
- function isIndexHtmlWebpackPlugin(htmlPlugin) {
452
- const { filename } = htmlPlugin.userOptions || htmlPlugin.options;
453
- return filename === "index.html" || typeof filename !== "string" || filename.endsWith("/index.html");
454
- }
455
-
456
- // src/server/rspackConfig/rspackConfigTopLevelAwait.ts
457
- function ensureRspackConfigTopLevelAwait(baseWebpackConfig) {
458
- const experiments = baseWebpackConfig.experiments || {};
459
- if (!experiments.topLevelAwait) {
460
- experiments.topLevelAwait = true;
461
- }
462
- return experiments;
463
- }
464
-
465
- // src/server/rspackConfig/getDevRspackConfig.ts
466
- async function getDevRspackConfig(cosmosConfig, userRspack) {
467
- const baseRspackConfig = await getUserRspackConfig(cosmosConfig);
468
- const rspackConfig = {
469
- ...baseRspackConfig,
470
- entry: getEntry(cosmosConfig),
471
- output: getOutput(cosmosConfig),
472
- module: getRspackConfigModule(cosmosConfig, baseRspackConfig),
473
- resolve: getRspackConfigResolve(cosmosConfig, baseRspackConfig),
474
- plugins: getPlugins(cosmosConfig, baseRspackConfig, userRspack),
475
- experiments: getExperiments(baseRspackConfig)
476
- };
477
- if (rspackConfig.optimization?.splitChunks) {
478
- const { name } = rspackConfig.optimization.splitChunks;
479
- if (name === false) delete rspackConfig.optimization.splitChunks.name;
480
- }
481
- return rspackConfig;
482
- }
483
- function getEntry(cosmosConfig) {
484
- const { hotReload, reloadOnFail } = createRspackCosmosConfig(cosmosConfig);
485
- const devtoolsHook = resolveRspackClientPath("reactDevtoolsHook");
486
- const clientIndex = resolveRspackClientPath("index");
487
- return hotReload ? [devtoolsHook, getHotMiddlewareEntry(reloadOnFail), clientIndex] : [devtoolsHook, clientIndex];
488
- }
489
- function getOutput({ publicUrl }) {
490
- const filename = "[name].js";
491
- return {
492
- filename,
493
- publicPath: publicUrl,
494
- // Enable click-to-open source in react-error-overlay
495
- devtoolModuleFilenameTemplate: (info) => path7.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
496
- };
497
- }
498
- function getPlugins(cosmosConfig, baseRspackConfig, userRspack) {
499
- const existingPlugins = ignoreEmptyRspackPlugins(baseRspackConfig.plugins);
500
- const globalsPlugin = getGlobalsPlugin(cosmosConfig, userRspack, true);
501
- const noEmitErrorsPlugin = new userRspack.NoEmitOnErrorsPlugin();
502
- let plugins = [...existingPlugins, globalsPlugin, noEmitErrorsPlugin];
503
- const { hotReload } = createRspackCosmosConfig(cosmosConfig);
504
- if (hotReload && !hasPlugin(plugins, "HotModuleReplacementPlugin")) {
505
- const hmrPlugin = new userRspack.HotModuleReplacementPlugin();
506
- plugins = [...plugins, hmrPlugin];
507
- }
508
- return ensureHtmlPlugin(plugins);
509
- }
510
- function getHotMiddlewareEntry(reloadOnFail) {
511
- const clientPath = resolve("webpack-hot-middleware/client");
512
- return `${clientPath}?reload=${reloadOnFail}&overlay=false`;
513
- }
514
- function getExperiments(baseWebpackConfig) {
515
- return ensureRspackConfigTopLevelAwait(baseWebpackConfig);
516
- }
517
-
518
- // src/server/rspackDevServerPlugin.ts
519
- async function rspackDevServerPlugin({
520
- cosmosConfig,
521
- platform,
522
- expressApp,
523
- sendMessage
524
- }) {
525
- if (platform !== "web") {
526
- return;
527
- }
528
- const userRspack = getRspack(cosmosConfig.rootDir);
529
- if (!userRspack) {
530
- return;
531
- }
532
- const rspackConfig = await getDevRspackConfig(
533
- cosmosConfig,
534
- userRspack
535
- );
536
- if (cosmosConfig.staticPath === null) {
537
- const rspackDerivedStaticPath = getRspackStaticPath(rspackConfig);
538
- if (rspackDerivedStaticPath !== null) {
539
- serveStaticDir(
540
- expressApp,
541
- path8.resolve(cosmosConfig.rootDir, rspackDerivedStaticPath),
542
- cosmosConfig.publicUrl
543
- );
544
- }
545
- }
546
- function sendBuildMessage(msg) {
547
- sendMessage(msg);
548
- }
549
- const rspackCompiler = userRspack(rspackConfig);
550
- rspackCompiler.hooks.invalid.tap("Cosmos", (filePath) => {
551
- if (typeof filePath === "string") {
552
- const relFilePath = path8.relative(process.cwd(), filePath);
553
- console.log("[Cosmos] rspack build invalidated by", relFilePath);
554
- } else {
555
- console.log("[Cosmos] rspack build invalidated by unknown file");
556
- }
557
- sendBuildMessage({ type: "buildStart" });
558
- });
559
- rspackCompiler.hooks.failed.tap("Cosmos", () => {
560
- sendBuildMessage({ type: "buildError" });
561
- });
562
- const onCompilationDone = new Promise((resolve6) => {
563
- rspackCompiler.hooks.done.tap("Cosmos", (stats) => {
564
- resolve6();
565
- if (stats.hasErrors()) {
566
- sendBuildMessage({ type: "buildError" });
567
- } else {
568
- sendBuildMessage({ type: "buildDone" });
569
- }
570
- });
571
- });
572
- console.log("[Cosmos] Building rspack...");
573
- const wdmModule = await import("webpack-dev-middleware");
574
- const wdmInst = wdmModule.default(
575
- // Rspack's Compiler type is pretty close to webpack's Compiler type, but
576
- // is missing a few members. Hopefully WDM doesn't need them, however.
577
- // @rspack/dev-server itself uses webpack-dev-middleware so it should be
578
- // fine.
579
- rspackCompiler,
580
- {
581
- // publicPath is the base path for the rspack assets and has to match
582
- // rspack.output.publicPath
583
- publicPath: cosmosConfig.publicUrl
584
- }
585
- );
586
- expressApp.use(wdmInst);
587
- const { hotReload } = createRspackCosmosConfig(cosmosConfig);
588
- if (hotReload) {
589
- expressApp.use(
590
- webpackHotMiddleware(
591
- // As above, rspack's Compiler type is pretty close to webpack's
592
- // Compiler type so this should be fine.
593
- rspackCompiler
594
- )
595
- );
596
- }
597
- await onCompilationDone;
598
- return async () => {
599
- await new Promise((res) => wdmInst.close(res));
600
- };
601
- }
602
- function getRspackStaticPath({ devServer }) {
603
- return devServer && typeof devServer.contentBase === "string" ? devServer.contentBase : null;
604
- }
605
-
606
- // src/server/rspackConfig/getExportRspackConfig.ts
607
- import * as path9 from "path";
608
- async function getExportRspackConfig(cosmosConfig, userRspack) {
609
- const baseRspackConfig = await getUserRspackConfig(cosmosConfig);
610
- return {
611
- ...baseRspackConfig,
612
- entry: getEntry2(),
613
- output: getOutput2(cosmosConfig),
614
- module: getRspackConfigModule(cosmosConfig, baseRspackConfig),
615
- resolve: getRspackConfigResolve(cosmosConfig, baseRspackConfig),
616
- plugins: getPlugins2(cosmosConfig, baseRspackConfig, userRspack),
617
- experiments: getExperiments2(baseRspackConfig)
618
- };
619
- }
620
- function getEntry2() {
621
- const devtoolsHook = resolveRspackClientPath("reactDevtoolsHook");
622
- const clientIndex = resolveRspackClientPath("index");
623
- return [devtoolsHook, clientIndex];
624
- }
625
- function getOutput2(cosmosConfig) {
626
- const { exportPath, publicUrl } = cosmosConfig;
627
- const { includeHashInOutputFilename } = createRspackCosmosConfig(cosmosConfig);
628
- return {
629
- path: path9.join(exportPath, publicUrl),
630
- filename: includeHashInOutputFilename ? "[name].[contenthash].js" : "[name].js",
631
- publicPath: publicUrl
632
- };
633
- }
634
- function getPlugins2(cosmosConfig, baseRspackConfig, userRspack) {
635
- const existingPlugins = ignoreEmptyRspackPlugins(baseRspackConfig.plugins);
636
- const globalsPlugin = getGlobalsPlugin(cosmosConfig, userRspack, false);
637
- const noEmitErrorsPlugin = new userRspack.NoEmitOnErrorsPlugin();
638
- return ensureHtmlPlugin([
639
- ...existingPlugins,
640
- globalsPlugin,
641
- noEmitErrorsPlugin
642
- ]);
643
- }
644
- function getExperiments2(baseWebpackConfig) {
645
- return ensureRspackConfigTopLevelAwait(baseWebpackConfig);
646
- }
647
-
648
- // src/server/rspackExportPlugin.ts
649
- async function rspackExportPlugin({ cosmosConfig }) {
650
- const userRspack = getRspack(cosmosConfig.rootDir);
651
- if (!userRspack) {
652
- return;
653
- }
654
- const rspackConfig = await getExportRspackConfig(cosmosConfig, userRspack);
655
- try {
656
- await runRspackCompiler(userRspack, rspackConfig);
657
- } catch (err) {
658
- const rspackError = err;
659
- if (rspackError.rspackErrors) {
660
- rspackError.rspackErrors.forEach((error) => {
661
- console.error(`${error}
662
- `);
663
- });
664
- }
665
- throw rspackError;
666
- }
667
- }
668
- function runRspackCompiler(userRspack, rspackConfig) {
669
- return new Promise((resolve6, reject) => {
670
- const compiler = userRspack(rspackConfig);
671
- compiler.run((err, stats) => {
672
- if (err) {
673
- reject(err);
674
- } else if (stats?.hasErrors()) {
675
- const error = new RspackCompilationError();
676
- error.rspackErrors = stats.toJson().errors;
677
- reject(error);
678
- } else {
679
- resolve6(stats);
680
- }
681
- });
682
- });
683
- }
684
- var RspackCompilationError = class extends Error {
685
- rspackErrors;
686
- constructor() {
687
- super("Rspack errors occurred");
688
- }
689
- };
690
-
691
- // src/server/rspackServerPlugin.ts
692
- var rspackServerPlugin = {
693
- name: "rspack",
694
- config: rspackConfigPlugin,
695
- devServer: rspackDevServerPlugin,
696
- export: rspackExportPlugin
697
- };
698
- var rspackServerPlugin_default = rspackServerPlugin;
699
- export {
700
- rspackServerPlugin_default as default
701
- };