forked from yorgai/ORG2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpack.config.js
More file actions
641 lines (628 loc) · 22.7 KB
/
Copy pathwebpack.config.js
File metadata and controls
641 lines (628 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
const fs = require("fs");
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const Dotenv = require("dotenv-webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const { EsbuildPlugin } = require("esbuild-loader");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// ForkTsCheckerWebpackPlugin removed - causes memory issues with large codebase
// Type checking handled by IDE; transpileOnly: true provides fast builds
module.exports = (env, argv) => {
const isProduction = argv.mode === "production";
const isLightDev = !isProduction && process.env.ORGII_LIGHT_DEV === "true";
// Development build mode:
// - Default: SWC (fast builds ~3-5s + React Fast Refresh for state-preserving HMR)
// - FAST_DEV=true: esbuild (fastest ~2s, but full app remount on changes)
// - ORGII_LIGHT_DEV=true: esbuild, no HMR, no source maps
//
// SWC is a Rust-based compiler that's nearly as fast as esbuild but supports
// React Fast Refresh. esbuild is faster but can't support Fast Refresh.
const useFastDev =
!isProduction && (isLightDev || process.env.FAST_DEV === "true");
const useDevSourceMaps =
!isProduction && !isLightDev && process.env.DEV_SOURCEMAPS !== "false";
const retryMainScriptLoad =
!isProduction &&
(process.env.ORGII_RETRY_MAIN_SCRIPT_LOAD === "true" ||
(process.env.ORGII_RETRY_MAIN_SCRIPT_LOAD !== "false" &&
process.platform === "linux"));
// FAST_PROD=true: use esbuild for transpilation + minification in production.
// Saves ~30-40s vs the SWC+Terser path. Trades some dead-code elimination
// depth for speed. Intended for local fast .app builds, not release builds.
const useFastProd = isProduction && process.env.FAST_PROD === "true";
const isE2E = process.env.ORGII_E2E === "1";
const devServerPort = Number.parseInt(
process.env.WEBPACK_DEV_SERVER_PORT ?? process.env.PORT ?? "1998",
10
);
return {
entry: {
main: "./src/index.tsx",
},
output: {
path: path.resolve(__dirname, "build"),
// IMPORTANT: publicPath must be "/" to ensure assets load from root
// Without this, deep routes like /orgii/marketplace/callback cause 404s
publicPath: "/",
// IMPORTANT: Use stable names in development to prevent 404s during hot reload
// Content hashes change on every rebuild, causing chunk loading failures
filename: isProduction ? "[name].[contenthash].js" : "[name].js",
chunkFilename: isProduction ? "[name].[contenthash].js" : "[name].js",
clean: true,
},
cache: {
type: "filesystem",
// Version the cache for faster invalidation
version: `${isProduction ? "prod" : "dev"}-10`,
buildDependencies: {
config: [__filename],
},
// Don't compress - avoids sass serialization issues
compression: false,
},
// Snapshot: use timestamps for node_modules instead of content hashing.
// node_modules rarely change during a dev session; timestamp checks are much faster.
snapshot: {
managedPaths: [path.resolve(__dirname, "node_modules")],
immutablePaths: [],
module: {
timestamp: true,
hash: false,
},
resolve: {
timestamp: true,
hash: false,
},
},
module: {
parser: {
javascript: {
exportsPresence: "warn",
},
},
rules: [
{
test: /\.css$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader",
],
},
{
test: /\.scss$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader",
"postcss-loader",
{
loader: "sass-loader",
options: {
// Use modern API to eliminate deprecation warnings (80+ warnings slowing builds)
api: "modern",
sassOptions: {
// Silence deprecation warnings for faster compilation
quietDeps: true,
silenceDeprecations: ["legacy-js-api", "import"],
},
},
},
],
},
{
test: /\.jsx$/,
exclude: /node_modules/,
use: useFastDev
? {
loader: "esbuild-loader",
options: {
loader: "jsx",
target: "es2018",
jsx: "automatic",
},
}
: {
// SWC: Fast Rust-based compiler with React Fast Refresh support
loader: "swc-loader",
options: {
jsc: {
target: "es2020",
parser: { syntax: "ecmascript", jsx: true },
transform: {
react: {
runtime: "automatic",
refresh: !isProduction,
},
},
},
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use:
useFastDev || useFastProd
? {
loader: "esbuild-loader",
options: {
loader: "js",
target: "es2020",
},
}
: {
loader: "swc-loader",
options: {
jsc: {
target: "es2020",
parser: { syntax: "ecmascript" },
},
},
},
},
{
test: /\.tsx$/,
exclude: /node_modules/,
use:
useFastDev || useFastProd
? {
// esbuild-loader: fastest but no React Fast Refresh
loader: "esbuild-loader",
options: {
loader: "tsx",
target: "es2020",
jsx: "automatic",
},
}
: {
// SWC: Fast Rust-based compiler with React Fast Refresh support
loader: "swc-loader",
options: {
jsc: {
target: "es2020",
parser: { syntax: "typescript", tsx: true },
transform: {
react: {
runtime: "automatic",
refresh: !isProduction,
},
},
},
},
},
},
{
test: /\.ts$/,
exclude: /node_modules/,
use:
useFastDev || useFastProd
? {
// IMPORTANT: .ts must be parsed as TS (not TSX) to avoid JSX ambiguity
loader: "esbuild-loader",
options: {
loader: "ts",
target: "es2020",
},
}
: {
loader: "swc-loader",
options: {
jsc: {
target: "es2020",
parser: { syntax: "typescript", tsx: false },
},
},
},
},
{
test: /\.(mp4|webm)$/i,
type: "asset/resource",
generator: {
filename: "videos/[name].[contenthash:8][ext]",
},
},
{
// Use webpack 5 asset modules for better performance
// Images smaller than 8KB will be inlined as data URLs
test: /\.(png|jpe?g|gif|webp)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 8 * 1024, // 8KB threshold for inlining
},
},
generator: {
filename: "images/[name].[contenthash:8][ext]",
},
},
{
test: /\.(woff2?|ttf|otf)$/i,
type: "asset/resource",
generator: {
filename: "fonts/[name].[contenthash:8][ext]",
},
},
{
// SVGs with ?url query - return URL instead of React component (for <img src>)
test: /\.svg$/,
resourceQuery: /url/,
type: "asset/resource",
generator: {
filename: "images/[name].[contenthash:8][ext]",
},
},
{
// Regular SVGs - convert to React components with @svgr
test: /\.svg$/,
resourceQuery: { not: [/url/] },
use: [
{
loader: "@svgr/webpack",
options: {
svgo: true,
svgoConfig: {
plugins: [
{
name: "preset-default",
params: {
overrides: {
removeViewBox: false, // Keep viewBox for proper scaling
},
},
},
],
},
},
},
],
},
{
test: /node_modules\/@webcontainer\/api/,
sideEffects: false,
},
{
// GLSL shaders - load as raw text for WebGL
test: /\.glsl$/,
use: "raw-loader",
},
{
// Markdown files - load as raw text strings
test: /\.md$/,
type: "asset/source",
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".mjs"],
// Only resolve from node_modules. src/ paths are handled by aliases (@src, etc.)
// Having src in modules causes extra filesystem lookups for every bare import.
modules: ["node_modules"],
alias: {
"@": path.resolve(__dirname),
"@src": path.resolve(__dirname, "src/"),
"@api": path.resolve(__dirname, "src/api/"),
"@common": path.resolve(__dirname, "src/common/"),
"@page": path.resolve(__dirname, "src/page/"),
"@assets": path.resolve(__dirname, "src/assets/"),
"@codemirror/commands": path.dirname(
require.resolve("@codemirror/commands")
),
"@codemirror/language": path.dirname(
require.resolve("@codemirror/language")
),
"@codemirror/state": path.dirname(require.resolve("@codemirror/state")),
"@codemirror/view": path.dirname(require.resolve("@codemirror/view")),
// @a2ui/web_core exports ./v0_9 only under "default" condition, not "import"/"browser".
// Webpack's package exports resolution omits "default"-only exports, so alias directly.
// Point at the DIRECTORY (not index.js): webpack alias does prefix matching, so the bare
// import resolves via directory-index (src/v0_9/index.js) while subpath imports like
// "@a2ui/web_core/v0_9/basic_catalog" resolve to src/v0_9/basic_catalog (its index.js).
// The "." entry resolves to .../src/v0_8/index.js; walk up to src/ then into v0_9 so this
// stays correct under pnpm's symlinked store (matches the @codemirror/* pattern above).
"@a2ui/web_core/v0_9": path.join(
path.dirname(path.dirname(require.resolve("@a2ui/web_core"))),
"v0_9"
),
// react-syntax-highlighter expects the v1 lowlight lib/core.js entry.
// Resolve that nested dependency explicitly from the pnpm store when needed.
"lowlight/lib/core": (() => {
const fs = require("fs");
const pnpmDir = path.resolve(__dirname, "node_modules/.pnpm");
try {
const dir = fs
.readdirSync(pnpmDir)
.find((d) => d.startsWith("lowlight@1."));
if (dir)
return path.join(
pnpmDir,
dir,
"node_modules/lowlight/lib/core.js"
);
} catch (_ignored) {}
return path.resolve(
__dirname,
"node_modules/react-syntax-highlighter/node_modules/lowlight/lib/core.js"
);
})(),
},
fallback: {
process: require.resolve("process/browser"),
fs: false,
// sql.js requires crypto but doesn't actually use it in browser
crypto: false,
path: false,
},
},
optimization: {
minimize: isProduction,
minimizer: isProduction
? useFastProd
? [
// FAST_PROD: esbuild minifier — ~10× faster than Terser, saves ~30s locally.
// Slightly less aggressive dead-code elimination but output is production-safe.
new EsbuildPlugin({
target: "es2020",
css: true,
keepNames: true,
drop: ["console", "debugger"],
}),
]
: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: [
"console.log",
"console.info",
"console.debug",
"console.trace",
],
passes: 1,
dead_code: true,
},
mangle: {
keep_classnames: true,
keep_fnames: true,
},
keep_classnames: true,
keep_fnames: true,
output: {
comments: false,
ascii_only: true,
},
},
extractComments: false,
}),
new CssMinimizerPlugin(),
]
: [],
// In dev, skip expensive per-module regex splitting and runtime chunk extraction.
// Only apply granular code splitting in production for caching benefits.
...(isProduction
? {
splitChunks: {
chunks: "all",
maxInitialRequests: 25,
maxAsyncRequests: 30,
minSize: 20000,
cacheGroups: {
initialVendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "initial",
priority: 20,
reuseExistingChunk: true,
},
asyncVendors: {
test(module) {
const moduleContext = module.context || "";
const isShikiLazyGrammarModule =
/[\\/]node_modules[\\/]\.pnpm[\\/]@shikijs\+(langs|themes)@/.test(
moduleContext
) ||
/[\\/]node_modules[\\/]@shikijs[\\/](langs|themes)[\\/]/.test(
moduleContext
);
return (
!isShikiLazyGrammarModule &&
/[\\/]node_modules[\\/]/.test(moduleContext)
);
},
name(module, chunks) {
const moduleContext = module.context || "";
const packageMatch =
moduleContext.match(
/[\\/]node_modules[\\/]\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/](.*?)([\\/]|$)/
) ||
moduleContext.match(
/[\\/]node_modules[\\/](.*?)([\\/]|$)/
);
let packageName = packageMatch?.[1];
if (packageName?.startsWith("@")) {
const scopedPackageMatch =
moduleContext.match(
/[\\/]node_modules[\\/]\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/](@[^\\/]+[\\/][^\\/]+)/
) ||
moduleContext.match(
/[\\/]node_modules[\\/](@[^\\/]+[\\/][^\\/]+)/
);
packageName = scopedPackageMatch?.[1] ?? packageName;
}
if (packageName) {
return `async-vendors.${packageName
.replace("@", "")
.replace(/[\\/]/g, ".")
.replace(/[^a-zA-Z0-9_.-]/g, "-")}`;
}
const namedChunks = chunks
.map((chunk) => chunk.name)
.filter(Boolean)
.sort();
if (namedChunks.length === 0) {
return "async-vendors";
}
return `async-vendors.${namedChunks[0].replace(
/[^a-zA-Z0-9_.-]/g,
"-"
)}`;
},
chunks: "async",
priority: 15,
reuseExistingChunk: true,
},
asyncCommon: {
chunks: "async",
minChunks: 2,
priority: 8,
reuseExistingChunk: true,
},
common: {
chunks: "initial",
minChunks: 2,
priority: 5,
reuseExistingChunk: true,
name: "common",
},
},
},
runtimeChunk: "single",
}
: {
splitChunks: false,
runtimeChunk: false,
}),
moduleIds: isProduction ? "deterministic" : "named",
},
plugins: [
// CleanWebpackPlugin: only needed for production builds.
// Dev server uses in-memory FS; output.clean handles the rest.
isProduction && new CleanWebpackPlugin(),
// Main app HTML
new HtmlWebpackPlugin({
template: "./public/index.html",
chunks: ["main"],
filename: "index.html",
// Linux WebKitGTK can internally fail a static <script src="/main.js">
// load even after the dev server is ready; a failed script is not
// retried, so Linux dev uses the retrying external loader below.
inject: retryMainScriptLoad ? false : "body",
retryMainScriptLoad,
}),
// NOTE: HotModuleReplacementPlugin is automatically added by webpack-dev-server when hot: true
// ReactRefreshWebpackPlugin works with SWC's refresh: true option to enable
// state-preserving hot reload. Only enabled when not using esbuild/light mode.
!isProduction &&
!useFastDev &&
!isLightDev &&
new ReactRefreshWebpackPlugin({ overlay: false }),
new Dotenv({
systemvars: true,
silent: !fs.existsSync(path.resolve(__dirname, ".env")),
}),
isProduction &&
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css",
ignoreOrder: true,
}),
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify(argv.mode),
// Local Rust IDE-server port, baked into the bundle so a second app
// instance (dual-instance collab testing) talks to its own backend.
// Must match the ORGII_IDE_SERVER_PORT the Rust side is launched with.
"process.env.ORGII_IDE_SERVER_PORT": JSON.stringify(
process.env.ORGII_IDE_SERVER_PORT ?? "13847"
),
"process.env.ORGII_DEEP_LINK_SCHEME": JSON.stringify(
process.env.ORGII_DEEP_LINK_SCHEME ?? "orgii"
),
"process.env.E2E_BASE_URL": JSON.stringify(
process.env.E2E_BASE_URL ??
`http://127.0.0.1:${process.env.ORGII_IDE_SERVER_PORT ?? "13847"}`
),
}),
// CopyWebpackPlugin: only needed for production.
// In dev, static directory serves public/ files directly.
isProduction &&
new CopyWebpackPlugin({
patterns: [{ from: "public/**/*.css", to: "[name][ext]" }],
}),
// ForkTsCheckerWebpackPlugin disabled - causes memory issues with large codebase
// Type checking is handled by IDE instead. transpileOnly: true provides fast builds.
].filter(Boolean),
devServer: {
port: devServerPort,
hot: !isLightDev,
// Light dev avoids the webpack-dev-server browser client entirely.
// WebKitGTK can trip internal loader errors around the injected
// liveReload websocket path, and Tauri dev does not need it here.
liveReload: !isLightDev,
historyApiFallback: true,
// Disable static file watching to prevent full page reloads during HMR.
// Default behavior watches public/ directory, which can race with HMR
// updates and trigger unnecessary index.html reloads.
static: {
directory: path.resolve(__dirname, "public"),
watch: false,
},
client: isLightDev
? false
: {
overlay: false,
// Reconnect settings for better HMR recovery
reconnect: 5,
webSocketURL: {
hostname: "localhost",
pathname: "/ws",
port: devServerPort,
},
},
open: false,
headers: {
"Cross-Origin-Embedder-Policy": "credentialless",
"Cross-Origin-Opener-Policy": "same-origin-allow-popups",
"Cross-Origin-Resource-Policy": "cross-origin",
},
proxy: {
// TaskTracker API proxy - avoids CORS issues with localhost:8002
"/tasktracker-api": {
target: "http://127.0.0.1:8002",
changeOrigin: true,
secure: false,
pathRewrite: { "^/tasktracker-api": "" },
},
},
},
ignoreWarnings: [
{
module: /keepalive-for-react/,
message: /export 'Activity'/,
},
],
performance: {
hints: false,
},
stats: {
all: false,
errors: true,
warnings: true,
timings: true,
version: false, // Skip version check for faster startup
builtAt: false, // Skip timestamp for faster startup
modules: false, // Skip module list for faster startup
colors: true,
// Only show minimal info in dev mode
preset: isProduction ? "normal" : "minimal",
},
// eval-cheap-module-source-map maps to original lines via loaders.
// Light dev disables source maps to reduce renderer and compiler memory.
devtool: useDevSourceMaps ? "eval-cheap-module-source-map" : false,
};
};