A platform for community discussion. Free, open, simple.
DEV: Determine block customization source at build time (#42553)
David Taylorab8b989303e9
diff --git a/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.js b/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.jsindex 094267f8e81..768e19b110d 100644--- a/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.js+++ b/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.js@@ -1,4 +1,25 @@-import rollupVirtualImports from "../rollup-virtual-imports";+import rollupVirtualImports, {+ privateVirtualImports,+} from "../rollup-virtual-imports";++// Core modules that plugin and theme code reaches through a generated wrapper,+// so registrations carry the plugin or theme they came from.+const ATTRIBUTED_MODULES = {+ "discourse/lib/plugin-api": "virtual:attributed-plugin-api",+ "discourse/lib/api": "virtual:attributed-api-initializer",+};++// The leading null byte marks a synthetic module, and keeps the id out of reach+// of anything a plugin or theme could write in an import.+function privateId(basePath, name) {+ return `\0${basePath}${name}`;+}++function isPrivateId(id, basePath) {+ return Object.keys(privateVirtualImports).some(+ (name) => id === privateId(basePath, name)+ );+}export default function discourseVirtualLoader({basePath,@@ -14,7 +35,16 @@ export default function discourseVirtualLoader({return {name: "discourse-virtual-loader",- resolveId(source) {+ resolveId(source, importer) {+ const attributed = ATTRIBUTED_MODULES[source];+ if (attributed) {+ // A wrapper's own import must reach the real module.+ if (!isPrivateId(importer, basePath)) {+ return privateId(basePath, attributed);+ }+ return;+ }+if (availableVirtualImports[source] ||source.startsWith("virtual:entrypoint:")@@ -23,6 +53,10 @@ export default function discourseVirtualLoader({}},load(id) {+ if (isPrivateId(id, basePath)) {+ return privateVirtualImports[id.slice(1 + basePath.length)](opts);+ }+if (!id.startsWith(basePath)) {return;}diff --git a/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.test.mjs b/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.test.mjsnew file mode 100644index 00000000000..05127c4642c--- /dev/null+++ b/frontend/asset-processor/rollup-plugins/discourse-virtual-loader.test.mjs@@ -0,0 +1,56 @@+/* eslint-disable qunit/require-expect */+import { expect, test } from "vitest";+import discourseVirtualLoader from "./discourse-virtual-loader.js";++const basePath = "discourse/plugins/chat/";+const PLUGIN_API_WRAPPER = `\0${basePath}virtual:attributed-plugin-api`;+const API_INITIALIZER_WRAPPER = `\0${basePath}virtual:attributed-api-initializer`;++function loader(isTheme = false) {+ return discourseVirtualLoader({+ basePath,+ entrypoints: {},+ opts: { pluginName: "chat" },+ isTheme,+ });+}++test("redirects the api entry modules to their attributed wrappers", () => {+ const { resolveId } = loader();++ expect(resolveId("discourse/lib/plugin-api", `${basePath}some-module`)).toBe(+ PLUGIN_API_WRAPPER+ );+ expect(resolveId("discourse/lib/api", `${basePath}some-module`)).toBe(+ API_INITIALIZER_WRAPPER+ );+});++test("leaves the wrappers' own imports of the real modules alone", () => {+ const { resolveId } = loader();++ for (const wrapper of [PLUGIN_API_WRAPPER, API_INITIALIZER_WRAPPER]) {+ expect(resolveId("discourse/lib/plugin-api", wrapper)).toBeUndefined();+ expect(resolveId("discourse/lib/api", wrapper)).toBeUndefined();+ }+});++test("the wrappers cannot be imported by name", () => {+ for (const isTheme of [false, true]) {+ const { resolveId } = loader(isTheme);++ expect(+ resolveId("virtual:attributed-plugin-api", `${basePath}some-module`)+ ).toBeUndefined();+ expect(+ resolveId("virtual:attributed-api-initializer", `${basePath}some-module`)+ ).toBeUndefined();+ }+});++test("plugin builds can load the wrappers but not virtual:theme", () => {+ const { load } = loader();++ expect(load(PLUGIN_API_WRAPPER)).toContain("_INTERNAL_SOURCE_KEY");+ expect(load(`${basePath}virtual:theme`)).toBeUndefined();+});diff --git a/frontend/asset-processor/rollup-virtual-imports.js b/frontend/asset-processor/rollup-virtual-imports.jsindex ecc94eb7113..f185575235a 100644--- a/frontend/asset-processor/rollup-virtual-imports.js+++ b/frontend/asset-processor/rollup-virtual-imports.js@@ -98,6 +98,49 @@ export default {},};+// Virtual modules the loader resolves only as a redirect target. They are kept+// out of the default export, and given a null-byte id, so that plugin and theme+// code cannot import them by name.+export const privateVirtualImports = {+ "virtual:attributed-plugin-api": (opts) =>+ attributedEntryFunction({+ module: "discourse/lib/plugin-api",+ exportName: "withPluginApi",+ opts,+ }),+ "virtual:attributed-api-initializer": (opts) =>+ attributedEntryFunction({+ module: "discourse/lib/api",+ exportName: "apiInitializer",+ opts,+ }),+};++// Wraps a core API-entry function so calls from this plugin or theme carry its+// source on `opts`. Plugin and theme imports of `module` resolve here, so the+// wrapper must export everything they are allowed to import from it.+function attributedEntryFunction({ module, exportName, opts }) {+ return cleanMultiline(`+ import { _INTERNAL_SOURCE_KEY } from "discourse/lib/api";+ import { ${exportName} as _${exportName} } from "${module}";++ const SOURCE = Object.freeze(${JSON.stringify(customizationSourceFor(opts))});++ export function ${exportName}(...args) {+ // A leading string is the legacy version argument, which shifts opts along.+ const optsIndex = typeof args[0] === "string" ? 2 : 1;+ args[optsIndex] = { ...args[optsIndex], [_INTERNAL_SOURCE_KEY]: SOURCE };+ return _${exportName}(...args);+ }+ `);+}++function customizationSourceFor({ themeId, pluginName }) {+ return pluginName+ ? { type: "plugin", name: pluginName }+ : { type: "theme", id: themeId };+}+function cleanMultiline(str) {const lines = str.split("\n");diff --git a/frontend/asset-processor/rollup-virtual-imports.test.mjs b/frontend/asset-processor/rollup-virtual-imports.test.mjsnew file mode 100644index 00000000000..df6f90175c0--- /dev/null+++ b/frontend/asset-processor/rollup-virtual-imports.test.mjs@@ -0,0 +1,44 @@+/* eslint-disable qunit/require-expect */+import { expect, test } from "vitest";+import { privateVirtualImports } from "./rollup-virtual-imports.js";++test("attributed plugin-api module wraps withPluginApi for a plugin", () => {+ const code = privateVirtualImports["virtual:attributed-plugin-api"]({+ pluginName: "chat",+ });++ expect(code).toContain(+ 'import { _INTERNAL_SOURCE_KEY } from "discourse/lib/api";'+ );+ expect(code).toContain(+ 'import { withPluginApi as _withPluginApi } from "discourse/lib/plugin-api";'+ );+ expect(code).toContain('Object.freeze({"type":"plugin","name":"chat"})');+ expect(code).toContain("export function withPluginApi(...args)");+ expect(code).toContain("[_INTERNAL_SOURCE_KEY]: SOURCE");+ expect(code).toContain("return _withPluginApi(...args);");+});++test("attributed api-initializer module wraps apiInitializer for a theme", () => {+ const code = privateVirtualImports["virtual:attributed-api-initializer"]({+ themeId: 42,+ });++ expect(code).toContain(+ 'import { apiInitializer as _apiInitializer } from "discourse/lib/api";'+ );+ expect(code).toContain('Object.freeze({"type":"theme","id":42})');+ expect(code).toContain("export function apiInitializer(...args)");+ expect(code).toContain("return _apiInitializer(...args);");+});++test("the source lands on opts, after the legacy version argument", () => {+ const code = privateVirtualImports["virtual:attributed-plugin-api"]({+ pluginName: "chat",+ });++ expect(code).toContain('typeof args[0] === "string" ? 2 : 1');+ expect(code).toContain(+ "args[optsIndex] = { ...args[optsIndex], [_INTERNAL_SOURCE_KEY]: SOURCE };"+ );+});diff --git a/frontend/discourse/app/lib/api.js b/frontend/discourse/app/lib/api.jsindex 334fc6ca12b..d5c4eac3139 100644--- a/frontend/discourse/app/lib/api.js+++ b/frontend/discourse/app/lib/api.js@@ -1,6 +1,8 @@// @ts-checkimport { withPluginApi } from "discourse/lib/plugin-api";+export { _INTERNAL_SOURCE_KEY } from "discourse/lib/customization-source";+let _apiInitializerId = 0;/**diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/block.ts b/frontend/discourse/app/lib/blocks/-internals/registry/block.tsindex 64d371d3976..63e4cb6b63a 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/block.ts+++ b/frontend/discourse/app/lib/blocks/-internals/registry/block.ts@@ -13,6 +13,7 @@ import type {BlockFactory,BlockRegistryEntry,} from "discourse/lib/blocks/-internals/types";+import type { CustomizationSource } from "discourse/lib/customization-source";import { isTesting } from "discourse/lib/environment";import {assertNotDuplicate,@@ -282,6 +283,7 @@ export function _freezeBlockRegistry(): void {* callers reach this through `api.registerBlock()`, where a bad or circular* import hands it `undefined`; that call must report the decorator error* rather than fail on a property read.+ * @param source - The plugin or theme the call came from.* @throws If called after registry is locked, or if block is invalid** @example@@ -299,7 +301,10 @@ export function _freezeBlockRegistry(): void {* };* ```*/-export function _registerBlock(klass: BlockClass | null | undefined): void {+export function _registerBlock(+ klass: BlockClass | null | undefined,+ source?: CustomizationSource+): void {const metadata: BlockMetadata | null = getBlockMetadata(klass);const blockName = metadata?.blockName;@@ -325,7 +330,9 @@ export function _registerBlock(klass: BlockClass | null | undefined): void {return;}- if (!validateSourceNamespace({ name: blockName, entityType: "block" })) {+ if (+ !validateSourceNamespace({ name: blockName, entityType: "block", source })+ ) {return;}@@ -344,6 +351,7 @@ export function _registerBlock(klass: BlockClass | null | undefined): void {** @param name - The name to register the block under.* @param factory - Factory function returning Promise<BlockClass>.+ * @param source - The plugin or theme the call came from.* @throws If registry is locked, name is invalid, or factory is not a function.** @example@@ -355,7 +363,8 @@ export function _registerBlock(klass: BlockClass | null | undefined): void {*/export function _registerBlockFactory(name: string,- factory: BlockFactory+ factory: BlockFactory,+ source?: CustomizationSource): void {if (!assertRegistryNotFrozen({@@ -379,7 +388,7 @@ export function _registerBlockFactory(return;}- if (!validateSourceNamespace({ name, entityType: "block" })) {+ if (!validateSourceNamespace({ name, entityType: "block", source })) {return;}diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/condition.ts b/frontend/discourse/app/lib/blocks/-internals/registry/condition.tsindex 09a1591d72b..c28eaa0cf2e 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/condition.ts+++ b/frontend/discourse/app/lib/blocks/-internals/registry/condition.ts@@ -2,6 +2,7 @@ import { DEBUG } from "@glimmer/env";import type { BlockCondition } from "discourse/blocks/conditions";import { isDecoratedCondition } from "discourse/blocks/conditions/decorator";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";+import type { CustomizationSource } from "discourse/lib/customization-source";import { isTesting } from "discourse/lib/environment";import {assertRegistryNotFrozen,@@ -84,6 +85,7 @@ export function _freezeConditionTypeRegistry(): void {* because untyped callers can hand `api.registerBlockConditionType()` a bad* import; that call must report the decorator error, not a property-read* failure.+ * @param source - The plugin or theme the call came from.** @example* ```javascript@@ -102,7 +104,8 @@ export function _freezeConditionTypeRegistry(): void {* @internal*/export function _registerConditionType(- ConditionClass: typeof BlockCondition | null | undefined+ ConditionClass: typeof BlockCondition | null | undefined,+ source?: CustomizationSource): void {if (!assertRegistryNotFrozen({@@ -132,7 +135,9 @@ export function _registerConditionType(}// Validate namespace requirements for plugins/themes and enforce consistency- if (!validateSourceNamespace({ name: type, entityType: "condition" })) {+ if (+ !validateSourceNamespace({ name: type, entityType: "condition", source })+ ) {return;}diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/helpers.ts b/frontend/discourse/app/lib/blocks/-internals/registry/helpers.tsindex 8ad08ec2ced..eb0d98c1ae8 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/helpers.ts+++ b/frontend/discourse/app/lib/blocks/-internals/registry/helpers.ts@@ -5,14 +5,18 @@ import {parseBlockName,VALID_NAMESPACED_BLOCK_PATTERN,} from "discourse/lib/blocks/-internals/patterns";+import {+ type CustomizationSource,+ resolveSourceId,+} from "discourse/lib/customization-source";import { isTesting } from "discourse/lib/environment";-import identifySource from "discourse/lib/source-identifier";+import { getThemeInfo } from "discourse/lib/source-identifier";/*** Tracks which namespace each source (theme/plugin) has used.* Enforces that each source can only register blocks with a single namespace.*- * Key: source identifier (e.g., "theme:Tactile Theme" or "plugin:chat")+ * Key: source identifier (e.g., "theme:42" or "plugin:chat")* Value: the namespace prefix used (e.g., "theme:tactile" or "chat")*/const sourceNamespaceMap = new Map<string, string | null>();@@ -121,6 +125,9 @@ interface ValidateSourceNamespaceOptions {/** Type of entity for error messages. */entityType: "block" | "outlet" | "condition";+ /** The plugin or theme the call came from. */+ source?: CustomizationSource;+/** Whether to enforce single namespace per source. Defaults to `true`. */enforceConsistency?: boolean;}@@ -138,9 +145,10 @@ interface ValidateSourceNamespaceOptions {export function validateSourceNamespace({name,entityType,+ source,enforceConsistency = true,}: ValidateSourceNamespaceOptions): boolean {- const sourceId = getSourceIdentifier();+ const sourceId = getSourceIdentifier(source);if (!sourceId) {return true;}@@ -183,9 +191,14 @@ export function validateSourceNamespace({existingNamespace !== undefined &&existingNamespace !== namespacePrefix) {+ // Themes are keyed by id, but the message reads better with their name.+ const sourceLabel =+ source?.type === "theme"+ ? `theme:${getThemeInfo(source.id).name}`+ : sourceId;raiseBlockError(`${entityCapitalized} "${name}" uses namespace "${namespacePrefix ?? "(core)"}" but ` +- `${sourceId} already used namespace "${existingNamespace ?? "(core)"}". ` ++ `${sourceLabel} already used namespace "${existingNamespace ?? "(core)"}". ` +`Each theme/plugin must use a single consistent namespace for all blocks, outlets, and conditions.`);return false;@@ -259,27 +272,18 @@ export function createTestRegistrationWrapper({*//**- * Gets a unique identifier for the current source from the call stack.- * Returns null for core code (no theme or plugin detected).+ * Gets a unique identifier for the given customization source. In tests, a value+ * set via `setTestSourceIdentifier` takes precedence.*- * @returns Source identifier like "theme:Tactile" or "plugin:chat"+ * @param source - The plugin or theme the call came from.+ * @returns Source identifier like "theme:42" or "plugin:chat", or null for core.*/-function getSourceIdentifier(): string | null {+function getSourceIdentifier(source?: CustomizationSource): string | null {if (DEBUG && testSourceIdentifier !== undefined) {return testSourceIdentifier;}- const source = identifySource();- if (!source) {- return null;- }- if (source.type === "theme") {- return `theme:${source.name}`;- }- if (source.type === "plugin") {- return `plugin:${source.name}`;- }- return null;+ return resolveSourceId(source);}/**diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/outlet.ts b/frontend/discourse/app/lib/blocks/-internals/registry/outlet.tsindex 0f21eaf7df9..6f2a6e0539b 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/outlet.ts+++ b/frontend/discourse/app/lib/blocks/-internals/registry/outlet.ts@@ -1,5 +1,6 @@import { DEBUG } from "@glimmer/env";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";+import type { CustomizationSource } from "discourse/lib/customization-source";import { isTesting } from "discourse/lib/environment";import { BLOCK_OUTLETS } from "discourse/lib/registry/block-outlets";import {@@ -100,12 +101,14 @@ interface RegisterOutletOptions {** @param outletName - The outlet name (must follow naming conventions).* @param options - Outlet options.+ * @param source - The plugin or theme the call came from.** @internal*/export function _registerOutlet(outletName: string,- options: RegisterOutletOptions = {}+ options: RegisterOutletOptions = {},+ source?: CustomizationSource): void {if (!assertRegistryNotFrozen({@@ -141,6 +144,7 @@ export function _registerOutlet(!validateSourceNamespace({name: outletName,entityType: "outlet",+ source,})) {return;diff --git a/frontend/discourse/app/lib/customization-source.ts b/frontend/discourse/app/lib/customization-source.tsnew file mode 100644index 00000000000..2a276f8404d--- /dev/null+++ b/frontend/discourse/app/lib/customization-source.ts@@ -0,0 +1,35 @@+/**+ * Key under which the asset processor puts a plugin's or theme's source on the+ * `opts` of an API-entry function. Re-exported from `discourse/lib/api` so the+ * generated wrappers can reach it; nothing else may read or write it.+ */+export const _INTERNAL_SOURCE_KEY = Symbol("customization source");++/** The origin of a piece of customization code. */+export type CustomizationSource =+ | { type: "core" }+ | { type: "plugin"; name: string }+ | { type: "theme"; id: number };++/** The source of code shipped with core, rather than a plugin or theme. */+export const CORE_SOURCE: Readonly<CustomizationSource> = Object.freeze({+ type: "core",+});++/**+ * Maps a source to a stable identifier: `plugin:<name>` or `theme:<id>`. Themes+ * are keyed by id because their name can change.+ *+ * @returns null for core, which has no namespace of its own.+ */+export function resolveSourceId(+ source?: CustomizationSource | null+): string | null {+ if (source?.type === "plugin") {+ return `plugin:${source.name}`;+ }+ if (source?.type === "theme") {+ return `theme:${source.id}`;+ }+ return null;+}diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 0efa0704ce4..5c210457d38 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -61,6 +61,10 @@ import classPrepend, {} from "discourse/lib/class-prepend";import { addPopupMenuOption } from "discourse/lib/composer/custom-popup-menu-options";import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";+import {+ _INTERNAL_SOURCE_KEY,+ CORE_SOURCE,+} from "discourse/lib/customization-source";import deprecated from "discourse/lib/deprecated";import { registerDesktopNotificationHandler } from "discourse/lib/desktop-notifications";import { downloadCalendar } from "discourse/lib/download-calendar";@@ -208,8 +212,16 @@ function wrapWithErrorHandler(func, messageKey) {* @typedef {_PluginApi} PluginApi*/class _PluginApi {- constructor(container) {+ #source;++ constructor(container, source = CORE_SOURCE) {this.container = container;+ this.#source = source;+ }++ /** The plugin, theme, or core code this api was handed to. */+ get source() {+ return this.#source;}/**@@ -3826,10 +3838,10 @@ class _PluginApi {`registerBlock("${blockOrName}", ...) requires a factory function as second argument.`);}- _registerBlockFactory(blockOrName, factory);+ _registerBlockFactory(blockOrName, factory, this.source);} else {// Direct class: registerBlock(BlockClass)- _registerBlock(blockOrName);+ _registerBlock(blockOrName, this.source);}}@@ -3863,7 +3875,7 @@ class _PluginApi {* ```*/registerBlockOutlet(outletName, options) {- _registerOutlet(outletName, options);+ _registerOutlet(outletName, options, this.source);}/**@@ -3911,7 +3923,7 @@ class _PluginApi {* ```*/registerBlockConditionType(ConditionClass) {- _registerConditionType(ConditionClass);+ _registerConditionType(ConditionClass, this.source);}#deprecateModifyClass(resolverName, apiName) {@@ -3929,23 +3941,6 @@ class _PluginApi {}}-function getPluginApi() {- const owner = getOwnerWithFallback(this);- let pluginApi = owner.lookup("plugin-api:main");-- if (!pluginApi) {- pluginApi = new _PluginApi(owner);- owner.registry.register("plugin-api:main", pluginApi, {- instantiate: false,- });- } else {- // If we are re-using an instance, make sure the container is correct- pluginApi.container = owner;- }-- return pluginApi;-}-/*** Executes the provided callback function with the `PluginApi` object.*@@ -3961,5 +3956,10 @@ export function withPluginApi(apiCodeCallback, opts) {opts = opts || {};- return apiCodeCallback(getPluginApi(), opts);+ const api = new _PluginApi(+ getOwnerWithFallback(this),+ opts[_INTERNAL_SOURCE_KEY]+ );++ return apiCodeCallback(api, opts);}diff --git a/frontend/discourse/tests/unit/lib/customization-source-test.js b/frontend/discourse/tests/unit/lib/customization-source-test.jsnew file mode 100644index 00000000000..915f2dbf682--- /dev/null+++ b/frontend/discourse/tests/unit/lib/customization-source-test.js@@ -0,0 +1,23 @@+import { module, test } from "qunit";+import {+ CORE_SOURCE,+ resolveSourceId,+} from "discourse/lib/customization-source";++module("Unit | Lib | customization-source", function () {+ test("CORE_SOURCE is a frozen core descriptor", function (assert) {+ assert.deepEqual(CORE_SOURCE, { type: "core" });+ assert.true(Object.isFrozen(CORE_SOURCE));+ });++ test("resolveSourceId maps descriptors to stable ids", function (assert) {+ assert.strictEqual(+ resolveSourceId({ type: "plugin", name: "chat" }),+ "plugin:chat"+ );+ assert.strictEqual(resolveSourceId({ type: "theme", id: 42 }), "theme:42");+ assert.strictEqual(resolveSourceId(CORE_SOURCE), null, "core has no id");+ assert.strictEqual(resolveSourceId(null), null);+ assert.strictEqual(resolveSourceId(undefined), null);+ });+});diff --git a/frontend/discourse/tests/unit/lib/plugin-api-test.js b/frontend/discourse/tests/unit/lib/plugin-api-test.jsindex 876f0d4a218..1db3758b3f8 100644--- a/frontend/discourse/tests/unit/lib/plugin-api-test.js+++ b/frontend/discourse/tests/unit/lib/plugin-api-test.js@@ -6,6 +6,7 @@ import { module, test } from "qunit";import sinon from "sinon";import { block } from "discourse/blocks";import { BlockCondition, blockCondition } from "discourse/blocks/conditions";+import { _INTERNAL_SOURCE_KEY, apiInitializer } from "discourse/lib/api";import { rollbackAllPrepends } from "discourse/lib/class-prepend";import { withPluginApi } from "discourse/lib/plugin-api";import {@@ -476,4 +477,164 @@ module("Unit | Utility | plugin-api", function (hooks) {});});});++ module("Customization source", function (nestedHooks) {+ nestedHooks.beforeEach(function () {+ resetBlockRegistryForTesting();+ });++ // The build emits a frozen source, so these mirror it.+ function pluginOpts(name, opts) {+ const source = Object.freeze({ type: "plugin", name });+ return { ...opts, [_INTERNAL_SOURCE_KEY]: source };+ }++ function themeOpts(id, opts) {+ const source = Object.freeze({ type: "theme", id });+ return { ...opts, [_INTERNAL_SOURCE_KEY]: source };+ }++ test("binds the source from opts to the api", function (assert) {+ let boundSource, receivedOpts;++ withPluginApi(+ (api, opts) => {+ boundSource = api.source;+ receivedOpts = opts;+ },+ pluginOpts("chat", { foo: 1 })+ );++ assert.strictEqual(boundSource.type, "plugin");+ assert.strictEqual(boundSource.name, "chat");+ assert.strictEqual(receivedOpts.foo, 1, "user opts are preserved");+ });++ test("core code (no source) gets a core source", function (assert) {+ let api;+ withPluginApi((a) => (api = a));++ assert.deepEqual(api.source, { type: "core" });+ assert.strictEqual(+ typeof api.getCurrentUser,+ "function",+ "the api methods are available"+ );+ });++ test("every call gets its own api carrying its own source", function (assert) {+ let first, second, other;++ withPluginApi((api) => (first = api), pluginOpts("chat"));+ withPluginApi((api) => (second = api), pluginOpts("chat"));+ withPluginApi((api) => (other = api), themeOpts(1));++ assert.notStrictEqual(first, second, "instances are not shared");+ assert.deepEqual(first.source, second.source);+ assert.deepEqual(other.source, { type: "theme", id: 1 });+ assert.strictEqual(+ typeof first.getCurrentUser,+ "function",+ "each one exposes the full PluginApi surface"+ );+ });++ test("legacy version-string signature still binds the source", function (assert) {+ let boundSource;++ withPluginApi(+ // eslint-disable-next-line discourse/plugin-api-no-version -- intentionally exercising the legacy version-string signature+ "1.0",+ (api) => (boundSource = api.source),+ pluginOpts("chat")+ );++ assert.strictEqual(boundSource.type, "plugin");+ assert.strictEqual(boundSource.name, "chat");+ });++ test("apiInitializer forwards the source to the callback", function (assert) {+ let boundSource;++ const initializer = apiInitializer(+ (api) => (boundSource = api.source),+ pluginOpts("chat")+ );+ initializer.initialize();++ assert.strictEqual(boundSource.type, "plugin");+ assert.strictEqual(boundSource.name, "chat");+ });++ test("attribution comes from the source, not the call stack", function (assert) {+ // Code with no source is core and may use any namespace, whatever frames+ // are on the stack.+ @block("any-namespace-block")+ class CoreNamespacedBlock extends Component {}++ withPluginApi((api) => api.registerBlock(CoreNamespacedBlock));+ assert.true(+ hasBlock("any-namespace-block"),+ "core code may register any name"+ );++ // A plugin source enforces the plugin namespace.+ @block("unnamespaced-from-plugin")+ class PluginBlock extends Component {}++ withPluginApi((api) => {+ assert.throws(+ () => api.registerBlock(PluginBlock),+ /Plugin blocks must use the "namespace:block-name" format/+ );+ }, pluginOpts("chat"));++ // The same plugin can register a correctly namespaced block.+ @block("chat:source-block")+ class NamespacedPluginBlock extends Component {}++ withPluginApi(+ (api) => api.registerBlock(NamespacedPluginBlock),+ pluginOpts("chat")+ );+ assert.true(hasBlock("chat:source-block"));+ });++ test("the api can invoke methods that use private members", function (assert) {+ // modifyClass touches a #private, which brand-checks, so the api has to be+ // a real instance rather than something made with Object.create.+ class SourceThing {}+ getOwner(this).register("source-thing:main", SourceThing);++ withPluginApi((api) => {+ api.modifyClass(+ "source-thing:main",+ (Superclass) => class extends Superclass {}+ );+ }, pluginOpts("chat"));++ assert.true(true, "modifyClass works on a source-carrying api");+ });++ test("source cannot be reassigned or mutated", function (assert) {+ let api;+ withPluginApi((a) => (api = a), pluginOpts("chat"));++ assert.throws(+ () => (api.source = { type: "plugin", name: "evil" }),+ TypeError,+ "the source binding cannot be reassigned"+ );+ assert.throws(+ () => (api.source.name = "evil"),+ TypeError,+ "the source object is frozen by the build"+ );+ assert.strictEqual(+ api.source.name,+ "chat",+ "the source is unchanged after both attempts"+ );+ });+ });});diff --git a/lib/asset_processor.rb b/lib/asset_processor.rbindex c05fed0cfcc..0c602a85220 100644--- a/lib/asset_processor.rb+++ b/lib/asset_processor.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass AssetProcessor- BASE_COMPILER_VERSION = 113+ BASE_COMPILER_VERSION = 114BUNDLE =PrecompiledBundle.new(diff --git a/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js b/plugins/chat/test/javascripts/unit/lib/chat-audio-test.jsindex 0174c4e3a0d..958a6171859 100644--- a/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js+++ b/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js@@ -26,7 +26,10 @@ module("Unit | chat-audio", function (hooks) {this.currentUser.user_option.chat_header_indicator_preference = "all_new";withPluginApi(async (api) => {- this.stub = sinon.spy(api, "registerDesktopNotificationHandler");+ this.stub = sinon.spy(+ Object.getPrototypeOf(api),+ "registerDesktopNotificationHandler"+ );chatAudioInitializer.initialize(getOwner(this));// stub the service worker responsediff --git a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjsindex 6b6e2cb2789..d1e70878332 100644--- a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs@@ -117,7 +117,7 @@ module(.get(() => ({ providerName: "youtube", id: "dQw4w9WgXcQ" }));withPluginApi((api) => {- preventCloak = sinon.stub(api, "preventCloak");+ preventCloak = sinon.stub(Object.getPrototypeOf(api), "preventCloak");});});@@ -175,7 +175,7 @@ module(sinon.stub(ZoomMeetingSession.prototype, "performJoin").resolves();withPluginApi((api) => {- preventCloak = sinon.stub(api, "preventCloak");+ preventCloak = sinon.stub(Object.getPrototypeOf(api), "preventCloak");});});diff --git a/spec/lib/theme_javascript_compiler_spec.rb b/spec/lib/theme_javascript_compiler_spec.rbindex bef3898eade..993bed33097 100644--- a/spec/lib/theme_javascript_compiler_spec.rb+++ b/spec/lib/theme_javascript_compiler_spec.rb@@ -258,4 +258,31 @@ RSpec.describe ThemeJavascriptCompiler doexpect(compiler.content).not_to include("discourse.es6-extension")endend++ describe "customization source" do+ it "routes api entry points through a wrapper carrying the theme" do+ compiler.append_tree({ "initializers/direct.js" => <<~JS })+ import { withPluginApi } from "discourse/lib/plugin-api";+ export function direct() {+ withPluginApi((api) => api.source);+ }+ JS++ expect(compiler.content).to include("[_INTERNAL_SOURCE_KEY]: SOURCE")+ expect(compiler.content).to include('"type": "theme"')+ expect(compiler.content).to include('"id": 1')+ end++ it "attributes a namespace import too" do+ compiler.append_tree({ "initializers/indirect.js" => <<~JS })+ import * as pluginApi from "discourse/lib/plugin-api";+ const stored = pluginApi.withPluginApi;+ export function indirect() {+ stored((api) => api.source);+ }+ JS++ expect(compiler.content).to include("[_INTERNAL_SOURCE_KEY]: SOURCE")+ end+ endend