Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add a bundle size analyzer to the dev-tools (#43950)

David Taylorb3af1310b5ef
diff --git a/app/controllers/bundle_analysis_controller.rb b/app/controllers/bundle_analysis_controller.rb
new file mode 100644
index 00000000000..a9fa38b24b8
--- /dev/null
+++ b/app/controllers/bundle_analysis_controller.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+# Where the bundle analyzer dev tool finds the reports the builds left behind.
+# One per plugin, since each plugin compiles on its own, plus core's.
+class BundleAnalysisController < ApplicationController
+ skip_before_action :preload_json, :check_xhr
+
+ def index
+ enabled = Discourse.plugins.select(&:enabled?).map(&:directory_name).to_set
+ reports =
+ Plugin::JsManager.bundle_analysis_assets.filter_map do |name, path|
+ path if enabled.include?(name)
+ end
+
+ render json: {
+ core: report_url(EmberAssets.bundle_analysis_asset),
+ plugins: reports.map { report_url(it) },
+ }
+ end
+
+ private
+
+ def report_url(logical_path)
+ view_context.asset_cdn_path(logical_path, brotli: true) if logical_path
+ end
+end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index cb5c399c19b..b1ad18eb6cf 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -129,7 +129,11 @@ module ApplicationHelper
end
def script_asset_path(script)
- path = ActionController::Base.helpers.asset_path("#{script}.js")
+ asset_cdn_path("#{script}.js", brotli: true)
+ end
+
+ def asset_cdn_path(logical_path, brotli: false)
+ path = ActionController::Base.helpers.asset_path(logical_path)
if GlobalSetting.use_s3? && GlobalSetting.s3_cdn_url
resolved_s3_asset_cdn_url =
@@ -151,7 +155,7 @@ module ApplicationHelper
path = "#{resolved_s3_asset_cdn_url}#{path}"
end
- path = path.sub("/assets/js/", "/assets/br/") if is_brotli_req?
+ path = path.sub("/assets/js/", "/assets/br/") if brotli && is_brotli_req?
end
path
diff --git a/config/routes.rb b/config/routes.rb
index 5bc85dbdc72..c83ef7df697 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -2051,6 +2051,8 @@ Discourse::Application.routes.draw do
get "/safe-mode" => "safe_mode#index"
post "/safe-mode" => "safe_mode#enter", :as => "safe_mode_enter"
+ get "/bundle-analysis.json" => "bundle_analysis#index"
+
get "/dev-mode" => "dev_mode#index"
post "/dev-mode" => "dev_mode#enter", :as => "dev_mode_enter"
diff --git a/frontend/asset-processor/asset-processor-rollup.js b/frontend/asset-processor/asset-processor-rollup.js
index 6d15bae7a26..d843fe7fff0 100644
--- a/frontend/asset-processor/asset-processor-rollup.js
+++ b/frontend/asset-processor/asset-processor-rollup.js
@@ -219,6 +219,12 @@ async function performRollup(modules, opts) {
imports: chunk.imports.filter((i) =>
bundle.output.find((c) => c.fileName === i)
),
+ modules: Object.entries(chunk.modules)
+ .map(([id, m]) => ({
+ id: id.startsWith(basePath) ? id.slice(basePath.length) : id,
+ renderedLength: m.renderedLength,
+ }))
+ .sort((a, b) => b.renderedLength - a.renderedLength),
routeBundles: chunk.isEntry
? routeBundlesForEntry(chunk.name)
: undefined,
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/button.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/button.gjs
new file mode 100644
index 00000000000..350597a5a96
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/button.gjs
@@ -0,0 +1,26 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import BundleAnalyzerModal from "./components/modal.gjs";
+
+export default class BundleAnalyzerButton extends Component {
+ @service modal;
+
+ @action
+ show() {
+ this.modal.show(BundleAnalyzerModal);
+ }
+
+ <template>
+ <button
+ class="bundle-analyzer-button"
+ title="Bundle analyzer"
+ type="button"
+ {{on "click" this.show}}
+ >
+ {{dIcon "chart-column"}}
+ </button>
+ </template>
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/analyzer-toolbar.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/analyzer-toolbar.gjs
new file mode 100644
index 00000000000..6316a1fd843
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/analyzer-toolbar.gjs
@@ -0,0 +1,31 @@
+import { hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import DFilterInput from "discourse/ui-kit/d-filter-input";
+import DNativeSelect from "discourse/ui-kit/d-native-select";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+
+export default <template>
+ <div class="ba-toolbar">
+ <DFilterInput
+ placeholder={{@placeholder}}
+ @filterAction={{@onFilter}}
+ @icons={{hash left="magnifying-glass"}}
+ @value={{@filter}}
+ />
+ <DNativeSelect
+ @includeNone={{false}}
+ @onChange={{@onScope}}
+ @value={{@scope}}
+ as |select|
+ >
+ <select.Option @value="all">Core and plugins</select.Option>
+ <select.Option @value="core">Core only</select.Option>
+ <select.Option @value="plugins">Plugins only</select.Option>
+ </DNativeSelect>
+ <DToggleSwitch
+ @state={{@view.onlyLoaded}}
+ @translatedLabel="Only show loaded chunks"
+ {{on "click" @view.toggle}}
+ />
+ </div>
+</template>
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/chunk-row.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/chunk-row.gjs
new file mode 100644
index 00000000000..5cd5d426b5b
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/chunk-row.gjs
@@ -0,0 +1,129 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import {
+ barWidth,
+ fileName,
+ fmt,
+ label,
+ matches,
+ routeName,
+ sizeOrDash,
+} from "../models/analysis.js";
+import Expansion from "../models/expansion.js";
+import Row from "./row.gjs";
+
+// One expandable chunk row. `@root` marks the card's own chunk rather than one
+// it pulls in.
+export default class ChunkRow extends Component {
+ // A filter matching a module inside this chunk opens it on that module.
+ expansion = new Expansion({
+ defaultTo: () => !!this.args.filter && this.visibleModules.length > 0,
+ filter: () => this.args.filter ?? "",
+ });
+
+ get chunk() {
+ return this.args.analysis.chunks[this.args.file];
+ }
+
+ get route() {
+ return routeName(this.chunk);
+ }
+
+ get isLoaded() {
+ return this.args.loaded?.has(this.args.file);
+ }
+
+ get label() {
+ return label(this.chunk);
+ }
+
+ get fileName() {
+ return fileName(this.args.file);
+ }
+
+ get usedBy() {
+ return this.args.analysis.usedByEntries[this.args.file] || [];
+ }
+
+ get usedByLabel() {
+ return this.usedBy.length
+ ? this.usedBy.map((f) => label(this.args.analysis.chunks[f])).join(", ")
+ : "—";
+ }
+
+ get maxModule() {
+ return this.chunk.modules.length ? this.chunk.modules[0].renderedLength : 1;
+ }
+
+ @cached
+ get visibleModules() {
+ return this.chunk.modules.filter((m) => matches(m.id, this.args.filter));
+ }
+
+ get brotliLabel() {
+ return sizeOrDash(this.args.analysis.brotliOf(this.args.file));
+ }
+
+ <template>
+ <Row
+ @expanded={{this.expansion.expanded}}
+ @loaded={{this.isLoaded}}
+ @toggle={{this.expansion.toggle}}
+ >
+ <:name>
+ {{#unless @root}}
+ {{#if this.chunk.isEntry}}
+ <span class="ba-badge">entry</span>
+ {{/if}}
+ {{#if this.route}}
+ <span class="ba-badge route">route: {{this.route}}</span>
+ {{else if this.chunk.isDynamicEntry}}
+ <span class="ba-badge">dynamic</span>
+ {{/if}}
+ {{#if @added}}
+ <span class="ba-badge add">added</span>
+ {{/if}}
+ {{/unless}}
+ {{#if @root}}
+ <span class="ba-label root">entrypoint chunk</span>
+ {{else}}
+ <span class="ba-label" title={{@file}}>
+ {{this.label}}
+ <span class="ba-pill">·
+ {{this.chunk.modules.length}}
+ modules</span>
+ </span>
+ {{/if}}
+ </:name>
+ <:numbers>
+ <span class="ba-num">{{this.brotliLabel}}
+ <span class="ba-pill">br</span></span>
+ <span class="ba-num muted">{{fmt this.chunk.rawSize}}
+ <span class="ba-pill">raw</span></span>
+ </:numbers>
+ <:body>
+ <div class="ba-site">file
+ <code>{{this.fileName}}</code>
+ </div>
+ <div class="ba-note">
+ Used by
+ {{this.usedByLabel}}
+ </div>
+ <div class="ba-note">
+ Source bytes, before minifying.
+ </div>
+ {{#each this.visibleModules as |m|}}
+ <div class="ba-mod" title={{m.id}}>
+ <div>
+ <div class="ba-mname">{{m.id}}</div>
+ <div class="ba-bar">
+ <span style={{barWidth m.renderedLength this.maxModule}}></span>
+ </div>
+ </div>
+ <div class="ba-num">{{fmt m.renderedLength}}</div>
+ </div>
+ {{/each}}
+ </:body>
+ </Row>
+ </template>
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/entrypoint-card.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/entrypoint-card.gjs
new file mode 100644
index 00000000000..2d288888e62
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/entrypoint-card.gjs
@@ -0,0 +1,179 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { brotliLabel, fmt, label, routeName } from "../models/analysis.js";
+import Expansion from "../models/expansion.js";
+import ChunkRow from "./chunk-row.gjs";
+import Row from "./row.gjs";
+
+// One entrypoint as an expandable card of the chunks it pulls in. `@baseline`
+// marks the card the others measure against, which shows its whole load rather
+// than a delta. `@urls` names what loads a bundle no import site points at.
+export default class EntrypointCard extends Component {
+ // Every card on screen matches the filter, so a filter opens them all.
+ expansion = new Expansion({
+ defaultTo: () => !!this.args.filter,
+ filter: () => this.args.filter ?? "",
+ });
+
+ get analysis() {
+ return this.args.analysis;
+ }
+
+ get chunk() {
+ return this.analysis.chunks[this.args.file];
+ }
+
+ get route() {
+ return routeName(this.chunk);
+ }
+
+ // `isDynamicEntry` is set only while such a module has a chunk to itself,
+ // though both kinds are fetched on demand.
+ get loadedOnDemand() {
+ return !this.chunk.isEntry;
+ }
+
+ get isLoaded() {
+ return this.args.loaded?.has(this.args.file);
+ }
+
+ get markAdded() {
+ return !this.args.baseline;
+ }
+
+ get label() {
+ return label(this.chunk);
+ }
+
+ @cached
+ get rootVisible() {
+ return this.analysis.includes(this.args.file);
+ }
+
+ @cached
+ get loadSet() {
+ return this.analysis.visibleClosure(this.args.file);
+ }
+
+ @cached
+ get added() {
+ if (this.args.baseline) {
+ return [...this.loadSet];
+ }
+ return [...this.loadSet].filter((f) => !this.args.baselineClosure.has(f));
+ }
+
+ @cached
+ get shownTotals() {
+ return this.analysis.totals(this.added);
+ }
+
+ get prefix() {
+ return this.args.baseline ? "" : "+";
+ }
+
+ get shownBrotli() {
+ return brotliLabel(this.shownTotals);
+ }
+
+ get sites() {
+ if (this.args.urls) {
+ return this.args.urls.map((url) => ({ lead: "loaded on", label: url }));
+ }
+ // The page names a static entrypoint itself, and a module inside one can
+ // still be some file's `import()` target.
+ if (this.chunk.isEntry) {
+ return [];
+ }
+ return (this.chunk.importSites ?? []).map((importer) => ({
+ lead: "imported by",
+ label: importer,
+ }));
+ }
+
+ @cached
+ get addedSorted() {
+ return this.added
+ .filter((f) => f !== this.args.file)
+ .filter((f) => this.analysis.chunkMatches(f, this.args.filter))
+ .sort((a, b) => this.analysis.sortSize(b) - this.analysis.sortSize(a));
+ }
+
+ <template>
+ <Row
+ @expanded={{this.expansion.expanded}}
+ @loaded={{this.isLoaded}}
+ @toggle={{this.expansion.toggle}}
+ >
+ <:name>
+ {{#if @baseline}}
+ <span class="ba-badge">baseline</span>
+ {{else if this.route}}
+ <span class="ba-badge route">route: {{this.route}}</span>
+ {{else if this.loadedOnDemand}}
+ <span class="ba-badge">dynamic</span>
+ {{else}}
+ <span class="ba-badge">entry</span>
+ {{/if}}
+ <span
+ class="ba-label"
+ title={{if this.chunk.facadeModuleId this.chunk.facadeModuleId @file}}
+ >{{this.label}}</span>
+ </:name>
+ <:numbers>
+ <span class="ba-num"><b>{{this.prefix}}{{this.shownBrotli}}</b>
+ <span class="ba-pill">br</span></span>
+ <span class="ba-num muted">{{this.prefix}}{{fmt this.shownTotals.raw}}
+ <span class="ba-pill">raw</span></span>
+ </:numbers>
+ <:body>
+ <div class="ba-sites">
+ {{#each this.sites as |site|}}
+ <div class="ba-site">{{site.lead}}
+ <code>{{site.label}}</code>
+ </div>
+ {{else}}
+ <div class="ba-site pill">
+ {{#if this.loadedOnDemand}}
+ no import site found
+ {{else}}
+ loaded as a top-level entrypoint
+ {{/if}}
+ </div>
+ {{/each}}
+ </div>
+ <div class="ba-note">
+ {{#if @baseline}}
+ <b>{{this.loadSet.size}}</b>
+ files
+ {{else}}
+ <b>{{this.added.length}}</b>
+ new files,
+ {{this.loadSet.size}}
+ in its subtree
+ {{/if}}
+ </div>
+ <div class="ba-sub-list">
+ {{#if this.rootVisible}}
+ <ChunkRow
+ @analysis={{@analysis}}
+ @file={{@file}}
+ @filter={{@filter}}
+ @loaded={{@loaded}}
+ @root={{true}}
+ />
+ {{/if}}
+ {{#each this.addedSorted as |f|}}
+ <ChunkRow
+ @added={{this.markAdded}}
+ @analysis={{@analysis}}
+ @file={{f}}
+ @filter={{@filter}}
+ @loaded={{@loaded}}
+ />
+ {{/each}}
+ </div>
+ </:body>
+ </Row>
+ </template>
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/modal.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/modal.gjs
new file mode 100644
index 00000000000..c9661ee8a3f
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/modal.gjs
@@ -0,0 +1,155 @@
+import Component from "@glimmer/component";
+import { DEBUG } from "@glimmer/env";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import "../styles.css";
+import getURL from "discourse/lib/get-url";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import Analysis from "../models/analysis.js";
+import LoadedChunks from "../models/loaded-chunks.js";
+import PluginsAnalysis from "../models/plugins-analysis.js";
+import ViewFilter from "../models/view-filter.js";
+import Report from "./report.gjs";
+
+export default class BundleAnalyzerModal extends Component {
+ @tracked analysis;
+ @tracked plugins;
+ @tracked error;
+ @tracked pluginError;
+
+ // Once per opening, not once per session: the numbers mislead every time.
+ @tracked warningAccepted = false;
+
+ view = new ViewFilter();
+
+ // Core and every plugin build write their own report, so the server lists the
+ // ones it has and they are fetched from there. Either half can be missing
+ // without taking the other down.
+ load = async () => {
+ let index;
+
+ try {
+ index = await this.#fetch(getURL("/bundle-analysis.json"));
+ } catch (e) {
+ if (!this.#destroyed) {
+ this.error = e.message;
+ }
+ return;
+ }
+
+ const core = this.#fetch(index.core).then(
+ (data) => (this.analysis = this.#prepare(new Analysis(data))),
+ (e) => {
+ if (!this.#destroyed) {
+ this.error = e.message;
+ }
+ }
+ );
+
+ const plugins = Promise.all(
+ index.plugins.map((url) => this.#fetch(url))
+ ).then(
+ (reports) =>
+ (this.plugins = this.#prepare(
+ new PluginsAnalysis({ plugins: reports })
+ )),
+ (e) => {
+ if (!this.#destroyed) {
+ this.pluginError = e.message;
+ }
+ }
+ );
+
+ await Promise.all([core, plugins]);
+ };
+
+ #observers = [];
+ #destroyed = false;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#destroyed = true;
+ this.#observers.forEach((o) => o.teardown());
+ }
+
+ get ready() {
+ return !!(this.analysis || this.plugins);
+ }
+
+ // `DEBUG` cannot be named in the template: the compiler lists its scope as
+ // object shorthand, and the macro replacing it rewrites the key as well.
+ get showWarning() {
+ return DEBUG && !this.warningAccepted;
+ }
+
+ @action
+ acceptWarning() {
+ this.warningAccepted = true;
+ }
+
+ #prepare(analysis) {
+ if (this.#destroyed) {
+ return null;
+ }
+ analysis.view = this.view;
+ analysis.loaded = new LoadedChunks(analysis.chunks);
+ this.#observers.push(analysis.loaded);
+ return analysis;
+ }
+
+ async #fetch(url) {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ return response.json();
+ }
+
+ <template>
+ <DModal
+ class="bundle-analyzer-modal"
+ @closeModal={{@closeModal}}
+ @title="Bundle analysis"
+ >
+ <:body>
+ {{#if this.showWarning}}
+ <div class="ba-warning">
+ <h2>Development build</h2>
+ <p>Chunk splitting and sizes are completely different to production,
+ and brotli sizes aren't available. Restart the server with
+ EMBER_ENV=production.</p>
+ <DButton
+ class="btn-primary"
+ @action={{this.acceptWarning}}
+ @translatedLabel="Open analyzer anyway"
+ />
+ </div>
+ {{else}}
+ <div {{didInsert this.load}}>
+ {{#if this.error}}
+ <div class="ba-empty">
+ Failed to load bundle-analysis.json:
+ {{this.error}}
+ </div>
+ {{/if}}
+ {{#if this.pluginError}}
+ <div class="ba-empty">
+ Failed to load bundle-analysis.json:
+ {{this.pluginError}}
+ </div>
+ {{/if}}
+ {{#if this.ready}}
+ <Report
+ @core={{this.analysis}}
+ @plugins={{this.plugins}}
+ @view={{this.view}}
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/plugin-card.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/plugin-card.gjs
new file mode 100644
index 00000000000..38ed1192b4a
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/plugin-card.gjs
@@ -0,0 +1,154 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { brotliLabel, fmt, matches } from "../models/analysis.js";
+import Expansion from "../models/expansion.js";
+import { routeBundlesByFile } from "../models/plugins-analysis.js";
+import EntrypointCard from "./entrypoint-card.gjs";
+import Row from "./row.gjs";
+
+// One plugin, expanding to the cards the core tab is built from. `main` is the
+// baseline, since a plugin loads it on every page; a route bundle measures
+// against the entrypoint that owns it, which its urls have already loaded.
+export default class PluginCard extends Component {
+ expansion = new Expansion({
+ defaultTo: () => !!this.args.filter,
+ filter: () => this.args.filter ?? "",
+ });
+
+ get analysis() {
+ return this.args.analysis;
+ }
+
+ get plugin() {
+ return this.args.plugin;
+ }
+
+ get graph() {
+ return this.analysis.graphFor(this.plugin);
+ }
+
+ // Any one chunk is enough, so a collapsed list says which plugins this page
+ // pulled in.
+ get isLoaded() {
+ return Object.keys(this.plugin.chunks).some((f) =>
+ this.args.loaded?.has(f)
+ );
+ }
+
+ get totals() {
+ return this.analysis.totalsFor(this.plugin);
+ }
+
+ get baselineFile() {
+ const { entrypoints } = this.plugin;
+ return entrypoints.main ?? Object.values(entrypoints)[0];
+ }
+
+ @cached
+ get baselineClosure() {
+ return this.graph.staticClosure(this.baselineFile);
+ }
+
+ @cached
+ get entrypoints() {
+ const base = this.baselineFile;
+ const others = Object.values(this.plugin.entrypoints).filter(
+ (f) => f !== base
+ );
+ return [base, ...others].filter(
+ (f) =>
+ f &&
+ this.graph.cardVisible(
+ f,
+ this.args.filter,
+ f === base ? null : this.baselineClosure
+ )
+ );
+ }
+
+ @cached
+ get routeBundles() {
+ return [...routeBundlesByFile(this.plugin)]
+ .map(([file, { entry, urls }]) => ({
+ file,
+ urls,
+ base: this.graph.staticClosure(this.plugin.entrypoints[entry]),
+ }))
+ .filter(
+ (b) =>
+ this.graph.cardVisible(b.file, this.args.filter, b.base) ||
+ // A filter naming one of its urls keeps a bundle whose chunks do not
+ // match; with nothing typed, what it adds is the only question.
+ (!!this.args.filter &&
+ this.graph.visibleClosure(b.file).size > 0 &&
+ b.urls.some((u) => matches(u, this.args.filter)))
+ )
+ .sort(
+ (a, b) => this.graph.sortSize(b.file) - this.graph.sortSize(a.file)
+ );
+ }
+
+ <template>
+ <Row
+ @expanded={{this.expansion.expanded}}
+ @loaded={{this.isLoaded}}
+ @toggle={{this.expansion.toggle}}
+ >
+ <:name>
+ <span class="ba-badge">plugin</span>
+ <span class="ba-label">{{this.plugin.plugin}}</span>
+ </:name>
+ <:numbers>
+ <span class="ba-num"><b>{{brotliLabel this.totals}}</b>
+ <span class="ba-pill">br</span></span>
+ <span class="ba-num muted">{{fmt this.totals.raw}}
+ <span class="ba-pill">raw</span></span>
+ </:numbers>
+ <:body>
+ <div class="ba-sub-list">
+ {{#each this.entrypoints as |f|}}
+ <EntrypointCard
+ @analysis={{this.graph}}
+ @baseline={{eq f this.baselineFile}}
+ @baselineClosure={{this.baselineClosure}}
+ @file={{f}}
+ @filter={{@filter}}
+ @loaded={{@loaded}}
+ />
+ {{/each}}
+ </div>
+
+ {{#if this.routeBundles}}
+ <div class="ba-hint">
+ Loaded on demand, when a url matches.
+ </div>
+ <div class="ba-sub-list">
+ {{#each this.routeBundles as |b|}}
+ <EntrypointCard
+ @analysis={{this.graph}}
+ @baselineClosure={{b.base}}
+ @file={{b.file}}
+ @filter={{@filter}}
+ @loaded={{@loaded}}
+ @urls={{b.urls}}
+ />
+ {{/each}}
+ </div>
+ {{/if}}
+ </:body>
+ </Row>
+ </template>
+}
+
+export function pluginMatches(graph, plugin, filter) {
+ if (!filter) {
+ return true;
+ }
+ return (
+ matches(plugin.plugin, filter) ||
+ Object.keys(plugin.chunks).some((f) => graph.chunkMatches(f, filter)) ||
+ Object.values(plugin.routeBundles)
+ .flat()
+ .some((b) => matches(b.url, filter))
+ );
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/report.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/report.gjs
new file mode 100644
index 00000000000..8691c86ea81
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/report.gjs
@@ -0,0 +1,175 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { brotliLabel } from "../models/analysis.js";
+import AnalyzerToolbar from "./analyzer-toolbar.gjs";
+import EntrypointCard from "./entrypoint-card.gjs";
+import PluginCard, { pluginMatches } from "./plugin-card.gjs";
+
+const EMPTY = { files: 0, raw: 0, brotli: 0, brotliReady: true };
+
+function sum(a, b) {
+ return {
+ files: a.files + b.files,
+ raw: a.raw + b.raw,
+ brotli: a.brotli + b.brotli,
+ brotliReady: a.brotliReady && b.brotliReady,
+ };
+}
+
+// Core and the plugins in one list, though their sizes do not add up into a
+// single figure: they are separate builds.
+export default class Report extends Component {
+ @tracked query = "";
+ @tracked scope = "all";
+
+ // The input shows what was typed; matching reads the normalised form.
+ get filter() {
+ return this.query.trim().toLowerCase();
+ }
+
+ get core() {
+ return this.scope === "plugins" ? null : this.args.core;
+ }
+
+ get plugins() {
+ return this.scope === "core" ? null : this.args.plugins;
+ }
+
+ get shownTotals() {
+ return [this.core?.loadedTotals, this.plugins?.loadedTotals]
+ .filter(Boolean)
+ .reduce(sum, EMPTY);
+ }
+
+ get chunkCount() {
+ return (this.core?.chunkCount ?? 0) + (this.plugins?.chunkCount ?? 0);
+ }
+
+ // discourse.js is the baseline every other entrypoint measures against.
+ get baselineFile() {
+ const { entrypoints, chunks } = this.args.core;
+ return (
+ entrypoints.find((f) => chunks[f].name === "discourse") ?? entrypoints[0]
+ );
+ }
+
+ @cached
+ get baselineClosure() {
+ return this.args.core.staticClosure(this.baselineFile);
+ }
+
+ // Ordered by what each adds over the baseline; the badge says how it loads.
+ @cached
+ get visibleEntrypoints() {
+ if (!this.core) {
+ return [];
+ }
+ const base = this.baselineFile;
+ const others = this.#bySizeDescending(
+ [...this.core.entrypoints, ...this.core.dynamicEntrypoints]
+ .filter((f) => f !== base)
+ .filter((f) => this.#visible(f))
+ );
+ return (this.#visible(base) ? [base] : []).concat(others);
+ }
+
+ @cached
+ get visiblePlugins() {
+ if (!this.plugins) {
+ return [];
+ }
+ const shown = this.plugins.plugins.filter(
+ (p) =>
+ this.#hasContent(p) &&
+ pluginMatches(this.plugins.graphFor(p), p, this.filter)
+ );
+ const sizes = new Map(shown.map((p) => [p, this.plugins.totalsFor(p).raw]));
+ return shown.sort((a, b) => sizes.get(b) - sizes.get(a));
+ }
+
+ get empty() {
+ return !this.visibleEntrypoints.length && !this.visiblePlugins.length;
+ }
+
+ @action
+ updateFilter(event) {
+ this.query = event.target.value;
+ }
+
+ @action
+ setScope(scope) {
+ this.scope = scope;
+ }
+
+ // Sized once per file, not once per comparison.
+ #bySizeDescending(files) {
+ const sizes = new Map(files.map((f) => [f, this.#addedSize(f)]));
+ return files.sort((a, b) => sizes.get(b) - sizes.get(a));
+ }
+
+ #addedSize(file) {
+ const base = this.baselineClosure;
+ return [...this.core.visibleClosure(file)]
+ .filter((x) => !base.has(x))
+ .reduce((n, x) => n + this.core.sortSize(x), 0);
+ }
+
+ #visible(file) {
+ const base = file === this.baselineFile ? null : this.baselineClosure;
+ return this.core.cardVisible(file, this.filter, base);
+ }
+
+ #hasContent(plugin) {
+ return Object.keys(plugin.chunks).some((f) => this.plugins.includes(f));
+ }
+
+ <template>
+ <div class="bundle-analyzer">
+ <div class="ba-header">
+ <span class="ba-sub">
+ {{this.chunkCount}}
+ chunks ·
+ <span class="ba-loaded-dot">●</span>
+ {{this.shownTotals.files}}
+ loaded,
+ {{brotliLabel this.shownTotals}}
+ br
+ </span>
+ </div>
+
+ <AnalyzerToolbar
+ @filter={{this.query}}
+ @onFilter={{this.updateFilter}}
+ @onScope={{this.setScope}}
+ @placeholder="Filter chunks, modules or plugins…"
+ @scope={{this.scope}}
+ @view={{@view}}
+ />
+
+ <div>
+ {{#each this.visibleEntrypoints as |f|}}
+ <EntrypointCard
+ @analysis={{this.core}}
+ @baseline={{eq f this.baselineFile}}
+ @baselineClosure={{this.baselineClosure}}
+ @file={{f}}
+ @filter={{this.filter}}
+ @loaded={{this.core.loaded}}
+ />
+ {{/each}}
+ {{#each this.visiblePlugins as |p|}}
+ <PluginCard
+ @analysis={{this.plugins}}
+ @filter={{this.filter}}
+ @loaded={{this.plugins.loaded}}
+ @plugin={{p}}
+ />
+ {{/each}}
+ {{#if this.empty}}
+ <div class="ba-empty">No matches.</div>
+ {{/if}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/row.gjs b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/row.gjs
new file mode 100644
index 00000000000..058bb972258
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/components/row.gjs
@@ -0,0 +1,33 @@
+import { on } from "@ember/modifier";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+
+// The shell every row shares: a header that toggles, and a body that exists
+// only while the row is open.
+export default <template>
+ <div
+ class={{dConcatClass "ba-row" (if @expanded "open") (if @loaded "loaded")}}
+ >
+ <button
+ aria-expanded={{if @expanded "true" "false"}}
+ class="ba-head"
+ type="button"
+ {{on "click" @toggle}}
+ >
+ <span class="ba-name">
+ {{dIcon "caret-right" class="ba-tw"}}
+ {{#if @loaded}}
+ <span
+ class="ba-loaded-dot"
+ title="Loaded in this browser session"
+ >●</span>
+ {{/if}}
+ {{yield to="name"}}
+ </span>
+ {{yield to="numbers"}}
+ </button>
+ {{#if @expanded}}
+ <div class="ba-body">{{yield to="body"}}</div>
+ {{/if}}
+ </div>
+</template>
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/analysis.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/analysis.js
new file mode 100644
index 00000000000..b1ccdb0ab08
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/analysis.js
@@ -0,0 +1,175 @@
+import { trustHTML } from "@ember/template";
+import ChunkTotals from "./chunk-totals.js";
+
+export function fileName(file) {
+ return file.replace(/^assets\/js\//, "");
+}
+
+export function label(chunk) {
+ if (!chunk) {
+ return "";
+ }
+ return chunk.name && chunk.name !== ANONYMOUS
+ ? chunk.name
+ : fileName(chunk.file).replace(/\.digested\.js$/, "");
+}
+
+const ANONYMOUS = "chunk";
+
+export function routeName(chunk) {
+ const m = (chunk?.facadeModuleId || "").match(
+ /-embroider-route-entrypoint\.js:route=(.+)$/
+ );
+ return m ? m[1] : null;
+}
+
+export function fmt(n) {
+ if (n >= 1048576) {
+ return (n / 1048576).toFixed(2) + " MB";
+ }
+ if (n >= 1024) {
+ return (n / 1024).toFixed(1) + " KB";
+ }
+ return n + " B";
+}
+
+export function sizeOrDash(size) {
+ return size == null ? "—" : fmt(size);
+}
+
+// A set holding a chunk the build did not compress reads as a dash, rather than
+// a total counting that chunk as zero.
+export function brotliLabel(totals) {
+ return sizeOrDash(totals.brotliReady ? totals.brotli : null);
+}
+
+export function barWidth(length, max) {
+ return trustHTML(`width:${Math.max(2, (length / max) * 100)}%`);
+}
+
+export function matches(text, filter) {
+ return !filter || text.toLowerCase().includes(filter);
+}
+
+// Wraps the report JSON and answers the graph questions the UI asks of it.
+export default class Analysis extends ChunkTotals {
+ #closures = new Map();
+ #matchCache = new Map();
+ #matchFilter = null;
+ #visible = new Map();
+ #visibleKey = null;
+
+ constructor(data) {
+ super();
+ this.chunks = data.chunks;
+ this.entrypoints = data.entrypoints;
+ this.dynamicEntrypoints = data.dynamicEntrypoints;
+ this.usedByEntries = this.#computeUsedBy();
+ }
+
+ // Unfiltered, so baseline subtraction keeps its meaning when the view narrows.
+ // Memoised: every card sizes and sorts itself by walking one of these.
+ staticClosure(file) {
+ let closure = this.#closures.get(file);
+ if (!closure) {
+ closure = new Set();
+ this.#walk(file, closure);
+ this.#closures.set(file, closure);
+ }
+ return closure;
+ }
+
+ // Every card on screen asks about the chunks it shares with the others, so
+ // both answers are kept until the question changes.
+ chunkMatches(file, filter) {
+ if (!filter) {
+ return true;
+ }
+
+ if (this.#matchFilter !== filter) {
+ this.#matchFilter = filter;
+ this.#matchCache.clear();
+ }
+
+ if (!this.#matchCache.has(file)) {
+ const c = this.chunks[file];
+ this.#matchCache.set(
+ file,
+ !!c &&
+ (matches(file, filter) ||
+ matches(c.name, filter) ||
+ c.modules.some((m) => matches(m.id, filter)))
+ );
+ }
+
+ return this.#matchCache.get(file);
+ }
+
+ visibleClosure(file) {
+ if (!this.view?.onlyLoaded) {
+ return this.staticClosure(file);
+ }
+
+ // Keyed on how much the browser has loaded, which only ever grows, so a
+ // chunk arriving while the modal is open still reaches the rows.
+ const key = this.loaded?.files.size ?? 0;
+ if (this.#visibleKey !== key) {
+ this.#visibleKey = key;
+ this.#visible.clear();
+ }
+
+ if (!this.#visible.has(file)) {
+ this.#visible.set(
+ file,
+ new Set([...this.staticClosure(file)].filter((f) => this.includes(f)))
+ );
+ }
+
+ return this.#visible.get(file);
+ }
+
+ // Judged on what the card shows rather than its whole closure, which would
+ // keep a card alive on baseline chunks and then render it empty.
+ cardVisible(file, filter, base = null) {
+ const closure = this.visibleClosure(file);
+ const own = base ? [...closure].filter((f) => !base.has(f)) : [...closure];
+
+ if (own.length === 0) {
+ return false;
+ }
+ return !filter || own.some((f) => this.chunkMatches(f, filter));
+ }
+
+ sortSize(file) {
+ const c = this.chunks[file];
+ if (!c) {
+ return 0;
+ }
+ return this.brotliOf(file) ?? c.rawSize;
+ }
+
+ #walk(file, set) {
+ if (set.has(file) || !this.chunks[file]) {
+ return;
+ }
+ set.add(file);
+ for (const dep of this.chunks[file].imports) {
+ this.#walk(dep, set);
+ }
+ }
+
+ #computeUsedBy() {
+ const used = {};
+ for (const f of Object.keys(this.chunks)) {
+ used[f] = [];
+ }
+ for (const e of [...this.entrypoints, ...this.dynamicEntrypoints]) {
+ for (const f of this.staticClosure(e)) {
+ if (used[f] && !used[f].includes(e)) {
+ used[f].push(e);
+ }
+ }
+ }
+ return used;
+ }
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/chunk-totals.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/chunk-totals.js
new file mode 100644
index 00000000000..a112a21b692
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/chunk-totals.js
@@ -0,0 +1,49 @@
+import { cached } from "@glimmer/tracking";
+
+// Totals over a set of chunks, counting only what the view admits.
+export default class ChunkTotals {
+ loaded = null;
+ view = null;
+
+ @cached
+ get chunkCount() {
+ return Object.keys(this.chunks).filter((f) => this.includes(f)).length;
+ }
+
+ // Independent of the view: what this page cost, whatever the reader narrowed to.
+ @cached
+ get loadedTotals() {
+ return this.totals(
+ Object.keys(this.chunks).filter((f) => this.loaded?.has(f))
+ );
+ }
+
+ includes(file) {
+ return !this.view?.onlyLoaded || !!this.loaded?.has(file);
+ }
+
+ brotliOf(file) {
+ return this.chunks[file]?.brotliSize ?? undefined;
+ }
+
+ totals(files) {
+ let count = 0;
+ let raw = 0;
+ let brotli = 0;
+ let brotliReady = true;
+ for (const f of files) {
+ if (!this.includes(f)) {
+ continue;
+ }
+ count++;
+ raw += this.chunks[f].rawSize;
+ const b = this.brotliOf(f);
+ if (b == null) {
+ brotliReady = false;
+ } else {
+ brotli += b;
+ }
+ }
+ return { files: count, raw, brotli, brotliReady };
+ }
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/expansion.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/expansion.js
new file mode 100644
index 00000000000..90228ba418d
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/expansion.js
@@ -0,0 +1,29 @@
+import { tracked } from "@glimmer/tracking";
+
+// A row's open state: the default it is given, until a click overrides it. The
+// click is remembered against the filter it was made under, so a new search
+// starts from its own default.
+export default class Expansion {
+ @tracked choice = null;
+ @tracked choiceFilter = "";
+
+ toggle = () => {
+ this.choice = !this.expanded;
+ this.choiceFilter = this.#filter();
+ };
+ #defaultTo;
+
+ #filter;
+
+ constructor({ defaultTo, filter }) {
+ this.#defaultTo = defaultTo;
+ this.#filter = filter;
+ }
+
+ get expanded() {
+ if (this.choice !== null && this.choiceFilter === this.#filter()) {
+ return this.choice;
+ }
+ return this.#defaultTo();
+ }
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/loaded-chunks.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/loaded-chunks.js
new file mode 100644
index 00000000000..3dcf9e763ee
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/loaded-chunks.js
@@ -0,0 +1,49 @@
+import { tracked } from "@glimmer/tracking";
+
+// Which of the report's chunks this browser has fetched, kept live so one
+// loaded while the modal is open lights up too.
+export default class LoadedChunks {
+ @tracked files = new Set();
+
+ constructor(chunks) {
+ // Keyed by basename, which a content hash makes unique, so the host and path
+ // a chunk was fetched from do not matter.
+ this.byBasename = new Map();
+ for (const file of Object.keys(chunks)) {
+ this.byBasename.set(basename(file), file);
+ }
+
+ try {
+ this.observer = new PerformanceObserver((list) =>
+ this.#add(list.getEntries())
+ );
+ // Buffered, so this replays what the page already fetched.
+ this.observer.observe({ type: "resource", buffered: true });
+ } catch {
+ // PerformanceObserver unsupported; take the one reading available.
+ this.#add(performance.getEntriesByType("resource"));
+ }
+ }
+
+ has(file) {
+ return this.files.has(file);
+ }
+
+ teardown() {
+ this.observer?.disconnect();
+ }
+
+ #add(entries) {
+ const added = entries
+ .map((entry) => this.byBasename.get(basename(entry.name)))
+ .filter((file) => file && !this.files.has(file));
+
+ if (added.length) {
+ this.files = new Set([...this.files, ...added]);
+ }
+ }
+}
+
+function basename(url) {
+ return url.split("?")[0].split("/").pop();
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/plugins-analysis.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/plugins-analysis.js
new file mode 100644
index 00000000000..a4b509f8781
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/plugins-analysis.js
@@ -0,0 +1,55 @@
+import Analysis from "./analysis.js";
+import ChunkTotals from "./chunk-totals.js";
+
+// Wraps the merged plugin report. Each plugin is built on its own, so sizing is
+// per plugin, and one flat chunk map holds them all: a filename carries the
+// plugin's directory.
+export default class PluginsAnalysis extends ChunkTotals {
+ #graphs = new Map();
+
+ constructor(data) {
+ super();
+ this.plugins = data.plugins;
+ this.chunks = Object.fromEntries(
+ data.plugins.flatMap((p) => Object.entries(p.chunks))
+ );
+ }
+
+ // Shaped as an `Analysis` so a plugin's pane is built from the core cards.
+ graphFor(plugin) {
+ let graph = this.#graphs.get(plugin.plugin);
+
+ if (!graph) {
+ graph = new Analysis({
+ chunks: plugin.chunks,
+ entrypoints: Object.values(plugin.entrypoints),
+ dynamicEntrypoints: [...routeBundlesByFile(plugin).keys()],
+ });
+ graph.loaded = this.loaded;
+ graph.view = this.view;
+ this.#graphs.set(plugin.plugin, graph);
+ }
+
+ return graph;
+ }
+
+ totalsFor(plugin) {
+ return this.totals(Object.keys(plugin.chunks));
+ }
+}
+
+// A plugin usually points a group of urls at one bundle, so group them by it.
+export function routeBundlesByFile(plugin) {
+ const byFile = new Map();
+
+ for (const [entry, bundles] of Object.entries(plugin.routeBundles)) {
+ for (const { url, fileName } of bundles) {
+ if (!byFile.has(fileName)) {
+ byFile.set(fileName, { entry, urls: [] });
+ }
+ byFile.get(fileName).urls.push(url);
+ }
+ }
+
+ return byFile;
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/view-filter.js b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/view-filter.js
new file mode 100644
index 00000000000..ab0e7973c31
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/models/view-filter.js
@@ -0,0 +1,12 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+
+// Shared by every graph on screen, so one toggle governs every row and total.
+export default class ViewFilter {
+ @tracked onlyLoaded = true;
+
+ @action
+ toggle() {
+ this.onlyLoaded = !this.onlyLoaded;
+ }
+}
diff --git a/frontend/discourse/app/static/dev-tools/bundle-analyzer/styles.css b/frontend/discourse/app/static/dev-tools/bundle-analyzer/styles.css
new file mode 100644
index 00000000000..3302e246d82
--- /dev/null
+++ b/frontend/discourse/app/static/dev-tools/bundle-analyzer/styles.css
@@ -0,0 +1,218 @@
+/* Held at the height it is allowed anyway, so expanding a card scrolls the body
+ rather than resizing the modal. 80vh is what `--modal-max-height` defaults to. */
+.bundle-analyzer-modal {
+ --modal-min-height: 80vh;
+}
+.bundle-analyzer-modal .d-modal__container {
+ width: min(1200px, 92vw);
+ max-width: 92vw;
+}
+/* Hard to miss on purpose: it is all that stands between a reader and numbers
+ that look authoritative and are not. */
+.bundle-analyzer-modal .ba-warning {
+ padding: 2rem 1.5rem;
+ text-align: center;
+}
+.bundle-analyzer-modal .ba-warning h2 {
+ margin: 0 0 0.5em;
+}
+.bundle-analyzer-modal .ba-warning p {
+ max-width: 34em;
+ margin: 0 auto 1.5em;
+ color: var(--primary-high);
+}
+
+.bundle-analyzer {
+ --ba-bg: var(--secondary);
+ --ba-panel: var(--primary-very-low);
+ --ba-panel2: var(--primary-low);
+ --ba-border: var(--primary-low);
+ --ba-text: var(--primary);
+ --ba-muted: var(--primary-medium);
+ --ba-accent: var(--tertiary);
+ --ba-good: var(--success);
+ --ba-bar: var(--primary-low);
+
+ background: var(--ba-bg);
+ color: var(--ba-text);
+ font-size: 0.8125em;
+ line-height: 1.5;
+}
+
+.bundle-analyzer * {
+ box-sizing: border-box;
+}
+.bundle-analyzer code {
+ color: var(--ba-good);
+}
+.bundle-analyzer .ba-header {
+ margin-bottom: 16px;
+}
+.bundle-analyzer .ba-sub {
+ color: var(--ba-muted);
+ font-size: 12px;
+}
+.bundle-analyzer .ba-hint {
+ color: var(--ba-muted);
+ font-size: 12px;
+ margin: 10px 0 12px;
+}
+
+.bundle-analyzer .ba-note {
+ color: var(--ba-muted);
+ font-size: 11px;
+ margin: 2px 0 6px;
+}
+
+/* The filter takes the slack so the scope and the switch sit at the right edge,
+ and the select is full width by default, which in a flex row is all of it. */
+.bundle-analyzer .ba-toolbar .filter-input-container {
+ flex: 1;
+}
+.bundle-analyzer .ba-toolbar .d-native-select {
+ width: auto;
+}
+.bundle-analyzer .ba-toolbar {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ margin-bottom: 12px;
+ flex-wrap: wrap;
+}
+.bundle-analyzer .ba-row {
+ border: 1px solid var(--ba-border);
+ border-radius: 8px;
+ margin-bottom: 6px;
+ background: var(--ba-panel);
+ overflow: hidden;
+}
+.bundle-analyzer .ba-row > .ba-head {
+ appearance: none;
+ border: 0;
+ margin: 0;
+ width: 100%;
+ text-align: left;
+ font: inherit;
+ color: inherit;
+ background: var(--ba-panel);
+ display: grid;
+ grid-template-columns: 1fr 130px 130px;
+ gap: 8px;
+ align-items: center;
+ padding: 9px 12px;
+ cursor: pointer;
+}
+.bundle-analyzer .ba-row > .ba-head:hover {
+ background: var(--ba-panel2);
+}
+.bundle-analyzer .ba-name {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+.bundle-analyzer .ba-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.bundle-analyzer .ba-label.root {
+ color: var(--ba-muted);
+ font-style: italic;
+}
+.bundle-analyzer .ba-tw {
+ color: var(--ba-muted);
+ width: 12px;
+ display: inline-block;
+ transition: transform 0.1s;
+ flex: none;
+}
+.bundle-analyzer .ba-row.open > .ba-head .ba-tw {
+ transform: rotate(90deg);
+}
+.bundle-analyzer .ba-num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+.bundle-analyzer .ba-num.muted {
+ color: var(--ba-muted);
+}
+.bundle-analyzer .ba-body {
+ padding: 0 12px 12px 32px;
+}
+
+.bundle-analyzer .ba-badge {
+ font-size: 10px;
+ padding: 1px 6px;
+ border-radius: 4px;
+ background: var(--ba-bar);
+ color: var(--ba-text);
+ flex: none;
+}
+.bundle-analyzer .ba-badge.add {
+ background: var(--highlight-low);
+ color: var(--primary);
+}
+.bundle-analyzer .ba-badge.route {
+ background: var(--success-low);
+ color: var(--success);
+}
+
+.bundle-analyzer .ba-bar {
+ height: 4px;
+ background: var(--ba-bar);
+ border-radius: 2px;
+ margin-top: 4px;
+}
+.bundle-analyzer .ba-bar > span {
+ display: block;
+ height: 100%;
+ background: var(--ba-accent);
+ border-radius: 2px;
+}
+.bundle-analyzer .ba-mod {
+ display: grid;
+ grid-template-columns: 1fr 90px;
+ gap: 8px;
+ padding: 3px 0;
+ border-bottom: 1px solid var(--ba-border);
+ color: var(--ba-muted);
+}
+.bundle-analyzer .ba-mname {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--ba-text);
+}
+.bundle-analyzer .ba-sites {
+ margin: 4px 0 10px;
+}
+.bundle-analyzer .ba-site {
+ color: var(--ba-muted);
+ padding: 2px 0;
+}
+.bundle-analyzer .ba-sub-list {
+ margin-top: 8px;
+}
+.bundle-analyzer .ba-pill,
+.bundle-analyzer .pill {
+ font-size: 11px;
+ color: var(--ba-muted);
+}
+.bundle-analyzer .ba-empty {
+ color: var(--ba-muted);
+ padding: 12px;
+}
+
+.bundle-analyzer .ba-loaded-dot {
+ color: var(--ba-good);
+ font-size: 9px;
+ line-height: 1;
+ flex: none;
+}
+.bundle-analyzer .ba-row.loaded {
+ border-color: color-mix(in srgb, var(--ba-good) 45%, var(--ba-border));
+}
+.bundle-analyzer .ba-row.loaded > .ba-head {
+ box-shadow: inset 3px 0 0 var(--ba-good);
+}
diff --git a/frontend/discourse/app/static/dev-tools/tools.ts b/frontend/discourse/app/static/dev-tools/tools.ts
index b00a3c18a4d..400fec11919 100644
--- a/frontend/discourse/app/static/dev-tools/tools.ts
+++ b/frontend/discourse/app/static/dev-tools/tools.ts
@@ -1,5 +1,6 @@
import type { ComponentLike } from "@glint/template";
import BlockDebugButton from "./block-debug/button.gts";
+import BundleAnalyzerButton from "./bundle-analyzer/button.gjs";
import PluginOutletDebugButton from "./plugin-outlet-debug/button.gjs";
import SafeModeButton from "./safe-mode/button.gjs";
import StyleguideButton from "./styleguide/button.gts";
@@ -25,4 +26,5 @@ export const CORE_TOOLS: readonly DevTool[] = [
{ id: "safe-mode", component: SafeModeButton },
{ id: "verbose-localization", component: VerboseLocalizationButton },
{ id: "styleguide", component: StyleguideButton },
+ { id: "bundle-analyzer", component: BundleAnalyzerButton },
];
diff --git a/frontend/discourse/lib/brotli-assets-plugin.mjs b/frontend/discourse/lib/brotli-assets-plugin.mjs
new file mode 100644
index 00000000000..f3615cd6a58
--- /dev/null
+++ b/frontend/discourse/lib/brotli-assets-plugin.mjs
@@ -0,0 +1,39 @@
+import { createHash } from "crypto";
+import brotli from "./brotli.mjs";
+
+// Ships a `.br` beside every chunk for nginx to serve under `brotli_static`.
+export default function brotliAssetsPlugin({ enabled } = {}) {
+ let compressed = new Map();
+
+ return {
+ name: "brotli-assets",
+
+ async generateBundle(_outputOptions, bundle) {
+ if (!enabled) {
+ return;
+ }
+
+ const stillHere = new Map();
+
+ await Promise.all(
+ Object.entries(bundle)
+ .filter(([, item]) => item.type === "chunk")
+ .map(async ([fileName, chunk]) => {
+ const source = Buffer.from(chunk.code, "utf8");
+ const key = createHash("sha256").update(source).digest("hex");
+ const br = compressed.get(key) ?? (await brotli(source));
+
+ stillHere.set(key, br);
+ this.emitFile({
+ type: "asset",
+ fileName: `${fileName}.br`,
+ source: br,
+ });
+ })
+ );
+
+ // This build's chunks only, so the map does not grow with every edit.
+ compressed = stillHere;
+ },
+ };
+}
diff --git a/frontend/discourse/lib/brotli.mjs b/frontend/discourse/lib/brotli.mjs
new file mode 100644
index 00000000000..5115fd64553
--- /dev/null
+++ b/frontend/discourse/lib/brotli.mjs
@@ -0,0 +1,13 @@
+import { promisify } from "util";
+import * as zlib from "zlib";
+
+const compress = promisify(zlib.brotliCompress);
+
+export default function brotli(source) {
+ return compress(source, {
+ params: {
+ [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: source.length,
+ },
+ });
+}
diff --git a/frontend/discourse/lib/bundle-analyzer-plugin.mjs b/frontend/discourse/lib/bundle-analyzer-plugin.mjs
new file mode 100644
index 00000000000..a93c72a7fbe
--- /dev/null
+++ b/frontend/discourse/lib/bundle-analyzer-plugin.mjs
@@ -0,0 +1,143 @@
+import { createHash } from "crypto";
+import * as fs from "fs";
+import { relative } from "path";
+import brotli from "./brotli.mjs";
+
+const BUNDLE_ANALYSIS_RE = /^bundle-analysis-\w+\.digested\.json(\.br)?$/;
+
+// rolldown's `chunk.name` keeps the original seed-module name even when
+// chunkFileNames renames the file.
+const FILE_NAME_RE = /(?:.*\/)?(.+)-[a-z0-9]+\.digested\.js$/;
+function nameFromFile(fileName) {
+ const m = fileName.match(FILE_NAME_RE);
+ return m ? m[1] : fileName;
+}
+
+const relCache = new Map();
+
+// A dependency reads better as its package-relative path than as a pnpm store
+// path; everything else is relative to the build cwd. Memoised: a module id
+// repeats across chunks.
+function rel(id) {
+ if (!id) {
+ return null;
+ }
+
+ if (!relCache.has(id)) {
+ const nodeModules = id.lastIndexOf("node_modules/");
+ relCache.set(
+ id,
+ nodeModules >= 0 ? id.slice(nodeModules) : relative(process.cwd(), id)
+ );
+ }
+
+ return relCache.get(id);
+}
+
+// Describes the finished bundle: what each chunk weighs, what is inside it, and
+// which files dynamically import it. Written from `writeBundle`, where the
+// chunks a browser will fetch are already on disk to be measured; Rails finds
+// the report by globbing for its name.
+export default function bundleAnalyzerPlugin({ compress } = {}) {
+ return {
+ name: "bundle-analyzer",
+
+ async writeBundle(options, bundle) {
+ const chunks = {};
+ const entrypoints = [];
+ const dynamicEntrypoints = [];
+
+ const chunkList = Object.entries(bundle).filter(
+ ([, chunk]) => chunk.type === "chunk"
+ );
+
+ // `isDynamicEntry` is set only while a dynamically-imported module has a
+ // chunk to itself, so the import edges are the authority instead.
+ const dynamicTargets = new Set(
+ chunkList.flatMap(([, chunk]) => chunk.dynamicImports)
+ );
+
+ for (const [fileName, chunk] of chunkList) {
+ const rawSize = Buffer.byteLength(chunk.code, "utf8");
+ const compressed = compressedSize(`${options.dir}/${fileName}.br`);
+
+ const modules = Object.entries(chunk.modules)
+ .map(([moduleId, m]) => ({
+ id: rel(moduleId),
+ renderedLength: m.renderedLength,
+ }))
+ .sort((a, b) => b.renderedLength - a.renderedLength);
+
+ // Per module rather than of the facade, so a chunk that several dynamic
+ // entries were merged into still names what pulls it in.
+ const importers = new Set();
+ for (const moduleId of Object.keys(chunk.modules)) {
+ for (const imp of this.getModuleInfo(moduleId)?.dynamicImporters ??
+ []) {
+ importers.add(rel(imp));
+ }
+ }
+
+ const importSites = [...importers];
+
+ chunks[fileName] = {
+ file: fileName,
+ name: nameFromFile(fileName),
+ facadeModuleId: rel(chunk.facadeModuleId),
+ isEntry: chunk.isEntry,
+ isDynamicEntry: chunk.isDynamicEntry,
+ rawSize,
+ brotliSize: compressed,
+ imports: chunk.imports,
+ modules,
+ importSites,
+ };
+
+ if (chunk.isEntry) {
+ entrypoints.push(fileName);
+ } else if (chunk.isDynamicEntry || dynamicTargets.has(fileName)) {
+ dynamicEntrypoints.push(fileName);
+ }
+ }
+
+ const data = {
+ emberEnv: process.env.EMBER_ENV || "development",
+ entrypoints,
+ dynamicEntrypoints,
+ chunks,
+ };
+
+ const json = JSON.stringify(data);
+
+ // `.digested.` promises propshaft the name is a fingerprint, and the report
+ // can only be digested once every chunk in it has been.
+ const digest = createHash("sha256")
+ .update(json)
+ .digest("hex")
+ .slice(0, 12);
+ const fileName = `bundle-analysis-${digest}.digested.json`;
+ const dir = `${options.dir}/assets/js`;
+
+ fs.writeFileSync(`${dir}/${fileName}`, json);
+
+ if (compress) {
+ fs.writeFileSync(
+ `${dir}/${fileName}.br`,
+ await brotli(Buffer.from(json, "utf8"))
+ );
+ }
+
+ // A watching build never clears its output directory, and each report is
+ // the size of the bundle it describes.
+ for (const entry of fs.readdirSync(dir)) {
+ if (BUNDLE_ANALYSIS_RE.test(entry) && !entry.startsWith(fileName)) {
+ fs.rmSync(`${dir}/${entry}`);
+ }
+ }
+ },
+ };
+}
+
+function compressedSize(path) {
+ return fs.existsSync(path) ? fs.statSync(path).size : null;
+}
diff --git a/frontend/discourse/lib/discourse-chunk-names.mjs b/frontend/discourse/lib/discourse-chunk-names.mjs
index d76de854383..d46a4d5ef95 100644
--- a/frontend/discourse/lib/discourse-chunk-names.mjs
+++ b/frontend/discourse/lib/discourse-chunk-names.mjs
@@ -55,12 +55,8 @@ export default function discourseChunkNamesPlugin() {
return {
...options,
chunkFileNames: (chunk) => {
- if (!chunk.isDynamicEntry) {
- return original.replaceAll("[name]", "chunk");
- }
-
if (!chunk.facadeModuleId) {
- return original;
+ return original.replaceAll("[name]", "chunk");
}
const name =
diff --git a/frontend/discourse/rolldown.config.mjs b/frontend/discourse/rolldown.config.mjs
index e733af719b1..65b45a1d0fa 100644
--- a/frontend/discourse/rolldown.config.mjs
+++ b/frontend/discourse/rolldown.config.mjs
@@ -1,6 +1,8 @@
import * as fs from "fs";
import { basename, relative } from "path";
import { viteAliasPlugin, viteImportGlobPlugin } from "rolldown/experimental";
+import brotliAssetsPlugin from "./lib/brotli-assets-plugin.mjs";
+import bundleAnalyzerPlugin from "./lib/bundle-analyzer-plugin.mjs";
import chunkImportMapPlugin from "./lib/chunk-import-map-plugin.mjs";
import discourseChunkNamesPlugin from "./lib/discourse-chunk-names.mjs";
import discourseSourceImports from "./lib/discourse-source-imports.mjs";
@@ -207,6 +209,8 @@ export function buildConfig({ devMode } = {}) {
}
},
},
+ brotliAssetsPlugin({ enabled: isProduction }),
+ bundleAnalyzerPlugin({ compress: isProduction }),
{
name: "bundle-manifest",
generateBundle(_outputOptions, bundle) {
diff --git a/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs b/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs
index 28c16a2ae81..abf01a2037d 100644
--- a/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs
+++ b/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs
@@ -21,6 +21,7 @@ const EXPECTED_ORDER = [
"safe-mode",
"verbose-localization",
"styleguide",
+ "bundle-analyzer",
"disable-dev-tools",
];
@@ -32,6 +33,7 @@ const SELECTORS = {
"safe-mode": ".toggle-safe-mode",
"verbose-localization": ".toggle-verbose-localization",
styleguide: ".open-styleguide",
+ "bundle-analyzer": ".bundle-analyzer-button",
"disable-dev-tools": ".disable-dev-tools",
};
diff --git a/lib/asset_processor.rb b/lib/asset_processor.rb
index c15dc35dcdf..9668400a0f9 100644
--- a/lib/asset_processor.rb
+++ b/lib/asset_processor.rb
@@ -3,7 +3,7 @@
class AssetProcessor
# Bump only when theme JS output changes; it rebakes every theme on every site. Plugin builds
# also key on the processor's digest, so JS changes there rebuild them without a bump.
- BASE_COMPILER_VERSION = 120
+ BASE_COMPILER_VERSION = 121
BUNDLE =
PrecompiledBundle.new(
diff --git a/lib/ember_assets.rb b/lib/ember_assets.rb
index 5070def6964..fecbfce72d8 100644
--- a/lib/ember_assets.rb
+++ b/lib/ember_assets.rb
@@ -154,6 +154,13 @@ class EmberAssets < ActiveSupport::CurrentAttributes
{ "message" => text, "messageHtml" => ERB::Util.html_escape(text) }
end
+ def self.bundle_analysis_asset
+ cache[:bundle_analysis] ||= Dir.glob(
+ "js/bundle-analysis-*.digested.json",
+ base: "#{dist_dir}/assets",
+ ).first
+ end
+
def self.is_ember_asset?(name)
assets.include?(name) || script_chunks.values.flatten.include?(name.delete_suffix(".js"))
end
diff --git a/lib/plugin/js_compiler.rb b/lib/plugin/js_compiler.rb
index 07464899f21..dd9d0683325 100644
--- a/lib/plugin/js_compiler.rb
+++ b/lib/plugin/js_compiler.rb
@@ -39,6 +39,7 @@ class Plugin::JsCompiler
"#{@filename_prefix}main#{@filename_suffix}.js" => {
"name" => "main",
"imports" => [],
+ "modules" => [],
"isEntry" => true,
"code" => "throw new Error(#{message.to_json});\n",
"map" => nil,
diff --git a/lib/plugin/js_manager.rb b/lib/plugin/js_manager.rb
index 03ffac923b1..ee8b078bf97 100644
--- a/lib/plugin/js_manager.rb
+++ b/lib/plugin/js_manager.rb
@@ -15,6 +15,9 @@ module Plugin
"admin-route-map.js" => "frontend/discourse/admin/routes/admin-route-map.js",
}.freeze
+ # Each plugin compiles on its own, so its report is written beside its
+ # manifest and the copies are merged into one asset the analyzer reads.
+
def self.optional_plugin_stub
"data:text/javascript,/* autogenerated missing optional plugin stub */const m=new Proxy({},{get:()=>null});export default new Proxy({},{get:()=>m});"
end
@@ -55,6 +58,22 @@ module Plugin
end
end
+ # Logical path of each plugin's bundle analysis report, for the dev tool.
+ def self.bundle_analysis_assets
+ get_set_cache("bundle_analysis_assets") do
+ Discourse
+ .plugins
+ .filter_map do |plugin|
+ file =
+ Dir.glob(
+ "#{Rails.root.join("app/assets/generated/#{plugin.directory_name}/js/plugins", "*bundle-analysis*.json")}",
+ ).first
+ [plugin.directory_name, logical_path(File.basename(file))] if file
+ end
+ .to_h
+ end
+ end
+
def self.logical_path(file_name)
"js/plugins/#{file_name.delete_suffix(".js")}"
end
@@ -133,7 +152,7 @@ module Plugin
map_dir = "#{base_output_dir}/map/plugins"
entrypoints = { "main" => "assets/javascripts", "admin" => "admin/assets/javascripts" }
- entrypoints["test"] = "test/javascripts" if Rails.env.local?
+ entrypoints["test"] = "test/javascripts" if Rails.env.local? && !production_build?
tree = {}
entrypoints_config = {}
@@ -167,6 +186,8 @@ module Plugin
end
end
+ return if entrypoints_config.empty?
+
frontend_config = plugin.about_json_metadata&.dig("frontend")
# Only a plugin that splits its own routes derives anything from these. Read from source, so
@@ -186,7 +207,7 @@ module Plugin
AssetProcessor::BASE_COMPILER_VERSION,
AssetProcessor.digest,
AssetProcessor.ember_version,
- minify?.to_s,
+ production_build?.to_s,
plugin.name,
frontend_config.to_json,
].join,
@@ -210,7 +231,7 @@ module Plugin
compiler =
Plugin::JsCompiler.new(
plugin.name,
- minify: minify?,
+ minify: production_build?,
tree: tree,
entrypoints: entrypoints_config,
filename_prefix:,
@@ -223,13 +244,25 @@ module Plugin
FileUtils.mkdir_p(map_dir)
manifest = {}
+ analysis_chunks = {}
result.each do |file_name, info|
code = info["code"]
code += "\n//# sourceMappingURL=../../map/plugins/#{file_name}.map\n" if info["map"]
- File.write("#{js_dir}/#{file_name}", code)
+ js_path = "#{js_dir}/#{file_name}"
+ File.write(js_path, code)
File.write("#{map_dir}/#{file_name}.map", info["map"]) if info["map"]
+ analysis_chunks[file_name] = {
+ file: file_name,
+ name: info["name"],
+ isEntry: info["isEntry"],
+ rawSize: code.bytesize,
+ brotliSize: (compress_to_brotli(js_path) if production_build?),
+ imports: info["imports"],
+ modules: info["modules"],
+ }
+
if info["isEntry"]
manifest[info["name"]] = {
fileName: file_name,
@@ -241,6 +274,18 @@ module Plugin
end
File.write("#{base_output_dir}/manifest.json", JSON.pretty_generate(manifest))
+
+ analysis_path = "#{js_dir}/#{filename_prefix}bundle-analysis#{filename_suffix}.json"
+ File.write(
+ analysis_path,
+ JSON.generate(
+ plugin: plugin.directory_name,
+ entrypoints: manifest.transform_values { it[:fileName] },
+ routeBundles: manifest.transform_values { it[:routeBundles] || [] },
+ chunks: analysis_chunks,
+ ),
+ )
+ compress_to_brotli(analysis_path) if production_build?
end
# Delete any old versions
@@ -289,8 +334,17 @@ module Plugin
private
- def minify?
- Rails.env.production?
+ def production_build?
+ Rails.env.production? || ENV["EMBER_ENV"] == "production"
+ end
+
+ def compress_to_brotli(path)
+ system("brotli", "-f", "--quality=11", "-o", "#{path}.br.tmp", path, exception: true)
+ File.rename("#{path}.br.tmp", "#{path}.br")
+ File.size("#{path}.br")
+ rescue Errno::ENOENT
+ log "brotli is not installed, so #{File.basename(path)} has no compressed size"
+ nil
end
def cache?
diff --git a/plugins/chat/spec/system/bundle_analyzer_spec.rb b/plugins/chat/spec/system/bundle_analyzer_spec.rb
new file mode 100644
index 00000000000..956efbe6968
--- /dev/null
+++ b/plugins/chat/spec/system/bundle_analyzer_spec.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+describe "Chat | bundle analyzer" do
+ let(:toolbar) { PageObjects::Components::DevTools::Toolbar.new }
+ let(:analyzer) { PageObjects::Components::DevTools::BundleAnalyzer.new }
+
+ def open_analyzer
+ visit("/latest")
+ toolbar.enable
+ toolbar.open_bundle_analyzer
+ analyzer.dismiss_development_warning
+ analyzer.select_scope("plugins")
+ end
+
+ it "reports what chat's own build produced" do
+ open_analyzer
+
+ expect(analyzer).to have_card("chat")
+ end
+
+ it "leaves out a plugin the site has disabled" do
+ SiteSetting.chat_enabled = false
+
+ open_analyzer
+
+ expect(analyzer).to have_no_card("chat")
+ end
+end
diff --git a/script/assemble_ember_build.rb b/script/assemble_ember_build.rb
index dc57b89e55b..8561eec001e 100755
--- a/script/assemble_ember_build.rb
+++ b/script/assemble_ember_build.rb
@@ -165,7 +165,8 @@ if ARGV.include?("--compress")
next if File.exist?("#{file}.br")
start = Time.now
- system("brotli", "-f", "--quality=11", "-o", "#{file}.br", file, exception: true)
+ system("brotli", "-f", "--quality=11", "-o", "#{file}.br.tmp", file, exception: true)
+ File.rename("#{file}.br.tmp", "#{file}.br")
puts "Compressed #{file} in #{(Time.now - start).round(2)}s"
end
end
diff --git a/spec/lib/plugin/js_manager_spec.rb b/spec/lib/plugin/js_manager_spec.rb
index ddb726fcdb8..360279c8a73 100644
--- a/spec/lib/plugin/js_manager_spec.rb
+++ b/spec/lib/plugin/js_manager_spec.rb
@@ -1,6 +1,31 @@
# frozen_string_literal: true
RSpec.describe Plugin::JsManager do
+ describe ".bundle_analysis_assets" do
+ let(:directory_name) { "js-manager-spec-plugin" }
+ let(:generated) { Rails.root.join("app/assets/generated/#{directory_name}/js/plugins") }
+
+ before do
+ described_class.instance_variable_set(:@production_cache, nil)
+ allow(Discourse).to receive(:plugins).and_return([stub(directory_name:)])
+ end
+
+ after { FileUtils.rm_rf(generated.dirname.dirname) }
+
+ it "is keyed by the directory name of the plugin the report came from" do
+ FileUtils.mkdir_p(generated)
+ FileUtils.touch(generated.join("#{directory_name}_bundle-analysis-abc123.digested.json"))
+
+ expect(described_class.bundle_analysis_assets).to eq(
+ directory_name => "js/plugins/#{directory_name}_bundle-analysis-abc123.digested.json",
+ )
+ end
+
+ it "leaves out a plugin that has not written one" do
+ expect(described_class.bundle_analysis_assets).to eq({})
+ end
+ end
+
describe ".route_bundle_for_path" do
let(:manifest) do
{
diff --git a/spec/system/bundle_analyzer_spec.rb b/spec/system/bundle_analyzer_spec.rb
new file mode 100644
index 00000000000..721a2f94fbf
--- /dev/null
+++ b/spec/system/bundle_analyzer_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+describe "Bundle analyzer" do
+ let(:toolbar) { PageObjects::Components::DevTools::Toolbar.new }
+ let(:analyzer) { PageObjects::Components::DevTools::BundleAnalyzer.new }
+
+ before do
+ visit("/latest")
+ toolbar.enable
+ toolbar.open_bundle_analyzer
+ end
+
+ it "warns that a development build's sizes are not what anyone downloads" do
+ expect(analyzer).to have_development_warning
+ expect(analyzer).to have_no_report
+
+ analyzer.dismiss_development_warning
+
+ expect(analyzer).to have_no_development_warning
+ expect(analyzer).to have_report
+
+ # Only a production build compresses, so there is nothing to report here.
+ expect(analyzer).to have_unmeasured_sizes
+ end
+
+ it "lists what the page loaded, and narrows to a filter" do
+ analyzer.dismiss_development_warning
+
+ expect(analyzer).to have_card("discourse")
+
+ analyzer.filter("No Such Module Anywhere")
+
+ expect(analyzer).to have_no_card("discourse")
+ expect(analyzer.filter_text).to eq("No Such Module Anywhere")
+ end
+
+ it "opens a card on click, and closes it again" do
+ analyzer.dismiss_development_warning
+
+ expect(analyzer).to have_no_expanded_card("discourse")
+
+ analyzer.toggle_card("discourse")
+
+ expect(analyzer).to have_expanded_card("discourse")
+
+ analyzer.toggle_card("discourse")
+
+ expect(analyzer).to have_no_expanded_card("discourse")
+ end
+
+ it "shows plugins and core separately" do
+ analyzer.dismiss_development_warning
+ analyzer.select_scope("plugins")
+
+ expect(analyzer).to have_no_card("discourse")
+
+ analyzer.select_scope("core")
+
+ expect(analyzer).to have_card("discourse")
+ end
+end
diff --git a/spec/system/page_objects/components/dev_tools/bundle_analyzer.rb b/spec/system/page_objects/components/dev_tools/bundle_analyzer.rb
new file mode 100644
index 00000000000..23e800e9af4
--- /dev/null
+++ b/spec/system/page_objects/components/dev_tools/bundle_analyzer.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ module DevTools
+ class BundleAnalyzer < PageObjects::Components::Base
+ MODAL = ".bundle-analyzer-modal"
+
+ # The warning renders with the modal, so a production build — which has
+ # nothing to warn about — is known immediately rather than waited for.
+ def dismiss_development_warning
+ if page.has_css?("#{MODAL} .ba-warning", wait: 0)
+ find("#{MODAL} .ba-warning .btn-primary").click
+ end
+ self
+ end
+
+ def filter(text)
+ find("#{MODAL} .filter-input").fill_in(with: text)
+ self
+ end
+
+ def filter_text
+ find("#{MODAL} .filter-input").value
+ end
+
+ def select_scope(value)
+ PageObjects::Components::DNativeSelect.new("#{MODAL} .d-native-select").select(value)
+ self
+ end
+
+ def has_development_warning?
+ page.has_css?("#{MODAL} .ba-warning")
+ end
+
+ def has_no_development_warning?
+ page.has_no_css?("#{MODAL} .ba-warning")
+ end
+
+ def has_report?
+ page.has_css?("#{MODAL} .bundle-analyzer")
+ end
+
+ def has_no_report?
+ page.has_no_css?("#{MODAL} .bundle-analyzer")
+ end
+
+ def toggle_card(name)
+ find("#{MODAL} .ba-row .ba-label", exact_text: name).click
+ self
+ end
+
+ def has_expanded_card?(name)
+ page.has_css?("#{MODAL} .ba-row.open > .ba-head .ba-label", exact_text: name)
+ end
+
+ def has_no_expanded_card?(name)
+ page.has_no_css?("#{MODAL} .ba-row.open > .ba-head .ba-label", exact_text: name)
+ end
+
+ def has_card?(name)
+ page.has_css?("#{MODAL} .ba-row .ba-label", exact_text: name)
+ end
+
+ def has_no_card?(name)
+ page.has_no_css?("#{MODAL} .ba-row .ba-label", exact_text: name)
+ end
+
+ # A build that did not compress shows a dash where each size would be.
+ def has_unmeasured_sizes?
+ page.has_css?("#{MODAL} .ba-num b", text: "—")
+ end
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/dev_tools/toolbar.rb b/spec/system/page_objects/components/dev_tools/toolbar.rb
index a99b8a17462..f8b9802c7a0 100644
--- a/spec/system/page_objects/components/dev_tools/toolbar.rb
+++ b/spec/system/page_objects/components/dev_tools/toolbar.rb
@@ -83,6 +83,11 @@ module PageObjects
self
end
+ def open_bundle_analyzer
+ find(".dev-tools-toolbar .bundle-analyzer-button").click
+ self
+ end
+
def has_toolbar?
page.has_css?(".dev-tools-toolbar")
end