A platform for community discussion. Free, open, simple.
FIX: Deprecation warning banners for boot-time deprecations (#42346)
David Taylore4507ffb27c0
diff --git a/frontend/discourse/app/lib/deprecated.js b/frontend/discourse/app/lib/deprecated.jsindex 087a623d906..67f7dc5714a 100644--- a/frontend/discourse/app/lib/deprecated.js+++ b/frontend/discourse/app/lib/deprecated.js@@ -1,11 +1,24 @@import { registerDeprecationHandler as emberRegisterDeprecationHandler } from "@ember/debug";import DeprecationWorkflow from "../deprecation-workflow";import { isRailsTesting } from "./environment";-import { consolePrefix } from "./source-identifier";+import identifySource, { consolePrefix } from "./source-identifier";const handlers = [];+// Universal handlers also receive Ember's own deprecations (via the bridge below).+const universalHandlers = [];const disabledDeprecations = [];+// Recent deprecations, replayed to universal handlers registered `{ buffered: true }`.+const universalBacklog = [];+const MAX_BACKLOG_LENGTH = 1000;++// Route Ember's own deprecations through the same pipeline, early enough to catch+// ones fired during boot.+emberRegisterDeprecationHandler((message, options, next) => {+ dispatchDeprecation(message, options, true);+ return next(message, options);+});+let emberDeprecationSilencer;/**@@ -43,8 +56,7 @@ export default function deprecated(msg, options = {}) {const formattedMessage = buildDeprecationMessage(msg, options, raiseError);const resolvedConsolePrefix = getConsolePrefix(source);- // Execute all registered deprecation handlers- handlers.forEach((h) => h(formattedMessage, options));+ dispatchDeprecation(formattedMessage, options, false);if (!DeprecationWorkflow.shouldSilence(id)) {if (raiseError) {@@ -54,14 +66,79 @@ export default function deprecated(msg, options = {}) {console.warn(...[resolvedConsolePrefix, formattedMessage].filter(Boolean)); //eslint-disable-line no-console}}++function dispatchDeprecation(message, options, fromEmber) {+ if (!fromEmber) {+ for (const callback of handlers) {+ callback(message, options);+ }+ }++ for (const callback of universalHandlers) {+ callback(message, options);+ }++ if (!DeprecationWorkflow.shouldSilence(options?.id)) {+ addToBacklog(message, options);+ }+}++function addToBacklog(message, options) {+ if (universalBacklog.length >= MAX_BACKLOG_LENGTH) {+ universalBacklog.shift();+ }++ // Resolve source now; identifySource() reads the live call stack.+ universalBacklog.push([+ message,+ { ...options, source: options.source || identifySource() },+ ]);+}/**- * Register a function which will be called whenever a deprecation is triggered- * @param {function} callback The callback function. Arguments will match those of `deprecated()`.+ * Register a callback invoked for each Discourse `deprecated()` call. To also+ * receive Ember's own deprecations, or replay ones fired before registering, use+ * `registerUniversalDeprecationHandler`.*/export function registerDeprecationHandler(callback) {handlers.push(callback);}+/**+ * Like `registerDeprecationHandler`, but also receives Ember's own deprecations.+ * With `{ buffered: true }` the callback is first replayed the backlog of+ * deprecations that fired before it registered.+ */+export function registerUniversalDeprecationHandler(+ callback,+ { buffered = false } = {}+) {+ universalHandlers.push(callback);++ if (buffered) {+ for (const [message, options] of universalBacklog) {+ callback(message, options);+ }+ }+}++/**+ * Unregister a callback previously passed to `registerUniversalDeprecationHandler`.+ */+export function unregisterUniversalDeprecationHandler(callback) {+ const index = universalHandlers.indexOf(callback);+ if (index > -1) {+ universalHandlers.splice(index, 1);+ }+}++/**+ * Clears the backlog. Intended for tests, so deprecations from one test don't+ * replay into a `{ buffered: true }` handler in the next.+ */+export function clearBacklog() {+ universalBacklog.length = 0;+}+/*** Silence one or more deprecations while running `callback`* @param {(string|RegExp|Array<string|RegExp>)} deprecationIds A single id, regex pattern, or an array containing a mix of ids and regex patterns to silencediff --git a/frontend/discourse/app/services/deprecation-warning-handler.js b/frontend/discourse/app/services/deprecation-warning-handler.jsindex 7baffb16bcb..c2feebd5d7d 100644--- a/frontend/discourse/app/services/deprecation-warning-handler.js+++ b/frontend/discourse/app/services/deprecation-warning-handler.js@@ -1,9 +1,11 @@-import { registerDeprecationHandler } from "@ember/debug";import Service, { service } from "@ember/service";import { addGlobalNotice } from "discourse/components/global-notice";import DeprecationWorkflow from "discourse/deprecation-workflow";import { bind } from "discourse/lib/decorators";-import { registerDeprecationHandler as registerDiscourseDeprecationHandler } from "discourse/lib/deprecated";+import {+ registerUniversalDeprecationHandler,+ unregisterUniversalDeprecationHandler,+} from "discourse/lib/deprecated";import identifySource from "discourse/lib/source-identifier";import { escapeExpression } from "discourse/lib/utilities";import dDasherize from "discourse/ui-kit/helpers/d-dasherize";@@ -11,17 +13,6 @@ import { i18n } from "discourse-i18n";const REPLACEMENT_URLS = {};-// Deprecation handling APIs don't have any way to unregister handlers, so we set up permanent-// handlers and link them up to the application lifecycle using module-local state.-let handler;-registerDeprecationHandler((message, opts, next) => {- handler?.(message, opts);- return next(message, opts);-});-registerDiscourseDeprecationHandler((message, opts) =>- handler?.(message, opts)-);-export default class DeprecationWarningHandler extends Service {@service currentUser;@service siteSettings;@@ -30,11 +21,14 @@ export default class DeprecationWarningHandler extends Service {constructor() {super(...arguments);- handler = this.handle;++ // `buffered: true` replays deprecations that fired before this service+ // existed, e.g. the boot-time `discourse.hbs-extension` notice.+ registerUniversalDeprecationHandler(this.handle, { buffered: true });}willDestroy() {- handler = null;+ unregisterUniversalDeprecationHandler(this.handle);}@binddiff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.jsindex 3056e9fecb5..07b9520aec5 100644--- a/frontend/discourse/tests/helpers/qunit-helpers.js+++ b/frontend/discourse/tests/helpers/qunit-helpers.js@@ -45,7 +45,7 @@ import { clearPluginHeaderActionComponents } from "discourse/lib/admin-plugin-heimport { resetAdditionalReportModes } from "discourse/lib/admin-report-additional-modes";import { rollbackAllPrepends } from "discourse/lib/class-prepend";import { clearPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";-import deprecated from "discourse/lib/deprecated";+import deprecated, { clearBacklog } from "discourse/lib/deprecated";import { clearDesktopNotificationHandlers } from "discourse/lib/desktop-notifications";import { visible as isVisible } from "discourse/lib/dom-utils";import { clearRegisteredEditCategoryTabs } from "discourse/lib/edit-category-tabs";@@ -288,6 +288,7 @@ export function testCleanup(container, app) {_resetOutletLayoutsForTesting();resetBlockRegistryForTesting();resetDebugCallbacks();+ clearBacklog();}function cleanupCssGeneratorTags() {diff --git a/lib/pretty_text/vendor-shims.js b/lib/pretty_text/vendor-shims.jsindex 0a04d0c41ff..2b3fc2e8acd 100644--- a/lib/pretty_text/vendor-shims.js+++ b/lib/pretty_text/vendor-shims.js@@ -33,5 +33,6 @@ define("discourse/lib/environment", ["exports"], function (exports) {});define("discourse/lib/source-identifier", ["exports"], function (exports) {+ exports.default = () => undefined;exports.consolePrefix = () => "";});diff --git a/spec/system/ember_deprecation_spec.rb b/spec/system/ember_deprecation_spec.rbindex 0418c08d57a..8d45297fc4a 100644--- a/spec/system/ember_deprecation_spec.rb+++ b/spec/system/ember_deprecation_spec.rb@@ -104,4 +104,40 @@ describe "JS Deprecation Handling" doexpect(page).to have_css("#global-notice-critical-deprecation--fake-deprecation")end++ it "shows warnings for Discourse and Ember deprecations triggered before the handler is set up" do+ sign_in Fabricate(:admin)++ SiteSetting.warn_critical_js_deprecations = true++ t = Fabricate(:theme, name: "Theme With Early Deprecations")+ t.set_field(+ target: :extra_js,+ type: :js,+ name: "discourse/api-initializers/trigger-early-deprecations.js",+ value: <<~JS,+ import { deprecate } from "@ember/debug";+ import { apiInitializer } from "discourse/lib/api";+ import deprecated from "discourse/lib/deprecated";++ // Both fire during boot, before the admin-banner handler exists.+ deprecated("Fake deprecation message", { id: "fake.deprecation1" });+ deprecate("Fake ember deprecation message", false, {+ id: "fake.deprecation2",+ for: "discourse",+ since: "3.4.0",+ until: "3.5.0",+ });++ export default apiInitializer(() => {});+ JS+ )+ t.save!+ SiteSetting.default_theme_id = t.id++ visit "/latest"++ expect(page).to have_css("#global-notice-critical-deprecation--fake-deprecation1")+ expect(page).to have_css("#global-notice-critical-deprecation--fake-deprecation2")+ endend