A platform for community discussion. Free, open, simple.
DEV: Convert the transformers pipeline to TypeScript (#44800)
Sérgio Saquetim41e2cde7ccc3
diff --git a/docs/developer-guides/docs/03-code-internals/24-transformers.md b/docs/developer-guides/docs/03-code-internals/24-transformers.mdindex 063a7481311..9a9873d04a9 100644--- a/docs/developer-guides/docs/03-code-internals/24-transformers.md+++ b/docs/developer-guides/docs/03-code-internals/24-transformers.md@@ -76,11 +76,11 @@ If multiple transformers are registered against a single name, then they will be## Finding Transformers-At the moment there is no centralized documentation for transformers. However, a list of all core transformers can be found in the code [here](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/lib/transformer/registry.js). You can then search for those names in the core codebase to find where they're called, the context/value, and the expected return type.+At the moment there is no centralized documentation for transformers. However, a list of all core transformers can be found in the code [here](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/lib/registry/transformers.ts). You can then search for those names in the core codebase to find where they're called, the context/value, and the expected return type.## Introducing new Transformers-To introduce new transformers, the name first needs to be added to the registry. In core, add it to [lib/transformer/registry.js](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/lib/transformer/registry.js).+To introduce new transformers, the name first needs to be added to the registry. In core, add it to [lib/registry/transformers.ts](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/lib/registry/transformers.ts).To introduce a new transformer via a theme or plugin, create a `pre-initializer` and register the name via the relevant API:@@ -124,3 +124,11 @@ applyBehaviorTransformer(context);```++## TypeScript++The transformer pipeline exports `ValueTransformer`, `MutableValueTransformer`, `AnyValueTransformer`, `BehaviorTransformer`, and `DefaultBehaviorTransformer` callback types from `discourse/lib/transformer`. Value callbacks take value and context type parameters: `ValueTransformer<T, C>` returns `T`, while `MutableValueTransformer<T, C>` mutates the value and returns `void`. `registerValueTransformer` accepts `AnyValueTransformer<T, C>`, which allows either kind but still rejects a callback returning something other than `T`. Behavior callbacks take return and context type parameters. Context types can be interfaces without an index signature. Hook names remain strings so plugins and themes can introduce hooks.++`applyValueTransformer` and `applyMutableValueTransformer` infer their result type from the default value. Supply an explicit type argument when a hook can return a broader type than its default, for example `applyValueTransformer<string | null>("custom-label", null)`. Registration and application must agree on a hook's value, context, and return types; the string registry does not enforce a shared contract between separate calls.++Behavior callbacks receive a shallow copy of the context. `next()` and `applyBehaviorTransformer` can return `void` when middleware stops the chain or calls `next()` after the queue is exhausted. Promise results pass through unchanged, and async middleware that awaits `next()` resolves to the awaited result or `undefined`; `BehaviorTransformerResult<R>` describes the full result type.diff --git a/frontend/discourse/app/components/user-field.gjs b/frontend/discourse/app/components/user-field.gjsindex e9a96fd8354..9c15d7b5e48 100644--- a/frontend/discourse/app/components/user-field.gjs+++ b/frontend/discourse/app/components/user-field.gjs@@ -1,6 +1,6 @@import Component from "@glimmer/component";import { get } from "@ember/helper";-import { applyValueTransformer } from "../lib/transformer.js";+import { applyValueTransformer } from "../lib/transformer.ts";import UserFieldConfirm from "./user-fields/confirm.gjs";import UserFieldDate from "./user-fields/date.gjs";import UserFieldDropdown from "./user-fields/dropdown.gjs";diff --git a/frontend/discourse/app/initializers/freeze-valid-transformers.js b/frontend/discourse/app/initializers/freeze-valid-transformers.tssimilarity index 90%rename from frontend/discourse/app/initializers/freeze-valid-transformers.jsrename to frontend/discourse/app/initializers/freeze-valid-transformers.tsindex a0bda414996..a4f3a73c91d 100644--- a/frontend/discourse/app/initializers/freeze-valid-transformers.js+++ b/frontend/discourse/app/initializers/freeze-valid-transformers.ts@@ -4,7 +4,7 @@ export default {before: "inject-discourse-objects",after: "discourse-bootstrap",- initialize() {+ initialize(): void {_freezeValidTransformerNames();},};diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex c12be4715c0..6d7ba7fe4f9 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -426,7 +426,7 @@ class _PluginApi {* },* };*- * @param name the name of the new transformer+ * @param {string} name the name of the new transformer**/addBehaviorTransformerName(name) {@@ -478,12 +478,12 @@ class _PluginApi {* });* ```*+ * @template [R=unknown] - The expected behavior result; middleware may also return void.+ * @template {object} [C=Record<string, unknown>] - Properties of the context supplied when applying the hook.* @param {string} transformerName the name of the transformer- * @param {function({next, context})} behaviorCallback callback to be used to transform or override the behavior.- * @param {*} behaviorCallback.next callback that executes the remaining transformer queue producing the expected- * behavior. Notice that this includes the default behavior and if next() is not called in your transformer's callback- * the default behavior will be completely overridden- * @param {*} [behaviorCallback.context] the optional context in which the behavior is being transformed+ * @param {import("discourse/lib/transformer").BehaviorTransformer<R, C>} behaviorCallback+ * Middleware which can call next() to run the remaining queue, including the default behavior. If the callback+ * doesn't call next(), the default behavior is completely overridden.* @returns {boolean} True if the transformer exists, false otherwise.*/registerBehaviorTransformer(transformerName, behaviorCallback) {@@ -515,7 +515,7 @@ class _PluginApi {* },* };*- * @param name the name of the new transformer+ * @param {string} name the name of the new transformer**/addValueTransformerName(name) {@@ -546,12 +546,14 @@ class _PluginApi {* });* ```*+ * @template [T=unknown] - The value passed to the callback.+ * @template {object} [C=Record<string, unknown>] - Properties of the context supplied when applying the hook.* @param {string} transformerName the name of the transformer- * @param {function({value, context})} valueCallback callback to be used to transform the value. To avoid potential- * errors or unexpected behavior the callback must be a pure function, i.e. return the transform value instead of- * mutating the input value, return the same output for the same input and not have any side effects.- * @param {*} valueCallback.value the value to be transformed- * @param {*} [valueCallback.context] the optional context in which the value is being transformed+ * @param {import("discourse/lib/transformer").AnyValueTransformer<T, C>} valueCallback+ * Receives the current value and context. To avoid potential errors or unexpected behavior the callback must be a+ * pure function, i.e. return the transformed value instead of mutating the input value, return the same output for+ * the same input and not have any side effects. Only hooks applied with `applyMutableValueTransformer` expect the+ * callback to mutate the value instead; their return value is ignored.* @returns {boolean} True if the transformer exists, false otherwise.*/registerValueTransformer(transformerName, valueCallback) {diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.tssimilarity index 96%rename from frontend/discourse/app/lib/registry/transformers.jsrename to frontend/discourse/app/lib/registry/transformers.tsindex 66b5745eed1..35a276d1ac2 100644--- a/frontend/discourse/app/lib/registry/transformers.js+++ b/frontend/discourse/app/lib/registry/transformers.ts@@ -4,8 +4,6 @@* These transformers are invoked at key points to allow customization of the application behavior.** USE ONLY lowercase names- *- * @constant {ReadonlyArray<string>} BEHAVIOR_TRANSFORMERS - An immutable array of behavior transformer identifiers*/// eslint-discourse keep-array-sortedexport const BEHAVIOR_TRANSFORMERS = Object.freeze([@@ -39,8 +37,6 @@ export const BEHAVIOR_TRANSFORMERS = Object.freeze([* Each transformer represents a specific value or computation that can be customized.** USE ONLY lowercase names- *- * @constant {ReadonlyArray<string>} VALUE_TRANSFORMERS - An immutable array of value transformer identifiers*/// eslint-discourse keep-array-sortedexport const VALUE_TRANSFORMERS = Object.freeze([diff --git a/frontend/discourse/app/lib/transformer.js b/frontend/discourse/app/lib/transformer.tssimilarity index 57%rename from frontend/discourse/app/lib/transformer.jsrename to frontend/discourse/app/lib/transformer.tsindex 11d8456fe93..bc5e36af007 100644--- a/frontend/discourse/app/lib/transformer.js+++ b/frontend/discourse/app/lib/transformer.ts@@ -7,6 +7,106 @@ import {} from "discourse/lib/registry/transformers";import { consolePrefix } from "discourse/lib/source-identifier";+/** The registration category of a transformer. */+export type TransformerType = "BEHAVIOR" | "VALUE";++/**+ * Context copied for a behavior chain, including its optional calling instance.+ * @typeParam C - Properties supplied by the caller before the calling instance is added.+ */+export type BehaviorTransformerContext<+ C extends object = Record<string, unknown>,+> = C & { _unstable_self?: unknown };++/**+ * A value hook receives the current value and the original, optional context.+ * @typeParam T - The value passed to the callback.+ * @typeParam C - Properties of the optional context object.+ */+export type ValueTransformer<+ T = unknown,+ C extends object = Record<string, unknown>,+> = (args: {+ /** The result of the preceding transformer, or the default value. */+ value: T;+ /** The context passed when applying the hook. */+ context: C | null | undefined;+}) => T;++/**+ * Mutates the supplied value; the pipeline ignores the callback's return value.+ * @typeParam T - The value to mutate.+ * @typeParam C - Properties of the optional context object.+ */+export type MutableValueTransformer<+ T = unknown,+ C extends object = Record<string, unknown>,+> = (args: Parameters<ValueTransformer<T, C>>[0]) => void;++/**+ * Either kind of value callback, as accepted at registration.+ *+ * A union with `MutableValueTransformer` would accept any return type, because a function returning a value is+ * assignable to one returning `void`. Returning `T | void` keeps the result checked.+ *+ * @typeParam T - The value passed to the callback.+ * @typeParam C - Properties of the optional context object.+ */+export type AnyValueTransformer<+ T = unknown,+ C extends object = Record<string, unknown>,+> = (args: Parameters<ValueTransformer<T, C>>[0]) => T | void;++/**+ * The core implementation called after the behavior middleware.+ * @typeParam R - The default implementation's result, including a Promise for async behavior.+ * @typeParam C - Properties supplied in the context before the calling instance is added.+ */+export type DefaultBehaviorTransformer<+ R = unknown,+ C extends object = Record<string, unknown>,+> = (args: {+ /** A shallow copy of the supplied context, shared throughout the chain. */+ context: BehaviorTransformerContext<C>;+}) => R;++/**+ * The result of a behavior chain. Middleware can stop the chain and return `void`, and async middleware that awaits+ * `next()` resolves to `Awaited<R> | void`.+ *+ * The check is not distributive, so a union of promise results gets a single combined promise.+ *+ * @typeParam R - The default implementation's result.+ */+export type BehaviorTransformerResult<R> =+ | R+ | void+ | ([Extract<R, Promise<unknown>>] extends [never]+ ? never+ : Promise<Awaited<R> | void>);++/**+ * Behavior middleware may continue the chain or replace the default behavior.+ * @typeParam R - The expected behavior result; middleware and next() may also return void.+ * @typeParam C - Properties supplied in the context before the calling instance is added.+ */+export type BehaviorTransformer<+ R = unknown,+ C extends object = Record<string, unknown>,+> = (args: {+ /** Runs the remaining middleware and default behavior; an exhausted chain returns undefined. */+ next: () => BehaviorTransformerResult<R>;+ /** A shallow copy of the supplied context, shared throughout the chain. */+ context: BehaviorTransformerContext<C>;+}) => BehaviorTransformerResult<R>;++type TransformerSource = "CORE" | "PLUGIN";++interface TransformerInfo {+ name: string;+ source: TransformerSource;+}+const CORE_TRANSFORMER = "CORE";const PLUGIN_TRANSFORMER = "PLUGIN";@@ -14,12 +114,10 @@ export const transformerTypes = Object.freeze({// key and value must matchBEHAVIOR: "BEHAVIOR",VALUE: "VALUE",-});+} as const);/*** Test flag - disables throwing an exception if applying a transformer fails on tests- *- * @type {boolean}*/let skipApplyExceptionOnTests = false;@@ -30,13 +128,12 @@ let skipApplyExceptionOnTests = false;** The list can be edited in `discourse/lib/registry/transformers`*/-let validTransformerNames = new Map();+let validTransformerNames = new Map<string, TransformerSource>();-// Initialize the valid transformer names, notice that we perform some checks to ensure the transformer names are-// correctly defined, i.e., lowercase and unique.+// Core names must be lowercase and unique across transformer categories.[- [BEHAVIOR_TRANSFORMERS, transformerTypes.BEHAVIOR],- [VALUE_TRANSFORMERS, transformerTypes.VALUE],+ [BEHAVIOR_TRANSFORMERS, transformerTypes.BEHAVIOR] as const,+ [VALUE_TRANSFORMERS, transformerTypes.VALUE] as const,].forEach(([list, transformerType]) => {list.forEach((name) => {if (DEBUG) {@@ -64,7 +161,8 @@ let validTransformerNames = new Map();});});-const transformersRegistry = new Map();+/** Hook names are extensible, so callback types are erased while stored. */+const transformersRegistry = new Map<string, unknown[]>();/*** Indicates if the registry is open for registration.@@ -74,8 +172,6 @@ const transformersRegistry = new Map();** When the registry is open, the system will throw an error if a transformer name is added and will accept registering* transformers to be applied.- *- * @type {boolean}*/let registryOpened = false;@@ -84,11 +180,11 @@ let registryOpened = false;** INTERNAL API: to be used only in `initializers/freeze-valid-transformers`*/-export function _freezeValidTransformerNames() {+export function _freezeValidTransformerNames(): void {registryOpened = true;}-function _normalizeTransformerName(name, type) {+function _normalizeTransformerName(name: string, type: string): string {return `${name}/${type.toLowerCase()}`;}@@ -100,10 +196,13 @@ function _normalizeTransformerName(name, type) {* DO NOT USE THIS FUNCTION TO ADD CORE TRANSFORMER NAMES. Instead register them directly in the* validTransformerNames set above.*- * @param {string} name the name to register- * @param {string} transformerType the type of the transformer being added+ * @param name - the name to register+ * @param transformerType - the type of the transformer being added*/-export function _addTransformerName(name, transformerType) {+export function _addTransformerName(+ name: string,+ transformerType: TransformerType+): void {const prefix = () =>`${consolePrefix()} api.add${capitalize(transformerType.toLowerCase()@@ -154,16 +253,33 @@ export function _addTransformerName(name, transformerType) {** INTERNAL API: use pluginApi.registerBehaviorTransformer or pluginApi.registerValueTransformer instead.*- * @param {string} transformerName the name of the transformer- * @param {string} transformerType the type of the transformer being registered- * @param {function} callback callback that will transform the value.- * @returns {boolean} True if the transformer exists, false otherwise.+ * @typeParam T - The value passed to the callback.+ * @typeParam C - Properties of the optional context object.+ * @param transformerName - the name of the transformer+ * @param transformerType - the type of the transformer being registered+ * @param callback - callback that will transform the value.+ * @returns True if the transformer exists, false if the name is unknown and the callback was ignored.*/+export function _registerTransformer<T, C extends object>(+ transformerName: string,+ transformerType: "VALUE",+ callback: AnyValueTransformer<T, C>+): boolean;+/**+ * Registers behavior middleware through the internal API.+ * @typeParam R - The expected behavior result, in addition to a possible void result.+ * @typeParam C - Properties supplied in the context before the calling instance is added.+ */+export function _registerTransformer<R, C extends object>(+ transformerName: string,+ transformerType: "BEHAVIOR",+ callback: BehaviorTransformer<R, C>+): boolean;export function _registerTransformer(- transformerName,- transformerType,- callback-) {+ transformerName: string,+ transformerType: TransformerType,+ callback: (...args: never[]) => unknown+): boolean {if (!transformerTypes[transformerType]) {throw new Error(`Invalid transformer type: ${transformerType}`);}@@ -210,11 +326,20 @@ export function _registerTransformer(return true;}-export function applyBehaviorTransformer(- transformerName,- defaultCallback,- context-) {+/**+ * Applies middleware in registration order, with the core implementation last.+ * @typeParam R - The result inferred from the default callback; middleware may also return void.+ * @typeParam C - Properties inferred from the supplied context object.+ */+export function applyBehaviorTransformer<+ R,+ C extends object = Record<string, unknown>,+>(+ this: unknown,+ transformerName: string,+ defaultCallback: DefaultBehaviorTransformer<R, C>,+ context?: C | null+): BehaviorTransformerResult<R> {const normalizedTransformerName = _normalizeTransformerName(transformerName,transformerTypes.BEHAVIOR@@ -237,14 +362,18 @@ export function applyBehaviorTransformer(}if (- typeof (context ?? undefined) !== "undefined" &&+ context != null &&!(typeof context === "object" && context.constructor === Object)) {throw `${prefix()}("${transformerName}", ...): context must be a simple JS object or nullish.`;}- const transformers = transformersRegistry.get(normalizedTransformerName);- const appliedContext = { ...context };+ // Registration and application must agree on the contract for this hook name.+ const transformers = transformersRegistry.get(normalizedTransformerName) as+ | BehaviorTransformer<R, C>[]+ | undefined;+ // Spreading an optional generic context loses C in TypeScript.+ const appliedContext = { ...context } as BehaviorTransformerContext<C>;if (!appliedContext._unstable_self && this) {appliedContext._unstable_self = this;}@@ -255,7 +384,7 @@ export function applyBehaviorTransformer(const callbackQueue = [...transformers, defaultCallback];- function nextCallback() {+ function nextCallback(): BehaviorTransformerResult<R> {const currentCallback = callbackQueue.shift();if (!currentCallback) {@@ -264,7 +393,10 @@ export function applyBehaviorTransformer(// do not surround the default implementation in the try ... catch blockif (currentCallback === defaultCallback) {- return currentCallback({ context: appliedContext });+ // Equality identifies the default callback, whose arguments omit next.+ return (currentCallback as DefaultBehaviorTransformer<R, C>)({+ context: appliedContext,+ });}try {@@ -292,20 +424,27 @@ export function applyBehaviorTransformer(/*** Apply a transformer to a value.*- * @param {string} transformerName - The name of the transformer applied- * @param {*} defaultValue - The default value- * @param {*} [context] - The optional context to pass to the transformer callbacks- * @param {Object} [opts] - Options for the transformer- * @param {boolean} [opts.mutable] - Flag indicating if the value should be mutated instead of returned- * @returns {*} The transformed value- * @throws {Error} If the transformer name does not exist or the context is invalid+ * @typeParam T - The result type, inferred from the default value; specify a wider type when needed.+ * @typeParam C - Properties inferred from the optional context object.+ *+ * @param transformerName - The name of the transformer applied+ * @param defaultValue - The default value+ * @param context - The optional context to pass to the transformer callbacks+ * @param opts - Options for the transformer+ * @throws If the transformer name does not exist or the context is invalid*/-export function applyValueTransformer(- transformerName,- defaultValue,- context,- opts = { mutable: false }-) {+export function applyValueTransformer<+ T,+ C extends object = Record<string, unknown>,+>(+ transformerName: string,+ defaultValue: T,+ context?: C | null,+ opts: {+ /** Mutate the original value and ignore callback return values. */+ mutable?: boolean;+ } | null = { mutable: false }+): T {const normalizedTransformerName = _normalizeTransformerName(transformerName,transformerTypes.VALUE@@ -322,7 +461,7 @@ export function applyValueTransformer(}if (- typeof (context ?? undefined) !== "undefined" &&+ context != null &&!(typeof context === "object" &&(context.constructor === Object || context.constructor === undefined)@@ -336,7 +475,10 @@ export function applyValueTransformer();}- const transformers = transformersRegistry.get(normalizedTransformerName);+ // Registration and application must agree on the contract for this hook name.+ const transformers = transformersRegistry.get(normalizedTransformerName) as+ | ValueTransformer<T, C>[]+ | undefined;if (!transformers) {return defaultValue;@@ -375,36 +517,30 @@ export function applyValueTransformer(* Apply a transformer to a mutable value.* The registered transformers should mutate the value instead of returning it.*- * @param {string} transformerName - The name of the transformer applied- * @param {*} defaultValue - The default value- * @param {*} [context] - The optional context to pass to the transformer callbacks- * @returns {*} The transformed value- * @throws {Error} If the transformer name does not exist or the context is invalid+ * @typeParam T - The original value's type, preserved in the returned reference.+ * @typeParam C - Properties inferred from the optional context object.+ *+ * @param transformerName - The name of the transformer applied+ * @param defaultValue - The default value+ * @param context - The optional context to pass to the transformer callbacks+ * @throws If the transformer name does not exist or the context is invalid*/-export function applyMutableValueTransformer(- transformerName,- defaultValue,- context-) {+export function applyMutableValueTransformer<+ T,+ C extends object = Record<string, unknown>,+>(transformerName: string, defaultValue: T, context?: C | null): T {return applyValueTransformer(transformerName, defaultValue, context, {mutable: true,});}-/**- * @typedef {Object} TransformerInfo- * @property {string} name - The normalized name of the transformer- * @property {string} source - The source of the transformer- */-/*** Find a transformer info by name, without considering the type*- * @param name the name of the transformer+ * @param name - the name of the transformer*- * @returns {TransformerInfo | null} info the transformer info or null if not found*/-function findTransformerInfoByName(name) {+function findTransformerInfoByName(name: string): TransformerInfo | null {for (const searchedType of Object.keys(transformerTypes)) {const searchedName = _normalizeTransformerName(name, searchedType);const source = validTransformerNames?.get(searchedName);@@ -420,24 +556,23 @@ function findTransformerInfoByName(name) {/*** Check if a transformer name exists*- * @param normalizedName the normalized name to check- * @returns {boolean} true if the transformer name exists, false otherwise+ * @param normalizedName - the normalized name to check*/-function transformerNameExists(normalizedName) {+function transformerNameExists(normalizedName: string): boolean {return validTransformerNames.has(normalizedName);}-///////// Testing helpers-/*** Check if a transformer was added*- * @param {string} name the name to check- * @param {string} type the type of the transformer+ * @param name - the name to check+ * @param type - the type of the transformer*- * @returns {boolean} true if a transformer with the given name and type exists, false otherwise*/-export function transformerWasAdded(name, type) {+export function transformerWasAdded(+ name: string,+ type: TransformerType+): boolean {return validTransformerNames.has(_normalizeTransformerName(name, type));}@@ -445,16 +580,15 @@ export function transformerWasAdded(name, type) {* Stores the initial state of `registryOpened` to allow the correct reset after a test that needs to manually* override the registry opened state finishes running.*- * @type {boolean | null}*/-let testRegistryOpenedState = null; // initially set to null bto allow testing if it was initialized+let testRegistryOpenedState: boolean | null = null;/*** Opens the transformers registry for registration** USE ONLY FOR TESTING PURPOSES.*/-export function acceptNewTransformerNames() {+export function acceptNewTransformerNames(): void {if (!isTesting()) {throw new Error("Use `acceptNewTransformerNames` only in tests.");}@@ -471,7 +605,7 @@ export function acceptNewTransformerNames() {** USE ONLY FOR TESTING PURPOSES.*/-export function acceptTransformerRegistrations() {+export function acceptTransformerRegistrations(): void {if (!isTesting()) {throw new Error("Use `acceptTransformerRegistrations` only in tests.");}@@ -488,7 +622,7 @@ export function acceptTransformerRegistrations() {** USE ONLY FOR TESTING PURPOSES.*/-export function resetTransformers() {+export function resetTransformers(): void {if (!isTesting()) {throw new Error("Use `resetTransformers` only in tests.");}@@ -506,7 +640,7 @@ export function resetTransformers() {/*** Clears all transformer names registered using the plugin API*/-function clearPluginTransformers() {+function clearPluginTransformers(): void {validTransformerNames = new Map([...validTransformerNames].filter(([, type]) => type === CORE_TRANSFORMER));@@ -519,6 +653,6 @@ function clearPluginTransformers() {** USE ONLY FOR TESTING PURPOSES.*/-export function disableThrowingApplyExceptionOnTests() {+export function disableThrowingApplyExceptionOnTests(): void {skipApplyExceptionOnTests = true;}diff --git a/frontend/discourse/type-tests/transformers/transformer-test.ts b/frontend/discourse/type-tests/transformers/transformer-test.tsnew file mode 100644index 00000000000..c90fdde3f86--- /dev/null+++ b/frontend/discourse/type-tests/transformers/transformer-test.ts@@ -0,0 +1,158 @@+import { expectTypeOf } from "expect-type";+import { withPluginApi } from "discourse/lib/plugin-api";+import {+ _registerTransformer,+ applyBehaviorTransformer,+ applyMutableValueTransformer,+ applyValueTransformer,+ type BehaviorTransformer,+ type BehaviorTransformerContext,+ type MutableValueTransformer,+ transformerTypes,+ type ValueTransformer,+} from "discourse/lib/transformer";++interface HookContext {+ categoryId: number;+}++const context: HookContext = { categoryId: 42 };+const labels: string[] = [];+expectTypeOf(applyValueTransformer("labels", labels, context)).toEqualTypeOf<+ string[]+>();+expectTypeOf(+ applyMutableValueTransformer("labels", labels, context)+).toEqualTypeOf<string[]>();+expectTypeOf(+ applyValueTransformer<string | false>("label", "default")+).toEqualTypeOf<string | false>();+expectTypeOf(+ applyValueTransformer("label", "default", null, null)+).toEqualTypeOf<string>();++const valueCallback: ValueTransformer<number, HookContext> = ({+ value,+ context: hookContext,+}) => {+ expectTypeOf(value).toEqualTypeOf<number>();+ expectTypeOf(hookContext).toEqualTypeOf<HookContext | null | undefined>();+ return value + (hookContext?.categoryId ?? 0);+};+expectTypeOf(+ _registerTransformer("count", transformerTypes.VALUE, valueCallback)+).toEqualTypeOf<boolean>();++const mutableCallback: MutableValueTransformer<string[], HookContext> = ({+ value,+}) => {+ value.push("added");+};+_registerTransformer("labels", transformerTypes.VALUE, mutableCallback);+_registerTransformer<number, HookContext>(+ "count",+ // @ts-expect-error a value callback must return the hook's value type; overload errors are reported here+ transformerTypes.VALUE,+ () => "wrong"+);++const behaviorCallback: BehaviorTransformer<Promise<number>, HookContext> = ({+ next,+ context: hookContext,+}) => {+ expectTypeOf(next()).toEqualTypeOf<+ Promise<number> | Promise<number | void> | void+ >();+ expectTypeOf(hookContext).toEqualTypeOf<+ BehaviorTransformerContext<HookContext>+ >();+ expectTypeOf(hookContext._unstable_self).toEqualTypeOf<unknown>();+ return next();+};+_registerTransformer("load", transformerTypes.BEHAVIOR, behaviorCallback);+_registerTransformer("stop", transformerTypes.BEHAVIOR, () => {});++const awaitingCallback: BehaviorTransformer<Promise<number>> = async ({+ next,+}) => await next();+const awaitingUnionCallback: BehaviorTransformer<+ Promise<number> | Promise<string>+> = async ({ next }) => await next();+const awaitingMixedCallback: BehaviorTransformer<+ number | Promise<string>+> = async ({ next }) => await next();+// @ts-expect-error a synchronous hook can't take async middleware+const asyncSync: BehaviorTransformer<number> = async ({ next }) => next();+export {+ asyncSync,+ awaitingCallback,+ awaitingMixedCallback,+ awaitingUnionCallback,+};++expectTypeOf(+ applyBehaviorTransformer(+ "load",+ ({ context: hookContext }) => {+ expectTypeOf(hookContext.categoryId).toEqualTypeOf<number>();+ return Promise.resolve(hookContext.categoryId);+ },+ context+ )+).toEqualTypeOf<Promise<number> | Promise<number | void> | void>();+expectTypeOf(applyBehaviorTransformer("stop", () => {})).toEqualTypeOf<void>();++withPluginApi((api) => {+ expectTypeOf(api.addValueTransformerName)+ .parameter(0)+ .toEqualTypeOf<string>();+ expectTypeOf(api.addBehaviorTransformerName)+ .parameter(0)+ .toEqualTypeOf<string>();+ expectTypeOf(+ api.registerValueTransformer("count", valueCallback)+ ).toEqualTypeOf<boolean>();+ expectTypeOf(+ api.registerBehaviorTransformer("load", behaviorCallback)+ ).toEqualTypeOf<boolean>();+ api.registerValueTransformer("labels", mutableCallback);+ api.registerValueTransformer<number, HookContext>(+ "count",+ ({ value, context: hookContext }) => {+ expectTypeOf(value).toEqualTypeOf<number>();+ expectTypeOf(hookContext).toEqualTypeOf<HookContext | null | undefined>();+ return value;+ }+ );+ api.registerValueTransformer<string[], HookContext>("labels", ({ value }) => {+ value.push("added");+ });+ api.registerValueTransformer<number, HookContext>(+ "count",+ // @ts-expect-error a value callback must return the hook's value type+ () => "wrong"+ );+ api.registerBehaviorTransformer<Promise<number>, HookContext>(+ "load",+ ({ next, context: hookContext }) => {+ expectTypeOf(next()).toEqualTypeOf<+ Promise<number> | Promise<number | void> | void+ >();+ expectTypeOf(hookContext.categoryId).toEqualTypeOf<number>();+ return next();+ }+ );+});++expectTypeOf<+ ValueTransformer<number, HookContext>+>().returns.toEqualTypeOf<number>();+expectTypeOf<+ MutableValueTransformer<string[], HookContext>+>().returns.toEqualTypeOf<void>();+expectTypeOf<MutableValueTransformer<string[], HookContext>>()+ .parameter(0)+ .toEqualTypeOf<Parameters<ValueTransformer<string[], HookContext>>[0]>();+expectTypeOf<+ ({ value }: { value: number; context: HookContext }) => string+>().not.toExtend<ValueTransformer<number, HookContext>>();