forked from metabase/metabase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrspack.embedding-sdk-bundle.config.js
More file actions
380 lines (343 loc) · 12.9 KB
/
rspack.embedding-sdk-bundle.config.js
File metadata and controls
380 lines (343 loc) · 12.9 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
/* eslint-env node */
/* eslint-disable import/no-commonjs */
/* eslint-disable import/order */
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
const rspack = require("@rspack/core");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const prefixwrap = require("postcss-prefixwrap");
const mainConfig = require("./rspack.main.config");
const { resolve } = require("path");
const path = require("path");
const postcssConfig = require("./postcss.config.js");
const {
LICENSE_TEXT,
IS_DEV_MODE,
} = require("./frontend/build/shared/constants");
const {
OPTIMIZATION_CONFIG,
} = require("./frontend/build/embedding-sdk/rspack/shared");
const { BABEL_CONFIG } = require("./frontend/build/shared/rspack/babel-config");
const { CSS_CONFIG } = require("./frontend/build/shared/rspack/css-config");
const {
EXTERNAL_DEPENDENCIES,
} = require("./frontend/build/embedding-sdk/constants/external-dependencies");
const {
getBannerOptions,
} = require("./frontend/build/shared/rspack/get-banner-options");
const { SVGO_CONFIG } = require("./frontend/build/shared/rspack/svgo-config");
const {
COMPRESSION_CONFIG,
} = require("./frontend/build/shared/rspack/compression");
const {
SDK_BUNDLE_PATH,
SDK_BUNDLE_FILENAME,
SDK_BUNDLE_BOOTSTRAP_FILENAME,
} = require("./frontend/build/embedding-sdk/constants/sdk-bundle");
const {
getBuildInfoValues,
} = require("./frontend/build/embedding-sdk/rspack/get-build-info-values");
const {
getSdkBundleVersionFromVersionProperties,
} = require("./frontend/build/embedding-sdk/lib/get-sdk-bundle-version-from-version-properties");
const SDK_BUNDLE_SRC_PATH = __dirname + "/frontend/src/embedding-sdk-bundle";
const BUILD_PATH = __dirname + "/resources/frontend_client";
const SDK_OUTPUT_PATH = path.join(BUILD_PATH, SDK_BUNDLE_PATH);
const ENTERPRISE_SRC_PATH =
__dirname + "/enterprise/frontend/src/metabase-enterprise";
const shouldAnalyzeBundles = process.env.SHOULD_ANALYZE_BUNDLES === "true";
// Name prefix for all chunked-entry output files (runtime, split chunks, entry)
const CHUNKED_PREFIX = "embedding-sdk-chunk";
const config = {
...mainConfig,
name: "embedding_sdk_bundle",
context: SDK_BUNDLE_SRC_PATH,
entry: {
// Legacy monolithic bundle — backward compatible for old NPM packages.
// Must remain a single file (splitChunks excludes it).
"embedding-sdk": "./index.ts",
// Bootstrap — tiny script that starts auth early and loads chunks
"embedding-sdk-bootstrap": "./embedding-sdk-bootstrap.ts",
// Chunked entry — same code as monolithic, but splitChunks splits it into
// multiple smaller files for faster V8 parse+eval via parallel streaming.
"embedding-sdk-chunked": {
import: "./index.ts",
runtime: "embedding-sdk-chunk-runtime",
},
},
output: {
path: SDK_OUTPUT_PATH,
publicPath: "",
// Unique name prevents self["webpackChunk"] collisions when the SDK
// is loaded on a page that already has another webpack/rspack runtime
// (e.g. the main Metabase app, Cypress test runner, customer's own app).
uniqueName: "embedding_sdk_bundle",
// Split chunks and bootstrap go into chunks/ subfolder.
// The legacy monolithic bundle goes into legacy/.
// The backend serves chunks/ with far-future immutable cache headers.
chunkFilename: "chunks/[id].[contenthash:8].js",
filename: (pathData) => {
switch (pathData.chunk?.name) {
case "embedding-sdk-bootstrap":
return `chunks/${SDK_BUNDLE_BOOTSTRAP_FILENAME}`;
case "embedding-sdk":
return `legacy/${SDK_BUNDLE_FILENAME}`;
default:
return "chunks/[name].[contenthash:8].js";
}
},
},
devtool: IS_DEV_MODE ? mainConfig.devtool : false,
// Same behavior as for webpack: https://rspack.rs/config/other-options#amd
amd: {},
module: {
rules: [
{
test: /\.(tsx?|jsx?)$/,
exclude: /node_modules|cljs/,
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: BABEL_CONFIG.cacheDirectory,
},
},
],
},
{
test: /\.(svg|png)$/,
type: "asset/inline",
resourceQuery: { not: [/component|source/] },
},
{
test: /\.css$/,
oneOf: [
// Scope SDK Mantine styles to the SDK to prevent leakage outside of the SDK
{
include: [/[\\/]@mantine[\\/].*\.css$/],
use: [
{ loader: "style-loader" },
{ loader: "css-loader", options: CSS_CONFIG },
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
...postcssConfig.plugins,
prefixwrap(":where(.mb-wrapper)", {
// We apply scope to selectors that start with `.m_`
// It skips some selectors like `[dir="ltr"] .m_*` but there's no ability to insert the `:where(.mb-wrapper)` between `[dir="ltr"]` and `.m_*`
ignoredSelectors: [/^(?!\.m_).*/],
}),
],
},
},
},
],
},
{
use: [
{ loader: "style-loader" },
{ loader: "css-loader", options: CSS_CONFIG },
{ loader: "postcss-loader" },
],
},
],
},
{
test: /\.js$/,
exclude: /node_modules/,
enforce: "pre",
use: ["source-map-loader"],
},
{
test: /\.svg/,
type: "asset/source",
resourceQuery: /source/, // *.svg?source
},
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
resourceQuery: /component/, // *.svg?component
use: [
{
loader: "@svgr/webpack",
options: {
ref: true,
svgoConfig: SVGO_CONFIG,
},
},
],
},
],
},
externals: EXTERNAL_DEPENDENCIES,
optimization: {
...OPTIMIZATION_CONFIG,
// Scope hoisting: merges ES modules into fewer closures, reducing parse overhead
concatenateModules: true,
// Avoid wrapping entry points in an IIFE — removes unnecessary function wrapper
avoidEntryIife: true,
// Override splitChunks: split the chunked entry into multiple pieces,
// but leave the legacy monolithic entry as a single file.
splitChunks: {
chunks: (chunk) => {
// Only split chunks that belong to the chunked entry
// (the entry itself + its runtime). Never split the legacy
// monolithic "embedding-sdk" or the bootstrap.
const name = chunk.name || "";
return name.startsWith(CHUNKED_PREFIX);
},
// Keep chunk count low (~10-12) so HTTP/1.1 clients (no reverse proxy)
// can load them in 1-2 waves (6 connections per domain).
// maxSize is the primary lever — larger maxSize = fewer chunks.
maxInitialRequests: 10,
maxSize: 5_000_000,
minSize: 100_000,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
// Use a fixed name prefix so rspack merges vendors into a few chunks
// (governed by maxSize) rather than one-per-package.
name: "vendor",
reuseExistingChunk: true,
},
default: {
minChunks: 1,
reuseExistingChunk: true,
},
},
},
},
plugins: [
new rspack.BannerPlugin(getBannerOptions(LICENSE_TEXT)),
new NodePolyfillPlugin(), // for crypto, among others
// https://github.com/remarkjs/remark/discussions/903
new rspack.ProvidePlugin({
process: "process/browser.js",
}),
new rspack.EnvironmentPlugin({
IS_EMBEDDING_SDK: "true",
...getBuildInfoValues({
version: getSdkBundleVersionFromVersionProperties(),
}),
}),
// Inject chunk manifest and hashes into the bootstrap so it can load
// all the right files with cache-busting URLs.
{
name: "inject-bundle-manifest",
apply(compiler) {
compiler.hooks.compilation.tap(
"inject-bundle-manifest",
(compilation) => {
compilation.hooks.processAssets.tap(
{
name: "inject-bundle-manifest",
// Must run BEFORE minification (OPTIMIZE_SIZE = 8000).
// The placeholder "__SDK_CHUNK_MANIFEST__" is a string literal
// that the minifier constant-folds ("str".chunks → void 0)
// if we don't replace it first.
stage: rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
},
(assets) => {
const bootstrapKey = `chunks/${SDK_BUNDLE_BOOTSTRAP_FILENAME}`;
const bootstrapAsset = assets[bootstrapKey];
if (!bootstrapAsset) {
return;
}
// Collect ALL chunk files for the chunked entry using the
// compilation's entrypoint API. This includes split chunks
// with any name (e.g. default-vendors-*), not just those
// matching CHUNKED_PREFIX.
const entrypoint = compilation.entrypoints.get(
"embedding-sdk-chunked",
);
const chunkFiles = [];
if (entrypoint) {
for (const chunk of entrypoint.chunks) {
for (const file of chunk.files) {
// In hot mode rspack may attach HMR payload files
// (*.hot-update.js) to chunk.files. Those are not
// executable bundle chunks and must never be loaded
// by the bootstrap manifest.
if (
file.endsWith(".js") &&
!file.includes(".hot-update.")
) {
chunkFiles.push(file);
}
}
}
}
chunkFiles.sort();
// Separate the runtime from the rest — runtime gets inlined
// into the bootstrap so we avoid an extra sequential request.
const runtimeFile =
chunkFiles.find((f) =>
/^chunks\/embedding-sdk-chunk-runtime\.[^/]+\.js$/.test(f),
) || chunkFiles.find((f) => f.includes("chunk-runtime"));
const otherFiles = chunkFiles.filter((f) => f !== runtimeFile);
// Paths are relative to /app/ (the bootstrap's baseUrl).
// Chunk asset keys already include "chunks/" prefix, so
// prepend "embedding-sdk/" to get the full route path.
const manifest = {
chunks: otherFiles.map((f) => `embedding-sdk/${f}`),
};
// Read the runtime chunk source to inline it in the bootstrap
const runtimeSource =
runtimeFile && assets[runtimeFile]
? assets[runtimeFile].source()
: "";
if (!runtimeSource) {
console.warn(
"inject-bundle-manifest: runtime chunk not found, bootstrap will not work",
);
}
let newSource = bootstrapAsset.source();
// Inject the chunk manifest as JSON
newSource = newSource.replace(
/"__SDK_CHUNK_MANIFEST__"/g,
JSON.stringify(manifest),
);
// Inline the runtime chunk source at the end of the bootstrap.
// The runtime sets up __webpack_require__ and the chunk registry
// that other chunks register into when they load.
if (runtimeSource) {
newSource +=
"\n// --- Inlined runtime chunk ---\n" + runtimeSource;
}
compilation.updateAsset(
bootstrapKey,
new rspack.sources.RawSource(newSource),
);
},
);
},
);
},
},
shouldAnalyzeBundles &&
new BundleAnalyzerPlugin({
analyzerMode: "static",
reportFilename: BUILD_PATH + "/dist/report.html",
}),
...COMPRESSION_CONFIG,
].filter(Boolean),
};
config.resolve.alias = {
...mainConfig.resolve.alias,
"sdk-ee-plugins": ENTERPRISE_SRC_PATH + "/sdk-plugins",
"sdk-iframe-embedding-ee-plugins":
ENTERPRISE_SRC_PATH + "/sdk-iframe-embedding-plugins",
"ee-overrides": ENTERPRISE_SRC_PATH + "/overrides",
// Allows importing side effects that applies only to the SDK.
"sdk-specific-imports": SDK_BUNDLE_SRC_PATH + "/lib/sdk-specific-imports.ts",
};
if (config.cache) {
config.cache.cacheDirectory = resolve(
__dirname,
"node_modules/.cache/",
"webpack-ee",
);
}
module.exports = config;