A platform for community discussion. Free, open, simple.
DEV: Convert the blocks API to TypeScript (#41635)
Sérgio Saquetim6b38e040f264
diff --git a/frontend/discourse-types/package.json b/frontend/discourse-types/package.jsonindex 27901d6f73a..818e9b8c15e 100644--- a/frontend/discourse-types/package.json+++ b/frontend/discourse-types/package.json@@ -42,6 +42,15 @@"./truth-helpers/*": {"types": "./declarations/truth-helpers/*.d.ts"},+ "./blocks": {+ "types": "./declarations/app/blocks/index.d.ts"+ },+ "./blocks/conditions": {+ "types": "./declarations/app/blocks/conditions/index.d.ts"+ },+ "./lib/blocks": {+ "types": "./declarations/app/lib/blocks/index.d.ts"+ },"./*": {"types": "./declarations/app/*.d.ts"}diff --git a/frontend/discourse/app/blocks/block-outlet.gjs b/frontend/discourse/app/blocks/block-outlet.gtssimilarity index 66%rename from frontend/discourse/app/blocks/block-outlet.gjsrename to frontend/discourse/app/blocks/block-outlet.gtsindex 66dad9b359c..097ce45e616 100644--- a/frontend/discourse/app/blocks/block-outlet.gjs+++ b/frontend/discourse/app/blocks/block-outlet.gts@@ -1,4 +1,3 @@-// @ts-check/*** BlockOutlet System*@@ -13,16 +12,16 @@import Component from "@glimmer/component";import { DEBUG } from "@glimmer/env";import { cached } from "@glimmer/tracking";+import type Owner from "@ember/owner";import curryComponent from "ember-curry-component";-/** @type {import("discourse/lib/blocks/-internals/components/block-layout-wrapper.gjs")} */+import type { BlockMetadata, LayoutEntry } from "discourse/blocks/types";import { wrapBlockLayout } from "discourse/lib/blocks/-internals/components/block-layout-wrapper";-/** @type {import("discourse/lib/blocks/-internals/components/block-outlet-inline-error.gjs")} */import BlockOutletInlineError from "discourse/lib/blocks/-internals/components/block-outlet-inline-error";-/** @type {import("discourse/lib/blocks/-internals/components/block-outlet-root-container.gjs")} */import BlockOutletRootContainer from "discourse/lib/blocks/-internals/components/block-outlet-root-container";import {createDebugGhost,DEBUG_CALLBACK,+ type DebugGhostData,debugHooks,} from "discourse/lib/blocks/-internals/debug-hooks";import {@@ -31,45 +30,40 @@ import {getBlockMetadata,registerRootBlock,} from "discourse/lib/blocks/-internals/decorator";+import type { CreateChildBlockFn } from "discourse/lib/blocks/-internals/entry-processing";import {captureCallSite,raiseBlockError,} from "discourse/lib/blocks/-internals/error";import { isBlockRegistryFrozen } from "discourse/lib/blocks/-internals/registry/block";+import type {+ BlockClass,+ BlockComponent,+ BlockEntry,+ ChildBlockResult,+} from "discourse/lib/blocks/-internals/types";import { applyArgDefaults } from "discourse/lib/blocks/-internals/utils";import { validateLayout } from "discourse/lib/blocks/-internals/validation/layout";import { isRailsTesting, isTesting } from "discourse/lib/environment";import { buildArgsWithDeprecations } from "discourse/lib/outlet-args";import { BLOCK_OUTLETS } from "discourse/lib/registry/block-outlets";+import type Blocks from "discourse/services/blocks";import DAsyncContent from "discourse/ui-kit/d-async-content";-/**- * A block entry in a layout configuration.- *- * @typedef {Object} LayoutEntry- * @property {typeof Component | string} block - The block component class (must use @block decorator) or a registered block name string.- * @property {Object} [args] - Args to pass to the block component.- * @property {string|string[]} [classNames] - Additional CSS classes for the block wrapper.- * @property {Array<LayoutEntry>} [children] - Nested block entries (only for container blocks).- * @property {Array<Object>|Object} [conditions] - Conditions that must pass for block to render.- * @property {Object} [containerArgs] - Args passed from parent container's childArgs.- */-/*** Maps outlet names to their registered outlet layouts.* Each outlet can have exactly one layout registered.** DO NOT EXPORT THIS MAP to prevent layouts bypassing the validation steps- *- * @type {Map<string, {validatedLayout: Promise<Array<Object>>}>}*/-const outletLayouts = new Map();+const outletLayouts = new Map<+ string,+ { validatedLayout: Promise<BlockEntry[]> }+>();/*** Counter for generating stable entry keys.* Incremented for each block entry when a layout is registered via `_renderBlocks()`.- *- * @type {number}*/let nextEntryKey = 0;@@ -82,16 +76,15 @@ let nextEntryKey = 0;** Keys are assigned at registration time (in `_renderBlocks()`) rather than* render time, ensuring they survive the shallow cloning in `BlockOutletRootContainer#preprocessEntries`.- *- * @param {Array<Object>} entries - The block entries to process.*/-function assignStableKeys(entries) {+function assignStableKeys(entries: BlockEntry[]): void {for (const entry of entries) {entry.__stableKey = nextEntryKey++;// Recursively assign keys to children- if (entry.children?.length) {- assignStableKeys(entry.children);+ const children = entry.children;+ if (children?.length) {+ assignStableKeys(children);}}}@@ -101,7 +94,7 @@ function assignStableKeys(entries) {** USE ONLY FOR TESTING PURPOSES.*/-export function _resetOutletLayoutsForTesting() {+export function _resetOutletLayoutsForTesting(): void {if (DEBUG) {outletLayouts.clear();nextEntryKey = 0;@@ -113,10 +106,11 @@ export function _resetOutletLayoutsForTesting() {* Allows tests to access validation promises to verify error handling.** USE ONLY FOR TESTING PURPOSES.- *- * @returns {Map<string, {validatedLayout: Promise<Array<Object>>}>} The outlet layouts map.*/-export function _getOutletLayouts() {+export function _getOutletLayouts(): Map<+ string,+ { validatedLayout: Promise<BlockEntry[]> }+> {if (DEBUG) {return outletLayouts;}@@ -126,13 +120,12 @@ export function _getOutletLayouts() {/*** Resolves the decoratorClassNames value from block metadata.* Handles string, array, and function forms.- *- * @param {Object} metadata - The block metadata object.- * @param {Object} args - The block's args (passed to function form).- * @returns {string|null} The resolved class names string, or null if none.*/-function resolveDecoratorClassNames(metadata, args) {- const value = metadata.decoratorClassNames;+function resolveDecoratorClassNames(+ metadata: BlockMetadata | null,+ args: Record<string, unknown>+): string | null {+ const value = metadata?.decoratorClassNames;if (value == null) {return null;}@@ -150,35 +143,18 @@ function resolveDecoratorClassNames(metadata, args) {* Curries the component with all necessary args and wraps all blocks* in a layout wrapper for consistent styling.*- * @param {Object} entry - The block entry- * @param {import("discourse/lib/blocks/-internals/registry/block").BlockClass} entry.block - The block component class- * @param {Object} [entry.args] - Args to pass to the block- * @param {Object} [entry.containerArgs] - Container args for parent's childArgs schema- * @param {string} [entry.classNames] - Additional CSS classes- * @param {string} [entry.id] - Unique identifier for BEM styling and targeting- * @param {import("@ember/owner").default} owner - The application owner- * @param {Object} [debugContext] - Debug context for visual overlay- * @param {string} [debugContext.displayHierarchy] - Where the block is rendered (for tooltip display)- * @param {string} [debugContext.containerPath] - Container's full path (for children's __hierarchy)- * @param {Object} [debugContext.conditions] - The block's conditions- * @param {Object} [debugContext.outletArgs] - Outlet args for debug display- * @param {string} [debugContext.key] - Stable unique key for this block- * @param {string} [debugContext.outletName] - The outlet name for wrapper class generation- * @param {Array<import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult>} [debugContext.processedChildren] - Pre-processed children- * @returns {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult}- * An object containing the curried block component, any containerArgs- * provided in the block entry, and a stable unique key for list rendering.- * The containerArgs are values required by the parent container's childArgs- * schema, accessible to the parent but not to the child block itself.+ * An object containing the curried block component, any containerArgs+ * provided in the block entry, and a stable unique key for list rendering.+ * The containerArgs are values required by the parent container's childArgs+ * schema, accessible to the parent but not to the child block itself.*/-function createChildBlock(entry, owner, debugContext = {}) {- const {- block: ComponentClass,- args = {},- containerArgs,- classNames,- id,- } = entry;+const createChildBlock: CreateChildBlockFn = (entry, owner, debugContext) => {+ const { block: rawBlock, args = {}, containerArgs, classNames, id } = entry;++ // Always a class here: callers only invoke this after `tryResolveBlock` has+ // resolved a by-name reference.+ const ComponentClass = rawBlock as BlockClass;+const blockMeta = getBlockMetadata(ComponentClass);const isContainer = blockMeta?.isContainer ?? false;@@ -196,12 +172,17 @@ function createChildBlock(entry, owner, debugContext = {}) {: debugContext.displayHierarchy,});- // Curry the component with pre-bound args so it can be rendered- // without knowing its configuration details- const curried = curryComponent(ComponentClass, blockArgs, owner);+ // Curry the component with pre-bound args so it can be rendered without+ // knowing its configuration details; the deliberately-opaque `BlockClass`+ // isn't glint-invokable, so assert the known renderable result.+ const curried = curryComponent(+ ComponentClass,+ blockArgs,+ owner+ ) as unknown as BlockComponent;// All blocks are wrapped for consistent styling- let wrappedComponent = wrapBlockLayout(+ let wrappedComponent: BlockComponent = wrapBlockLayout({name: blockMeta?.blockName,namespace: blockMeta?.namespace,@@ -235,28 +216,24 @@ function createChildBlock(entry, owner, debugContext = {}) {outletName: debugContext.displayHierarchy,outletArgs: debugContext.outletArgs,}- );+ ) as DebugGhostData | null | undefined;if (debugResult?.Component) {wrappedComponent = debugResult.Component;}}- /** @type {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult} */- const result = {+ const result: ChildBlockResult = {Component: wrappedComponent,containerArgs,key: debugContext.key,+/*** Returns a ghost version of this child with a custom failure reason.** Used by container blocks (like head) that choose not to render some children* but want to show them as ghosts in debug mode with an explanation.- *- * @param {string} reason - The failure reason to display in the ghost overlay.- * @returns {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult|null}- * A ghost child block result, or null if debug mode is disabled.*/- asGhost(reason) {+ asGhost(reason: string): ChildBlockResult | null {const ghostResult = createDebugGhost({name: blockMeta?.blockName,@@ -273,8 +250,7 @@ function createChildBlock(entry, owner, debugContext = {}) {);if (ghostResult) {- /** @type {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult} */- const ghostChild = {+ const ghostChild: ChildBlockResult = {Component: ghostResult.Component,containerArgs,key: `${debugContext.key}:ghost`,@@ -289,7 +265,7 @@ function createChildBlock(entry, owner, debugContext = {}) {};return result;-}+};/*** Registers an outlet layout (array of block entries) for a named outlet.@@ -301,13 +277,9 @@ function createChildBlock(entry, owner, debugContext = {}) {* @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @param {string} outletName - The outlet identifier (must be in BLOCK_OUTLETS).- * @param {Array<LayoutEntry>} layout - Array of block entries.- * @param {Object} [owner] - The application owner for service lookup (passed from plugin API).- * @param {Error|null} [callSiteError] - Pre-captured error for source-mapped stack traces.+ * @param owner - The application owner for service lookup (passed from plugin API).+ * @param callSiteError - Pre-captured error for source-mapped stack traces.* When called via api.renderBlocks(), this is captured there to exclude the PluginApi wrapper.- * @returns {Promise<Array<Object>>} Promise resolving to the validated layout array.- * @throws {Error} If validation fails or outlet already has a layout.** @example* ```js@@ -331,7 +303,12 @@ function createChildBlock(entry, owner, debugContext = {}) {* ]);* ```*/-export function _renderBlocks(outletName, layout, owner, callSiteError = null) {+export function _renderBlocks(+ outletName: string,+ layout: LayoutEntry[],+ owner?: Owner,+ callSiteError: Error | null = null+): Promise<BlockEntry[]> {if (!callSiteError) {callSiteError = captureCallSite(_renderBlocks);}@@ -357,10 +334,12 @@ export function _renderBlocks(outletName, layout, owner, callSiteError = null) {);}- const blocksService = owner?.lookup("service:blocks");+ const blocksService = owner?.lookup("service:blocks") as Blocks | undefined;- // Assign stable keys to all entries- assignStableKeys(layout);+ // Tagging entries in place with `__stableKey` turns the author-facing+ // `LayoutEntry[]` into the internal `BlockEntry[]` shape used from here on.+ const trackedLayout = layout as unknown as BlockEntry[];+ assignStableKeys(trackedLayout);// Validate layout asynchronouslyconst validatedLayout = validateLayout(@@ -369,7 +348,7 @@ export function _renderBlocks(outletName, layout, owner, callSiteError = null) {blocksService,"", // parentPath - empty so paths start with array index like [0]callSiteError // Error object for source-mapped call site- ).then(() => layout);+ ).then(() => trackedLayout);// Store layout with validation promise for potential future useoutletLayouts.set(outletName, { validatedLayout });@@ -381,27 +360,39 @@ export function _renderBlocks(outletName, layout, owner, callSiteError = null) {* Checks if a layout has been registered for a given outlet.** @internal This is an internal API. Use the `blocks` service's `hasLayout()` method instead.- *- * @param {string} outletName - The outlet identifier to check.- * @returns {boolean} True if a layout is registered for this outlet.*/-export function _hasLayout(outletName) {+export function _hasLayout(outletName: string): boolean {return outletLayouts.has(outletName);}-/**- * Component signature for BlockOutlet.- *- * @typedef {Object} BlockOutletSignature- * @property {Object} Args- * @property {string} Args.name - The outlet name (must be in BLOCK_OUTLETS registry).- * @property {Object} [Args.outletArgs] - Arguments to pass to blocks rendered in this outlet.- * @property {Object} [Args.deprecatedArgs] - Deprecated args with deprecation warnings.- * @property {Object} Blocks- * @property {[hasLayout: boolean]} Blocks.before - Yields hasLayout flag before content.- * @property {[hasLayout: boolean]} Blocks.after - Yields hasLayout flag after content.- * @property {[error: Error]} Blocks.error - Yields error when validation fails.- */+interface BlockOutletSignature {+ Args: {+ // The outlet name (must be in BLOCK_OUTLETS registry).+ name: string;+ // Arguments to pass to blocks rendered in this outlet.+ outletArgs?: Record<string, unknown>;+ // Deprecated args with deprecation warnings.+ deprecatedArgs?: Record<string, unknown>;+ };+ Blocks: {+ // Yields hasLayout flag before content.+ before?: [hasLayout: boolean];+ // Yields hasLayout flag after content.+ after?: [hasLayout: boolean];+ // Yields error when validation fails.+ error?: [error: Error];+ };+}++/** The signature `debugHooks.outletInfoComponent` renders with, when set. */+interface OutletInfoSignature {+ Args: {+ outletName: string;+ blockCount: number;+ outletArgs: Record<string, unknown>;+ error: Error | null;+ };+}/*** Root component for rendering registered blocks in a designated outlet.@@ -418,8 +409,6 @@ export function _hasLayout(outletName) {* @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @extends {Component<BlockOutletSignature>}- ** @example* ```hbs* <BlockOutlet @name="homepage-blocks">@@ -432,16 +421,14 @@ export function _hasLayout(outletName) {* ```*/@block("block-outlet", { container: true })-export default class BlockOutlet extends Component {+export default class BlockOutlet extends Component<BlockOutletSignature> {/*** The outlet name, locked at construction time.* This prevents dynamic name changes which could cause inconsistent rendering.- *- * @type {string}*/- #name;+ #name: string;- constructor(owner, args) {+ constructor(owner: Owner, args: BlockOutletSignature["Args"]) {super(owner, args);// Lock the name at construction to prevent dynamic changes@@ -454,17 +441,25 @@ export default class BlockOutlet extends Component {}}- get validatedLayout() {+ get validatedLayout(): Promise<BlockEntry[]> | undefined {return outletLayouts.get(this.#name)?.validatedLayout;}/*** Processes block entries and returns renderable components.- *- * @returns {Promise<{rawChildren: Array<Object>, showGhosts: boolean, showVisualOverlay: boolean, isLoggingEnabled: boolean}>|undefined}*/@cached- get children() {+ get children():+ | Promise<+ | {+ rawChildren: BlockEntry[];+ showGhosts: boolean;+ showVisualOverlay: boolean;+ isLoggingEnabled: boolean;+ }+ | undefined+ >+ | undefined {// We need to track the state outside the promise contexts to force the children to be rendered when// the user enables the debuggingconst showGhosts = debugHooks.isGhostBlocksEnabled;@@ -492,7 +487,7 @@ export default class BlockOutlet extends Component {return { rawChildren, showGhosts, showVisualOverlay, isLoggingEnabled };})- .catch((error) => {+ .catch((error: unknown) => {if (isTesting() || isRailsTesting()) {setTimeout(() => {throw error;@@ -515,21 +510,24 @@ export default class BlockOutlet extends Component {/*** The locked outlet name, used for CSS class generation and config lookup.- *- * @returns {string}*/- get outletName() {+ get outletName(): string {return this.#name;}/*** The component to render for outlet boundary debug info.* Returns the OutletInfo component when debug mode is enabled, null otherwise.- *- * @returns {typeof Component<{outletName: string, blockCount: number, outletArgs: object, error: Error}>|null}*/- get OutletInfoComponent() {- return debugHooks.outletInfoComponent;+ get OutletInfoComponent():+ | typeof Component<OutletInfoSignature>+ | null+ | undefined {+ // Narrow the hook's bare `typeof Component` to the shape rendered here.+ return debugHooks.outletInfoComponent as+ | typeof Component<OutletInfoSignature>+ | null+ | undefined;}/**@@ -541,19 +539,19 @@ export default class BlockOutlet extends Component {** Deprecated args trigger a deprecation warning when accessed, helping* migrate consumers away from renamed or removed outlet args.- *- * @returns {Object} Combined args object with lazy property getters*/@cached- get outletArgsWithDeprecations() {+ get outletArgsWithDeprecations(): Record<string, unknown> {if (!this.args.deprecatedArgs) {return this.args.outletArgs || {};}+ // `buildArgsWithDeprecations` is authored in untyped `.js`; its actual+ // runtime return is a plain object keyed by the combined arg names.return buildArgsWithDeprecations(this.args.outletArgs || {},this.args.deprecatedArgs,{ outletName: this.#name }- );+ ) as Record<string, unknown>;}<template>@@ -581,27 +579,31 @@ export default class BlockOutlet extends Component {</:loading><:content as |layout|>- {{#let- (component- BlockOutletRootContainer- outletName=this.outletName- outletArgs=this.outletArgsWithDeprecations- rawChildren=layout.rawChildren- showGhosts=layout.showGhosts- showVisualOverlay=layout.showVisualOverlay- isLoggingEnabled=layout.isLoggingEnabled- createChildBlockFn=createChildBlock- )- as |ChildrenContainer|- }}- {{#if OutletInfo}}- <OutletInfo @blockCount={{layout.rawChildren.length}}>+ {{! layout is only undefined when no blocks passed validation, in+ which case the :empty block below renders instead }}+ {{#if layout}}+ {{#let+ (component+ BlockOutletRootContainer+ outletName=this.outletName+ outletArgs=this.outletArgsWithDeprecations+ rawChildren=layout.rawChildren+ showGhosts=layout.showGhosts+ showVisualOverlay=layout.showVisualOverlay+ isLoggingEnabled=layout.isLoggingEnabled+ createChildBlockFn=createChildBlock+ )+ as |ChildrenContainer|+ }}+ {{#if OutletInfo}}+ <OutletInfo @blockCount={{layout.rawChildren.length}}>+ <ChildrenContainer />+ </OutletInfo>+ {{else}}<ChildrenContainer />- </OutletInfo>- {{else}}- <ChildrenContainer />- {{/if}}- {{/let}}+ {{/if}}+ {{/let}}+ {{/if}}</:content><:error as |error|>diff --git a/frontend/discourse/app/blocks/builtin/block-group.gjs b/frontend/discourse/app/blocks/builtin/block-group.gtssimilarity index 75%rename from frontend/discourse/app/blocks/builtin/block-group.gjsrename to frontend/discourse/app/blocks/builtin/block-group.gtsindex 86724fef78f..1054c6d77ba 100644--- a/frontend/discourse/app/blocks/builtin/block-group.gjs+++ b/frontend/discourse/app/blocks/builtin/block-group.gts@@ -1,10 +1,16 @@-// @ts-checkimport Component from "@glimmer/component";import { block } from "discourse/blocks";+import type { ChildBlockResult } from "discourse/lib/blocks/-internals/types";++interface GroupedBlocksSignature {+ Args: {+ children: ChildBlockResult[];+ };+}/*** A container block that groups multiple children blocks together.- * Rendered children are pre-processed by the block outlet system and passed via the @children arg.+ * Rendered children are pre-processed by the block outlet system and passed via the `@children` arg.** The system wrapper provides standard BEM classes:* - `{outletName}__block-container` - Standard container class@@ -18,7 +24,7 @@ import { block } from "discourse/blocks";container: true,description: "Groups multiple children blocks together",})-export default class GroupedBlocks extends Component {+export default class GroupedBlocks extends Component<GroupedBlocksSignature> {<template>{{#each @children key="key" as |child|}}<child.Component />diff --git a/frontend/discourse/app/blocks/builtin/block-head.gjs b/frontend/discourse/app/blocks/builtin/block-head.gtssimilarity index 81%rename from frontend/discourse/app/blocks/builtin/block-head.gjsrename to frontend/discourse/app/blocks/builtin/block-head.gtsindex e9611ca0aad..992211e0ba3 100644--- a/frontend/discourse/app/blocks/builtin/block-head.gjs+++ b/frontend/discourse/app/blocks/builtin/block-head.gts@@ -1,10 +1,17 @@-// @ts-checkimport Component from "@glimmer/component";import { service } from "@ember/service";import { block } from "discourse/blocks";+import type { ChildBlockResult } from "discourse/lib/blocks/-internals/types";+import type Blocks from "discourse/services/blocks";import { eq } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";+interface HeadBlockSignature {+ Args: {+ children: ChildBlockResult[];+ };+}+/*** A container block that renders only its first visible child.*@@ -23,7 +30,7 @@ import { i18n } from "discourse-i18n";* not display children 2+, we are responsible for:** 1. Rendering ghosts for children that failed their own conditions- * (already ghost blocks in @children)+ * (already ghost blocks in `@children`)* 2. Converting children that passed conditions but aren't rendered* (because another sibling was first) into ghosts with an explanation*@@ -58,27 +65,31 @@ import { i18n } from "discourse-i18n";container: true,description: "Renders only the first child whose conditions pass",})-export default class HeadBlock extends Component {- @service blocks;+export default class HeadBlock extends Component<HeadBlockSignature> {+ @service declare blocks: Blocks;/*** Children that passed their conditions and could be rendered.- *- * @returns {Array<import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult>}*/- get renderableChildren() {+ get renderableChildren(): ChildBlockResult[] {return this.args.children?.filter((c) => !c.isGhost) ?? [];}/*** The one child we actually render (first that passed conditions).- *- * @returns {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult|undefined}*/- get firstChild() {+ get firstChild(): ChildBlockResult | undefined {return this.renderableChildren[0];}+ /**+ * Converts a passed-over sibling into a ghost with the given reason,+ * for the debug visual overlay.+ */+ ghostify(child: ChildBlockResult, reason: string): ChildBlockResult | null {+ return child.asGhost(reason);+ }+<template>{{#if this.blocks.showGhosts}}{{!@@ -97,8 +108,8 @@ export default class HeadBlock extends Component {{{else}}{{! Passed conditions but hidden by priority - convert to ghost }}{{#let- (child.asGhost- (i18n "js.blocks.ghost_reasons.head_hidden_tail_hint")+ (this.ghostify+ child (i18n "js.blocks.ghost_reasons.head_hidden_tail_hint"))as |ghostChild|}}diff --git a/frontend/discourse/app/blocks/builtin/index.js b/frontend/discourse/app/blocks/builtin/index.tssimilarity index 63%rename from frontend/discourse/app/blocks/builtin/index.jsrename to frontend/discourse/app/blocks/builtin/index.tsindex 884a6bdc2b4..359dcdb2d3f 100644--- a/frontend/discourse/app/blocks/builtin/index.js+++ b/frontend/discourse/app/blocks/builtin/index.ts@@ -9,24 +9,24 @@* ## Adding a New Built-in Block** 1. Create the block component in `app/blocks/builtin/` with the `@block` decorator:- * ```javascript- * import Component from "@glimmer/component";- * import { block } from "discourse/blocks";*- * @block("my-block")- * export default class MyBlock extends Component {- * // ...- * }- * ```+ * ```javascript+ * import Component from "@glimmer/component";+ * import { block } from "discourse/blocks";+ *+ * @block("my-block")+ * export default class MyBlock extends Component {+ * // ...+ * }+ * ```** 2. Add an export to this file:- * ```javascript- * export { default as MyBlock } from "discourse/blocks/builtin/my-block";- * ```*- * The initializer automatically picks up any new exports and registers them.+ * ```javascript+ * export { default as MyBlock } from "discourse/blocks/builtin/my-block";+ * ```*- * @module discourse/blocks/builtin+ * The initializer automatically picks up any new exports and registers them.*/export { default as BlockHead } from "./block-head";export { default as BlockGroup } from "./block-group";diff --git a/frontend/discourse/app/blocks/conditions/condition.js b/frontend/discourse/app/blocks/conditions/condition.tssimilarity index 60%rename from frontend/discourse/app/blocks/conditions/condition.jsrename to frontend/discourse/app/blocks/conditions/condition.tsindex c2ad3fb0172..8b8cc5f55aa 100644--- a/frontend/discourse/app/blocks/conditions/condition.js+++ b/frontend/discourse/app/blocks/conditions/condition.ts@@ -1,5 +1,65 @@-// @ts-check+import type { ArgSchema, BlockConstraints } from "discourse/blocks/types";import { getByPath } from "discourse/lib/blocks";+import type { DebugLoggerInterface } from "discourse/lib/blocks/-internals/debug-hooks";++/**+ * Declares how a condition handles the `source` parameter.+ *+ * - `"none"`: `source` parameter is disallowed.+ * - `"outletArgs"`: `source` must be `@outletArgs.propertyPath`; the base+ * class resolves it via outlet args.+ * - `"object"`: `source` is passed directly as an object (e.g., for settings).+ */+export type ConditionSourceType = "none" | "outletArgs" | "object";++/**+ * Custom validation function for a condition, run at registration time+ * against the condition's resolved args. Returns an error message (or+ * messages), or `null`/`undefined` when the args are valid.+ */+export type ConditionValidateFn = (+ args: Record<string, unknown>+) => string | string[] | null | undefined;++/**+ * Evaluation context passed to `evaluate()`, `resolveSource()`, and+ * `getResolvedValueForLogging()`. Built by the block render pipeline (and,+ * for nested route params, by the route condition itself).+ */+export interface ConditionContext {+ /** Whether debug logging is enabled for this evaluation. */+ debug?: boolean;++ /** Outlet args passed to the block, used to resolve `@outletArgs.*` sources. */+ outletArgs?: Record<string, unknown>;++ /** Current nesting depth, used for debug log indentation. */+ _depth?: number;++ /** Logger interface for nested debug logging (used by the route condition+ * to log its OR/NOT/param sub-checks). */+ logger?: DebugLoggerInterface | null;+}++/**+ * Resolved-value info returned by `getResolvedValueForLogging()`, shown in+ * the dev-tools debug overlay. Conditions that don't resolve a value (e.g.+ * because `source` wasn't provided) return `undefined` instead.+ */+export interface ConditionResolvedValue {+ /** Always `true` when a value was resolved. */+ hasValue: true;++ /** The resolved value, for conditions that resolve via `source`. */+ value?: unknown;++ /** An additional annotation, e.g. a "did you mean" note for an unknown setting. */+ note?: string;++ /** An alternate formatted payload, for conditions with non-`source`+ * resolution (e.g. the `outletArg` condition's `path`/`actual`/`configured` triple). */+ formatted?: unknown;+}/*** Base class for all block conditions.@@ -36,8 +96,6 @@ import { getByPath } from "discourse/lib/blocks";* @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @class BlockCondition- ** @example* ```javascript* import { blockCondition, BlockCondition } from "discourse/blocks/conditions";@@ -75,10 +133,8 @@ export class BlockCondition {** This property is defined by the `@blockCondition` decorator and should not* be set directly. Pass the `type` option to the decorator instead.- *- * @type {string}*/- static type;+ declare static type: string;/*** Declares how this condition handles the `source` parameter.@@ -89,10 +145,8 @@ export class BlockCondition {** This property is defined by the `@blockCondition` decorator and should not* be set directly. Pass the `sourceType` option to the decorator instead.- *- * @type {"none" | "outletArgs" | "object"}*/- static sourceType = "none";+ static sourceType: ConditionSourceType = "none";/*** Arg schema definitions for this condition.@@ -100,10 +154,8 @@ export class BlockCondition {* This property is defined by the `@blockCondition` decorator and should not* be overridden directly. The decorator creates a non-configurable getter* that returns a frozen object.- *- * @type {Object}*/- static argsSchema;+ declare static argsSchema: Readonly<Record<string, ArgSchema>>;/*** Cross-arg constraint definitions for this condition.@@ -111,10 +163,8 @@ export class BlockCondition {* This property is defined by the `@blockCondition` decorator and should not* be overridden directly. The decorator creates a non-configurable getter* that returns a frozen object or undefined.- *- * @type {Object|undefined}*/- static constraints;+ declare static constraints: Readonly<BlockConstraints> | undefined;/*** Custom validation function for this condition.@@ -122,10 +172,8 @@ export class BlockCondition {* This property is defined by the `@blockCondition` decorator and should not* be overridden directly. The decorator creates a non-configurable getter* that returns the validate function or undefined.- *- * @type {Function|undefined}*/- static validateFn;+ declare static validateFn: ConditionValidateFn | undefined;/*** Valid argument keys for this condition.@@ -135,10 +183,8 @@ export class BlockCondition {** The `source` key is automatically added by the decorator when* `sourceType !== "none"`.- *- * @type {readonly string[]}*/- static validArgKeys;+ declare static validArgKeys: readonly string[];/*** Resolves the `source` parameter value based on the condition's `sourceType`.@@ -147,28 +193,32 @@ export class BlockCondition {* and retrieves the corresponding value from `context.outletArgs`.* - `sourceType: "object"`: Returns the `source` value directly.*- * @param {Object} args - The condition arguments containing `source`.- * @param {Object} context - Evaluation context containing `outletArgs`.- * @param {Object} [context.outletArgs] - The outlet args passed to the block.- * @returns {*} The resolved value from outlet args, or undefined if not found.+ * @param args - The condition arguments containing `source`.+ * @param context - Evaluation context containing `outletArgs`.+ * @returns The resolved value from outlet args, or undefined if not found.*/- resolveSource(args, context) {+ resolveSource(+ args: Record<string, unknown>,+ context?: ConditionContext+ ): unknown {const { source } = args;if (!source) {return undefined;}- // @ts-ignore - Static property defined on subclasses- const sourceType = this.constructor.sourceType;+ // Read via the constructor's statics, which the `@blockCondition`+ // decorator sets on every concrete subclass (never on this base class).+ const sourceType = (this.constructor as typeof BlockCondition).sourceType;if (sourceType === "object") {return source;}if (sourceType === "outletArgs") {- // Extract path after "@outletArgs."- const path = source.replace(/^@outletArgs\./, "");+ // Extract path after "@outletArgs.". `source` is validated to be a+ // string in this format at registration time.+ const path = (source as string).replace(/^@outletArgs\./, "");return getByPath(context?.outletArgs, path);}@@ -178,21 +228,22 @@ export class BlockCondition {/*** Default source value when `source` parameter is not provided.* Override in subclasses to provide a fallback (e.g., currentUser, siteSettings).- *- * @type {*}*/- get defaultSource() {+ get defaultSource(): unknown {return undefined;}/*** Resolves the source value, falling back to defaultSource when not provided.*- * @param {Object} args - The condition arguments.- * @param {Object} [context] - Evaluation context.- * @returns {*} The resolved source or defaultSource.+ * @param args - The condition arguments.+ * @param context - Evaluation context.+ * @returns The resolved source or defaultSource.*/- getSourceValue(args, context) {+ getSourceValue(+ args: Record<string, unknown>,+ context?: ConditionContext+ ): unknown {return args.source !== undefined? this.resolveSource(args, context): this.defaultSource;@@ -206,15 +257,12 @@ export class BlockCondition {* multiple times during a single render cycle (e.g., when debug logging* is enabled), and should not have side effects.*- * @param {Object} args - The condition arguments from the layout entry.- * @param {Object} [context] - Evaluation context from the blocks service.- * @param {boolean} [context.debug] - Whether debug logging is enabled.- * @param {Object} [context.outletArgs] - Outlet args for source resolution.- * @param {number} [context._depth] - Current nesting depth for logging.- * @returns {boolean} True if condition passes, false otherwise.+ * @param args - The condition arguments from the layout entry.+ * @param context - Evaluation context from the blocks service.+ * @returns True if condition passes, false otherwise.*/- // eslint-disable-next-line no-unused-vars- evaluate(args, context) {+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ evaluate(args: Record<string, unknown>, context?: ConditionContext): boolean {throw new Error(`${this.constructor.name} must implement evaluate()`);}@@ -226,12 +274,14 @@ export class BlockCondition {* For example, the `outletArg` condition uses a `path` parameter* to resolve values from outlet args.*- * @param {Object} args - The condition arguments from the layout entry.- * @param {Object} [context] - Evaluation context containing outletArgs.- * @returns {{ value: *, hasValue: true }|undefined} Object with resolved value,- * or undefined if this condition doesn't resolve values.+ * @param args - The condition arguments from the layout entry.+ * @param context - Evaluation context containing outletArgs.+ * @returns Object with resolved value, or undefined if this condition doesn't resolve values.*/- getResolvedValueForLogging(args, context) {+ getResolvedValueForLogging(+ args: Record<string, unknown>,+ context?: ConditionContext+ ): ConditionResolvedValue | undefined {// Default implementation returns resolved source if presentif (args.source !== undefined) {return { value: this.resolveSource(args, context), hasValue: true };diff --git a/frontend/discourse/app/blocks/conditions/decorator.js b/frontend/discourse/app/blocks/conditions/decorator.tssimilarity index 72%rename from frontend/discourse/app/blocks/conditions/decorator.jsrename to frontend/discourse/app/blocks/conditions/decorator.tsindex 822efe8a6bf..57032495db3 100644--- a/frontend/discourse/app/blocks/conditions/decorator.js+++ b/frontend/discourse/app/blocks/conditions/decorator.ts@@ -1,25 +1,32 @@-// @ts-check+import type { ArgSchema, BlockConstraints } from "discourse/blocks/types";import {MAX_BLOCK_NAME_LENGTH,parseBlockName,+ type ParsedBlockName,VALID_NAMESPACED_BLOCK_PATTERN,} from "discourse/lib/blocks/-internals/patterns";import { validateConditionArgsSchema } from "discourse/lib/blocks/-internals/validation/condition-args";import { validateConstraintsSchema } from "discourse/lib/blocks/-internals/validation/constraints";import { formatWithSuggestion } from "discourse/lib/string-similarity";-import { BlockCondition } from "./condition";+import {+ BlockCondition,+ type ConditionSourceType,+ type ConditionValidateFn,+} from "./condition";/*** Valid sourceType values for the decorator config.- * @constant {ReadonlyArray<string>}*/-const VALID_SOURCE_TYPES = Object.freeze(["none", "outletArgs", "object"]);+const VALID_SOURCE_TYPES: readonly ConditionSourceType[] = Object.freeze([+ "none",+ "outletArgs",+ "object",+]);/*** Valid config keys for the decorator.- * @constant {ReadonlyArray<string>}*/-const VALID_CONFIG_KEYS = Object.freeze([+const VALID_CONFIG_KEYS: readonly string[] = Object.freeze(["type","sourceType","args",@@ -31,22 +38,44 @@ const VALID_CONFIG_KEYS = Object.freeze([* WeakSet tracking decorated classes.* Private - only accessible via isDecoratedCondition().*/-const decoratedConditions = new WeakSet();+const decoratedConditions = new WeakSet<object>();/**- * Checks if a class was decorated with @blockCondition.+ * Checks if a class was decorated with `@blockCondition`.* Used by the block registration system to reject non-decorated classes.** @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @param {Function} ConditionClass - The class to check.- * @returns {boolean} True if the class was decorated.+ * @param ConditionClass - The class to check. Widened to `object` (rather than+ * a condition-class type) because this is also probed defensively before a+ * class is known to extend `BlockCondition`.+ * @returns True if the class was decorated.*/-export function isDecoratedCondition(ConditionClass) {+export function isDecoratedCondition(ConditionClass: object): boolean {return decoratedConditions.has(ConditionClass);}+/** Configuration accepted by the `@blockCondition` decorator. */+export interface BlockConditionConfig {+ /** Unique condition type identifier. */+ type: string;++ /** How the `source` parameter is handled. Defaults to `"none"`. */+ sourceType?: ConditionSourceType;++ /** Arg schema definitions (type, required, min, max, pattern, etc.).+ * Use `{ type: "any" }` to allow any type. */+ args?: Record<string, ArgSchema>;++ /** Cross-arg constraints (atLeastOne, exactlyOne, allOrNone, atMostOne). */+ constraints?: BlockConstraints;++ /** Custom validation function called at registration time. Receives the+ * args object, returns an error string/array or null. */+ validate?: ConditionValidateFn;+}+/*** Decorator to define a block condition with declarative arg validation.*@@ -57,17 +86,10 @@ export function isDecoratedCondition(ConditionClass) {* @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @param {Object} config - Condition configuration.- * @param {string} config.type - Unique condition type identifier.- * @param {"none"|"outletArgs"|"object"} [config.sourceType="none"] - How source parameter is handled.- * @param {Object} [config.args={}] - Arg schema definitions (type, required, min, max, pattern, etc.).- * Use `{ type: "any" }` to allow any type.- * @param {Object} [config.constraints] - Cross-arg constraints (atLeastOne, exactlyOne, allOrNone, atMostOne).- * @param {Function} [config.validate] - Custom validation function called at registration time.- * Receives args object, returns error string/array or null.- * @throws {Error} If config is invalid or class doesn't extend BlockCondition.+ * @throws Error If config is invalid or class doesn't extend BlockCondition.** @example+ * ```javascript* import { blockCondition, BlockCondition } from "discourse/blocks/conditions";** @blockCondition({@@ -90,8 +112,10 @@ export function isDecoratedCondition(ConditionClass) {* @service currentUser;* evaluate(args, context) { ... }* }+ * ```** @example+ * ```javascript* // With constraints* @blockCondition({* type: "setting",@@ -106,8 +130,11 @@ export function isDecoratedCondition(ConditionClass) {* atMostOne: ["enabled", "equals", "includes"],* },* })+ * ```*/-export function blockCondition(config) {+export function blockCondition(+ config: BlockConditionConfig+): <T extends typeof BlockCondition>(TargetClass: T) => T {const {type,sourceType = "none",@@ -137,8 +164,10 @@ export function blockCondition(config) {);}- // Parse the type to extract namespace components- const parsed = parseBlockName(type);+ // Parse the type to extract namespace components. `type` is regex-validated+ // above, so `parseBlockName` is guaranteed to resolve one of its three+ // namespace formats and never return null here.+ const parsed = parseBlockName(type) as ParsedBlockName;// Validate sourceType is one of the allowed valuesif (!VALID_SOURCE_TYPES.includes(sourceType)) {@@ -182,15 +211,17 @@ export function blockCondition(config) {}// Freeze schema and compute derived validArgKeys- const frozenSchema = Object.freeze({ ...argsSchema });- const frozenConstraints = constraints+ const frozenSchema: Readonly<Record<string, ArgSchema>> = Object.freeze({+ ...argsSchema,+ });+ const frozenConstraints: Readonly<BlockConstraints> | undefined = constraints? Object.freeze({ ...constraints }): undefined;- const argKeys = Object.freeze(Object.keys(argsSchema));- const allKeys =+ const argKeys: readonly string[] = Object.freeze(Object.keys(argsSchema));+ const allKeys: readonly string[] =sourceType !== "none" ? Object.freeze([...argKeys, "source"]) : argKeys;- return function decorator(TargetClass) {+ return (TargetClass) => {// Validate that the class extends BlockConditionif (!(TargetClass.prototype instanceof BlockCondition)) {throw new Error(diff --git a/frontend/discourse/app/blocks/conditions/index.js b/frontend/discourse/app/blocks/conditions/index.tssimilarity index 73%rename from frontend/discourse/app/blocks/conditions/index.jsrename to frontend/discourse/app/blocks/conditions/index.tsindex 83719cfed6f..844111a2455 100644--- a/frontend/discourse/app/blocks/conditions/index.js+++ b/frontend/discourse/app/blocks/conditions/index.ts@@ -1,7 +1,13 @@-// @ts-check// BlockCondition class and decoratorexport { BlockCondition } from "./condition";+export type {+ ConditionContext,+ ConditionResolvedValue,+ ConditionSourceType,+ ConditionValidateFn,+} from "./condition";export { blockCondition } from "./decorator";+export type { BlockConditionConfig } from "./decorator";// Built-in condition classes// Registered by the freeze-block-registry initializerdiff --git a/frontend/discourse/app/blocks/conditions/outlet-arg.js b/frontend/discourse/app/blocks/conditions/outlet-arg.tssimilarity index 71%rename from frontend/discourse/app/blocks/conditions/outlet-arg.jsrename to frontend/discourse/app/blocks/conditions/outlet-arg.tsindex 3b3e2d8b96b..5f1eb13e3af 100644--- a/frontend/discourse/app/blocks/conditions/outlet-arg.js+++ b/frontend/discourse/app/blocks/conditions/outlet-arg.ts@@ -1,6 +1,9 @@-// @ts-checkimport { getByPath, matchValue } from "discourse/lib/blocks";-import { BlockCondition } from "./condition";+import {+ BlockCondition,+ type ConditionContext,+ type ConditionResolvedValue,+} from "./condition";import { blockCondition } from "./decorator";/**@@ -9,21 +12,26 @@ import { blockCondition } from "./decorator";*/const MAX_PATH_LENGTH = 255;+/** Args accepted by the `outlet-arg` condition. */+interface OutletArgConditionArgs {+ /** Dot-notation path to the property, e.g. `"topic.closed"`,+ * `"user.trust_level"`, `"category.id"`. */+ path: string;++ /** Value to match against (see matching rules below). */+ value?: unknown;++ /** If true, passes when the property exists (not undefined); if false,+ * passes when the property is undefined. */+ exists?: boolean;+}+/*** A condition that evaluates based on outlet arg values.** Checks properties passed via `@outletArgs` on the BlockOutlet. Supports* dot-notation paths for nested properties and flexible value matching.*- * @class BlockOutletArgCondition- * @extends BlockCondition- *- * @param {string} path - Dot-notation path to the property (required).- * E.g., `"topic.closed"`, `"user.trust_level"`, `"category.id"`.- * @param {*} [value] - Value to match against (see matching rules below).- * @param {boolean} [exists] - If true, passes when property exists (not undefined);- * if false, passes when property is undefined.- ** ## Value Matching Rules** Uses the shared `matchValue` utility:@@ -35,32 +43,46 @@ const MAX_PATH_LENGTH = 255;* - **`{ any: [...] }`**: Passes if `actual` matches ANY spec in array (OR logic)** @example+ * ```* // Check if topic is closed* { type: "outlet-arg", path: "topic.closed", value: true }+ * ```** @example+ * ```* // Check user trust level is 2 or higher* { type: "outlet-arg", path: "user.trust_level", value: [2, 3, 4] }+ * ```** @example+ * ```* // Check category is one of several IDs* { type: "outlet-arg", path: "category.id", value: [1, 2, 3] }+ * ```** @example+ * ```* // Check if topic property exists* { type: "outlet-arg", path: "topic", exists: true }+ * ```** @example+ * ```* // Check topic is NOT closed* { type: "outlet-arg", path: "topic.closed", value: { not: true } }+ * ```** @example+ * ```* // Check category slug matches pattern* { type: "outlet-arg", path: "category.slug", value: /^support/ }+ * ```** @example+ * ```* // Check topic is closed OR archived (using any)* { type: "outlet-arg", path: "topic.closed", value: { any: [true, { not: false }] } }+ * ```*/@blockCondition({type: "outlet-arg",@@ -73,7 +95,9 @@ const MAX_PATH_LENGTH = 255;exactlyOne: ["value", "exists"],},validate(args) {- const { path: argPath } = args;+ // The `args` schema declares `path` as a required string, validated+ // before this custom validator runs.+ const { path: argPath } = args as unknown as OutletArgConditionArgs;// Check length first to prevent regex DoS with extremely long strings.if (argPath.length > MAX_PATH_LENGTH) {@@ -97,13 +121,9 @@ const MAX_PATH_LENGTH = 255;export default class BlockOutletArgCondition extends BlockCondition {/*** Evaluates whether the outlet arg condition passes.- *- * @param {Object} args - The condition arguments.- * @param {Object} [context] - Evaluation context.- * @returns {boolean} True if the condition passes.*/- evaluate(args, context) {- const { path, value, exists } = args;+ evaluate(args: Record<string, unknown>, context?: ConditionContext): boolean {+ const { path, value, exists } = args as unknown as OutletArgConditionArgs;const outletArgs = context?.outletArgs;// Get the value at the path@@ -121,21 +141,12 @@ export default class BlockOutletArgCondition extends BlockCondition {/*** Returns the resolved value at the path for debug logging.- *- * @param {Object} args - The condition arguments containing `path`, `value`, `exists`.- * @param {Object} [context] - Evaluation context containing outletArgs.- * @returns {{- * hasValue: true,- * formatted: {- * path: string,- * actual: *,- * configured: * | { exists: boolean }- * }- * }} Object with formatted log data showing path, actual value, and configured expectation.*/- // @ts-ignore - TS2416: Override returns formatted object instead of base class value structure- getResolvedValueForLogging(args, context) {- const { path, value, exists } = args;+ getResolvedValueForLogging(+ args: Record<string, unknown>,+ context?: ConditionContext+ ): ConditionResolvedValue {+ const { path, value, exists } = args as unknown as OutletArgConditionArgs;return {hasValue: true,formatted: {diff --git a/frontend/discourse/app/blocks/conditions/route.js b/frontend/discourse/app/blocks/conditions/route.tssimilarity index 74%rename from frontend/discourse/app/blocks/conditions/route.jsrename to frontend/discourse/app/blocks/conditions/route.tsindex 3d7618d5e03..6d5abca072a 100644--- a/frontend/discourse/app/blocks/conditions/route.js+++ b/frontend/discourse/app/blocks/conditions/route.ts@@ -1,4 +1,4 @@-// @ts-check+import type RouterService from "@ember/routing/router-service";import { service } from "@ember/service";import {getCurrentPageType,@@ -18,9 +18,43 @@ import {validateParamSpec,} from "discourse/lib/blocks/-internals/matching/value-matcher";import { isValidGlobPattern } from "discourse/lib/glob-utils";-import { BlockCondition } from "./condition";+import type DiscoveryService from "discourse/services/discovery";+import { BlockCondition, type ConditionContext } from "./condition";import { blockCondition } from "./decorator";+/**+ * The `any`/`not` combinator keys of a `params`/`queryParams` spec. Specs are+ * authored as plain objects, so the operators are read through this shape at+ * each recursion site; `validateParamsWithOperators()` is the runtime+ * enforcement point for `any` actually being an array.+ */+interface ParamsSpecOperators {+ /** Alternative param specs — OR logic. */+ any?: unknown[];++ /** A negated param spec. */+ not?: unknown;+}++/** Args accepted by the `route` condition. */+interface RouteConditionArgs {+ /** URL patterns to match (passes if ANY match). */+ urls?: string[];++ /** Page types to match (passes if ANY match). */+ pages?: string[];++ /** Page parameters to match (only valid with `pages`). A plain key/value+ * object, or `{ any: [...] }` / `{ not: ... }` combinator of the same. */+ params?: unknown;++ /** Query parameters to match. Note: queryParams alone is not sufficient -+ * the condition requires `urls` or `pages` to match first. This creates+ * implicit AND behavior between route and query params. A plain key/value+ * object, or `{ any: [...] }` / `{ not: ... }` combinator of the same. */+ queryParams?: unknown;+}+/*** A condition that evaluates based on the current URL path, semantic page types,* route parameters, and query parameters.@@ -47,39 +81,41 @@ import { blockCondition } from "./decorator";* normalizing URLs before matching. Theme authors don't need to know if* Discourse runs on `/forum` or root - patterns like `/c/**` work everywhere.*- * @class BlockRouteCondition- * @extends BlockCondition- *- * @param {string[]} [urls] - URL patterns to match (passes if ANY match).- * @param {string[]} [pages] - Page types to match (passes if ANY match).- * @param {Object} [params] - Page parameters to match (only valid with `pages`).- * @param {Object} [queryParams] - Query parameters to match. Note: queryParams alone- * is not sufficient - the condition requires `urls` or `pages` to match first.- * This creates implicit AND behavior between route and query params.- ** @example+ * ```* // Match category pages using page type* { type: "route", pages: ["CATEGORY_PAGES"] }+ * ```** @example+ * ```* // Match category pages using URL pattern* { type: "route", urls: ["/c/**"] }+ * ```** @example+ * ```* // Match multiple page types (OR logic)* { type: "route", pages: ["CATEGORY_PAGES", "TAG_PAGES"] }+ * ```** @example+ * ```* // Match specific category by ID* { type: "route", pages: ["CATEGORY_PAGES"], params: { categoryId: 5 } }+ * ```** @example+ * ```* // Match with query params* { type: "route", urls: ["/latest"], queryParams: { filter: "solved" } }+ * ```** @example+ * ```* // Exclude pages using NOT combinator* { not: { type: "route", pages: ["ADMIN_PAGES"] } }+ * ```*/@blockCondition({type: "route",@@ -95,7 +131,7 @@ import { blockCondition } from "./decorator";atMostOne: ["params", "urls"],},validate(args) {- const { urls, pages, params, queryParams } = args;+ const { urls, pages, params, queryParams } = args as RouteConditionArgs;// Validate urlsif (urls?.length) {@@ -123,8 +159,14 @@ import { blockCondition } from "./decorator";// Validate paramsif (params) {- // Handle any/not operators in params- const paramsError = validateParamsWithOperators(params, pages, "params");+ // Handle any/not operators in params. The `requires: { params: "pages" }`+ // constraint (validated before this custom validator runs) guarantees+ // `pages` is present whenever `params` is.+ const paramsError = validateParamsWithOperators(+ params,+ pages as string[],+ "params"+ );if (paramsError) {return paramsError;}@@ -132,7 +174,7 @@ import { blockCondition } from "./decorator";// Validate queryParams for operator typos (e.g., "an" vs "any")if (queryParams) {- let queryParamsError = null;+ let queryParamsError: string | null = null;validateParamSpec(queryParams, "queryParams", (msg) => {queryParamsError = msg;});@@ -145,8 +187,8 @@ import { blockCondition } from "./decorator";},})export default class BlockRouteCondition extends BlockCondition {- @service router;- @service discovery;+ @service declare router: RouterService;+ @service declare discovery: DiscoveryService;/*** Returns the current URL path, normalized for matching.@@ -154,10 +196,8 @@ export default class BlockRouteCondition extends BlockCondition {* Normalization strips the subfolder prefix, query strings, hash fragments,* and trailing slashes. This allows patterns to work consistently regardless* of Discourse's installation configuration.- *- * @returns {string} The normalized URL path.*/- get currentPath() {+ get currentPath(): string {return normalizePath(this.router.currentURL);}@@ -174,27 +214,30 @@ export default class BlockRouteCondition extends BlockCondition {* will only pass if BOTH the route (via `urls` or `pages`) AND the queryParams* match. This is implicit AND behavior. To match only based on query parameters,* use `urls: ["**"]` to match all routes first.- *- * @param {Object} args - The condition arguments.- * @param {Object} [context={}] - Evaluation context (for debugging).- * @returns {boolean} True if the condition passes.*/- evaluate(args, context = {}) {- const { urls, pages, params, queryParams } = args;+ evaluate(+ args: Record<string, unknown>,+ context: ConditionContext = {}+ ): boolean {+ const { urls, pages, params, queryParams } = args as RouteConditionArgs;const currentPath = this.currentPath;// Debug context for nested loggingconst isDebugging = context.debug ?? false;const logger = context.logger;const childDepth = (context._depth ?? 0) + 1;- const debugContext = { debug: isDebugging, _depth: childDepth, logger };+ const debugContext: ConditionContext = {+ debug: isDebugging,+ _depth: childDepth,+ logger,+ };// Get actual query params for matchingconst actualQueryParams = this.router.currentRoute?.queryParams;let routeMatched = false;- let matchedPageType = null;- let actualPageContext = null;+ let matchedPageType: string | null = null;+ let actualPageContext: Record<string, unknown> | null = null;// Check urls (passes if ANY match)if (urls?.length) {@@ -261,7 +304,11 @@ export default class BlockRouteCondition extends BlockCondition {});// Call #matchPageParams with debug=true to log nested OR/NOT/param checks- const paramsContext = { debug: true, _depth: childDepth + 1, logger };+ const paramsContext: ConditionContext = {+ debug: true,+ _depth: childDepth + 1,+ logger,+ };const paramsMatched = this.#matchPageParams(params,actualPageContext,@@ -293,7 +340,7 @@ export default class BlockRouteCondition extends BlockCondition {}// Pass deeper context so OR/AND/NOT logs nest under the queryParams summary- const queryParamsContext = {+ const queryParamsContext: ConditionContext = {...debugContext,_depth: childDepth + 1,};@@ -322,13 +369,12 @@ export default class BlockRouteCondition extends BlockCondition {/*** Matches page parameters against the current context.* Supports any/not operators for complex matching.- *- * @param {Object} params - The expected params from the condition.- * @param {Object} pageContext - The actual context values from the current page.- * @param {Object} debugContext - Debug context for logging.- * @returns {boolean} True if params match.*/- #matchPageParams(params, pageContext, debugContext) {+ #matchPageParams(+ params: unknown,+ pageContext: Record<string, unknown>,+ debugContext: ConditionContext+ ): boolean {// Recursive matching with operators:// - { any: [...] } - OR logic, passes if any spec matches// - { not: {...} } - Negation, passes if inner spec does NOT match@@ -338,21 +384,20 @@ export default class BlockRouteCondition extends BlockCondition {const logger = debugContext.logger;// Handle any operator: { any: [{ categoryId: 1 }, { categoryId: 2 }] }- if (params.any !== undefined) {- const specs = params.any;-+ const anySpec = (params as ParamsSpecOperators).any;+ if (anySpec !== undefined) {// Log combinator BEFORE children so it appears first in treeif (isLoggingEnabled) {logger?.logCondition?.({type: "OR",- args: `${specs.length} params specs`,+ args: `${anySpec.length} params specs`,result: null,depth,conditionSpec: params,});}- const results = specs.map((spec) =>+ const results = anySpec.map((spec) =>this.#matchPageParams(spec, pageContext, {debug: isLoggingEnabled,_depth: depth + 1,@@ -369,7 +414,8 @@ export default class BlockRouteCondition extends BlockCondition {}// Handle not operator: { not: { categoryId: 3 } }- if (params.not !== undefined) {+ const notSpec = (params as ParamsSpecOperators).not;+ if (notSpec !== undefined) {// Log combinator BEFORE children so it appears first in treeif (isLoggingEnabled) {logger?.logCondition?.({@@ -381,7 +427,7 @@ export default class BlockRouteCondition extends BlockCondition {});}- const innerResult = this.#matchPageParams(params.not, pageContext, {+ const innerResult = this.#matchPageParams(notSpec, pageContext, {debug: isLoggingEnabled,_depth: depth + 1,logger,@@ -397,8 +443,15 @@ export default class BlockRouteCondition extends BlockCondition {// Simple params object - all must match// Log individual param checks- const matches = [];- for (const [paramName, expectedValue] of Object.entries(params)) {+ const matches: Array<{+ key: string;+ expected: unknown;+ actual: unknown;+ result: boolean;+ }> = [];+ for (const [paramName, expectedValue] of Object.entries(+ params as Record<string, unknown>+ )) {const actualValue = pageContext[paramName];const result = actualValue === expectedValue;matches.push({@@ -427,22 +480,23 @@ export default class BlockRouteCondition extends BlockCondition {/*** Extracts param values from page context for the specified params.* Handles any/not operators by extracting from nested param objects.- *- * @param {Object} params - The expected params (keys to extract).- * @param {Object} pageContext - The page context containing actual values.- * @returns {Object} Object with only the requested param keys and their actual values.*/- #extractParamValues(params, pageContext) {+ #extractParamValues(+ params: unknown,+ pageContext: Record<string, unknown>+ ): Record<string, unknown> {// Handle any/not operators - extract from first nested object for display- if (params.any !== undefined && params.any.length > 0) {- return this.#extractParamValues(params.any[0], pageContext);+ const anySpec = (params as ParamsSpecOperators).any;+ if (anySpec !== undefined && anySpec.length > 0) {+ return this.#extractParamValues(anySpec[0], pageContext);}- if (params.not !== undefined) {- return this.#extractParamValues(params.not, pageContext);+ const notSpec = (params as ParamsSpecOperators).not;+ if (notSpec !== undefined) {+ return this.#extractParamValues(notSpec, pageContext);}- const result = {};- for (const key of Object.keys(params)) {+ const result: Record<string, unknown> = {};+ for (const key of Object.keys(params as Record<string, unknown>)) {result[key] = pageContext[key];}return result;@@ -453,20 +507,23 @@ export default class BlockRouteCondition extends BlockCondition {* Validates params with support for any/not operators.* This is a standalone function to keep decorator config clean.*- * @param {Object} params - The params to validate.- * @param {Array<string>} pages - The page types to validate against.- * @param {string} [path="params"] - Path for error messages.- * @returns {string|null} Error or null if valid.+ * @param path - Path for error messages.+ * @returns Error or null if valid.*/-function validateParamsWithOperators(params, pages, path = "params") {+function validateParamsWithOperators(+ params: unknown,+ pages: string[],+ path = "params"+): string | null {// Handle any operator: { any: [{ categoryId: 1 }, { categoryId: 2 }] }- if (params.any !== undefined) {- if (!Array.isArray(params.any)) {+ const anySpec = (params as ParamsSpecOperators).any;+ if (anySpec !== undefined) {+ if (!Array.isArray(anySpec)) {return `\`any\` in params must be an array of param objects.`;}- for (let i = 0; i < params.any.length; i++) {+ for (let i = 0; i < anySpec.length; i++) {const nestedError = validateParamsWithOperators(- params.any[i],+ anySpec[i],pages,`${path}.any[${i}]`);@@ -478,8 +535,9 @@ function validateParamsWithOperators(params, pages, path = "params") {}// Handle not operator: { not: { categoryId: 3 } }- if (params.not !== undefined) {- return validateParamsWithOperators(params.not, pages, `${path}.not`);+ const notSpec = (params as ParamsSpecOperators).not;+ if (notSpec !== undefined) {+ return validateParamsWithOperators(notSpec, pages, `${path}.not`);}// Simple params object - validate against page types@@ -489,7 +547,9 @@ function validateParamsWithOperators(params, pages, path = "params") {}// Validate param types- for (const [paramName, value] of Object.entries(params)) {+ for (const [paramName, value] of Object.entries(+ params as Record<string, unknown>+ )) {const pageType = pages.find((p) => {const pageParams = getParamsForPageType(p);return pageParams && paramName in pageParams;diff --git a/frontend/discourse/app/blocks/conditions/setting.js b/frontend/discourse/app/blocks/conditions/setting.tssimilarity index 75%rename from frontend/discourse/app/blocks/conditions/setting.jsrename to frontend/discourse/app/blocks/conditions/setting.tsindex 1d3f640b8de..a0cd3af6e10 100644--- a/frontend/discourse/app/blocks/conditions/setting.js+++ b/frontend/discourse/app/blocks/conditions/setting.ts@@ -1,9 +1,37 @@-// @ts-checkimport { service } from "@ember/service";import { findClosestMatch } from "discourse/lib/string-similarity";-import { BlockCondition } from "./condition";+import {+ BlockCondition,+ type ConditionContext,+ type ConditionResolvedValue,+} from "./condition";import { blockCondition } from "./decorator";+/** Args accepted by the `setting` condition. */+interface SettingConditionArgs {+ /** The setting key to check. */+ name: string;++ /** Custom settings object (e.g., theme settings), passed via `source`.+ * If not provided, `siteSettings` is used. */+ source?: Record<string, unknown>;++ /** If true, passes when setting is truthy; if false, passes when falsy. */+ enabled?: boolean;++ /** Passes when setting exactly equals this value. */+ equals?: unknown;++ /** For single-value settings: passes when setting value is in this array. */+ includes?: unknown[];++ /** For list settings: passes when the setting list contains this value. */+ contains?: string;++ /** For list settings: passes when setting list contains ANY of these. */+ containsAny?: string[];+}+/*** A condition that evaluates based on site setting or custom settings object values.*@@ -29,41 +57,42 @@ import { blockCondition } from "./decorator";* access to the siteSettings service. Unknown settings will cause the condition to* return false rather than throw an error at registration time.*- * @class BlockSettingCondition- * @extends BlockCondition- *- * @param {string} name - The setting key to check (required).- * @param {Object} [source] - Custom settings object (e.g., theme settings). If not provided, uses siteSettings.- * @param {boolean} [enabled] - If true, passes when setting is truthy; if false, passes when falsy.- * @param {*} [equals] - Passes when setting exactly equals this value.- * @param {Array<*>} [includes] - For single-value settings: passes when setting value is in this array.- * @param {string} [contains] - For list settings: passes when the setting list contains this value.- * @param {Array<string>} [containsAny] - For list settings: passes when setting list contains ANY of these.- ** @example+ * ```* // Boolean setting check* { type: "setting", name: "enable_badges", enabled: true }+ * ```** @example+ * ```* // Exact value match* { type: "setting", name: "desktop_category_page_style", equals: "categories_and_latest_topics" }+ * ```** @example+ * ```* // Setting is one of several values* { type: "setting", name: "desktop_category_page_style", includes: ["categories_and_latest_topics", "categories_and_top_topics"] }+ * ```** @example+ * ```* // List setting contains value* { type: "setting", name: "top_menu", contains: "hot" }+ * ```** @example+ * ```* // List setting contains any of values* { type: "setting", name: "share_links", containsAny: ["twitter", "facebook"] }+ * ```** @example+ * ```* // Theme setting check (pass settings object from "virtual:theme")* import { settings } from "virtual:theme";* { type: "setting", source: settings, name: "show_sidebar", enabled: true }+ * ```*/@blockCondition({type: "setting",@@ -84,28 +113,29 @@ import { blockCondition } from "./decorator";// (since it requires service access to siteSettings)})export default class BlockSettingCondition extends BlockCondition {- @service siteSettings;+ // The injected value is the dynamic, per-request settings object built by+ // the `site-settings` service factory (see `discourse/services/site-settings`),+ // not an instance of that module's exported class shim.+ @service declare siteSettings: Record<string, unknown>;/*** Returns the siteSettings service as the default source.- *- * @returns {Object} The siteSettings service.*/- get defaultSource() {+ get defaultSource(): Record<string, unknown> {return this.siteSettings;}/*** Evaluates whether the setting condition passes.- *- * @param {Object} args - The condition arguments.- * @param {Object} [context] - Evaluation context.- * @returns {boolean} True if the condition passes.*/- evaluate(args, context) {- const { name, enabled, equals, includes, contains, containsAny } = args;+ evaluate(args: Record<string, unknown>, context?: ConditionContext): boolean {+ const { name, enabled, equals, includes, contains, containsAny } =+ args as unknown as SettingConditionArgs;- const settingsSource = this.getSourceValue(args, context);+ const settingsSource = this.getSourceValue(args, context) as+ | Record<string, unknown>+ | null+ | undefined;// Handle null/undefined settings source gracefullyif (settingsSource == null) {@@ -154,12 +184,8 @@ export default class BlockSettingCondition extends BlockCondition {* Values are converted to strings before comparison to handle cases where* `searchValue` might be a number but the setting stores string values* (e.g., checking for `123` in `"123|456"`).- *- * @param {string|Array} settingValue - The setting value (may be "a|b|c" or ["a", "b", "c"]).- * @param {string|number} searchValue - The value to search for.- * @returns {boolean} True if the setting contains the search value.*/- #settingContains(settingValue, searchValue) {+ #settingContains(settingValue: unknown, searchValue: string): boolean {if (Array.isArray(settingValue)) {// Convert all values to strings for consistent matchingreturn settingValue.map(String).includes(String(searchValue));@@ -177,15 +203,17 @@ export default class BlockSettingCondition extends BlockCondition {/*** Returns the resolved setting value for debug logging.* Includes a warning note with "did you mean" suggestion if the setting doesn't exist.- *- * @param {Object} args - The condition arguments.- * @param {Object} [context] - Evaluation context.- * @returns {{ value: *, hasValue: true, note?: string }}*/- getResolvedValueForLogging(args, context) {- const { name } = args;-- const settingsSource = this.getSourceValue(args, context);+ getResolvedValueForLogging(+ args: Record<string, unknown>,+ context?: ConditionContext+ ): ConditionResolvedValue {+ const { name } = args as unknown as SettingConditionArgs;++ const settingsSource = this.getSourceValue(args, context) as+ | Record<string, unknown>+ | null+ | undefined;// Handle null/undefined settings sourceif (settingsSource == null) {diff --git a/frontend/discourse/app/blocks/conditions/user.js b/frontend/discourse/app/blocks/conditions/user.tssimilarity index 81%rename from frontend/discourse/app/blocks/conditions/user.jsrename to frontend/discourse/app/blocks/conditions/user.tsindex abdaa3fc1f8..ae5b971dba9 100644--- a/frontend/discourse/app/blocks/conditions/user.js+++ b/frontend/discourse/app/blocks/conditions/user.ts@@ -1,8 +1,49 @@-// @ts-checkimport { service } from "@ember/service";-import { BlockCondition } from "./condition";+import type User from "discourse/models/user";+import { BlockCondition, type ConditionContext } from "./condition";import { blockCondition } from "./decorator";+/** Args accepted by the `user` condition. */+interface UserConditionArgs {+ /** Path to a user object in outlet args (e.g., `@outletArgs.user`). */+ source?: string;++ /** If true, passes for logged-in users (or if source matches currentUser). */+ loggedIn?: boolean;++ /** If true, passes only for admin users. */+ admin?: boolean;++ /** If true, passes only for moderators (includes admins). */+ moderator?: boolean;++ /** If true, passes only for staff members. */+ staff?: boolean;++ /** Minimum trust level required (0-4). */+ minTrustLevel?: number;++ /** Maximum trust level allowed (0-4). */+ maxTrustLevel?: number;++ /** User must be in at least one of these groups (OR logic). */+ groups?: string[];+}++/**+ * The minimal shape read from a resolved user object, whether it's the+ * `currentUser` service or an arbitrary user-shaped value from outlet args+ * (e.g. a topic's author).+ */+interface UserLike {+ id?: number | string;+ admin?: boolean;+ moderator?: boolean;+ staff?: boolean;+ trust_level?: number;+ groups?: Array<{ name?: string }>;+}+/*** A condition that evaluates based on user state.*@@ -17,9 +58,6 @@ import { blockCondition } from "./decorator";* The only exception is the `groups` array itself, which uses OR logic internally* (user must be in at least ONE of the specified groups).*- * @class BlockUserCondition- * @extends BlockCondition- ** ## Condition Configuration Properties** These properties are passed as an args object to `evaluate()`:@@ -36,32 +74,46 @@ import { blockCondition } from "./decorator";* | `groups` | `string[]` | User must be in at least one of these groups (OR logic) |** @example+ * ```* // Logged-in users only* { type: "user", loggedIn: true }+ * ```** @example+ * ```* // Anonymous users only* { type: "user", loggedIn: false }+ * ```** @example+ * ```* // Admin users only* { type: "user", admin: true }+ * ```** @example+ * ```* // Trust level 2+ AND in specific groups* { type: "user", minTrustLevel: 2, groups: ["beta-testers", "power-users"] }+ * ```** @example+ * ```* // Check a user from outlet args instead of currentUser* { type: "user", source: "@outletArgs.topicAuthor", admin: true }+ * ```** @example+ * ```* // Check if source user IS the current logged-in user* { type: "user", source: "@outletArgs.post.user", loggedIn: true }+ * ```** @example+ * ```* // Check if source user is NOT the current user (e.g., for "follow" button)* { type: "user", source: "@outletArgs.user", loggedIn: false }+ * ```*/@blockCondition({type: "user",@@ -95,7 +147,7 @@ import { blockCondition } from "./decorator";minTrustLevel,maxTrustLevel,groups,- } = args;+ } = args as UserConditionArgs;// Check for loggedIn: false with user-specific conditionsif (loggedIn === false) {@@ -132,26 +184,19 @@ import { blockCondition } from "./decorator";},})export default class BlockUserCondition extends BlockCondition {- @service currentUser;+ @service declare currentUser: User | null;/*** Returns the currentUser service as the default source.- *- * @returns {Object|null} The currentUser service.*/- get defaultSource() {+ get defaultSource(): User | null {return this.currentUser;}/*** Evaluates whether the user condition passes.- *- * @param {Object} args - The condition arguments.- * @param {Object} [context] - Evaluation context.- * @param {Object} [context.outletArgs] - Outlet args for source resolution.- * @returns {boolean} True if the condition passes.*/- evaluate(args, context) {+ evaluate(args: Record<string, unknown>, context?: ConditionContext): boolean {const {loggedIn,admin,@@ -160,9 +205,12 @@ export default class BlockUserCondition extends BlockCondition {minTrustLevel,maxTrustLevel,groups,- } = args;+ } = args as UserConditionArgs;- const user = this.getSourceValue(args, context);+ const user = this.getSourceValue(args, context) as+ | UserLike+ | null+ | undefined;// Check login state or current user match (when source is provided)if (loggedIn !== undefined) {@@ -248,12 +296,11 @@ export default class BlockUserCondition extends BlockCondition {* Checks if two user objects represent the same user by comparing their ids.* Used when `source` is provided with `loggedIn` to check if the source user* is the current logged-in user.- *- * @param {Object} user1 - First user object.- * @param {Object} user2 - Second user object.- * @returns {boolean} True if both users exist and have the same id.*/- #isSameUser(user1, user2) {+ #isSameUser(+ user1: UserLike | null | undefined,+ user2: UserLike | null | undefined+ ): boolean {if (!user1 || !user2) {return false;}@@ -267,12 +314,8 @@ export default class BlockUserCondition extends BlockCondition {* Checks if a user is a member of at least one of the specified groups.* This implements OR logic for group membership: if the user belongs to any of* the provided groups, the check passes.- *- * @param {Object} user - The user object to check.- * @param {Array<string>} groupNames - Array of group names to check membership against.- * @returns {boolean} True if the user is in at least one of the specified groups.*/- #isInAnyGroup(user, groupNames) {+ #isInAnyGroup(user: UserLike, groupNames: string[]): boolean {// Extract the names of all groups the user belongs toconst userGroups = user.groups?.map((g) => g.name) || [];// Check if any of the required group names appear in the user's groupsdiff --git a/frontend/discourse/app/blocks/conditions/viewport.js b/frontend/discourse/app/blocks/conditions/viewport.tssimilarity index 65%rename from frontend/discourse/app/blocks/conditions/viewport.jsrename to frontend/discourse/app/blocks/conditions/viewport.tsindex 7643de34d47..4156ee0d4e7 100644--- a/frontend/discourse/app/blocks/conditions/viewport.js+++ b/frontend/discourse/app/blocks/conditions/viewport.ts@@ -1,66 +1,89 @@-// @ts-checkimport { service } from "@ember/service";+import type { CapabilitiesService } from "discourse/services/capabilities";import { BlockCondition } from "./condition";import { blockCondition } from "./decorator";+/** A viewport breakpoint name, matching the breakpoints defined in+ * `capabilities.viewport`. */+type Breakpoint = "sm" | "md" | "lg" | "xl" | "2xl";++/** Args accepted by the `viewport` condition. */+interface ViewportConditionArgs {+ /** Minimum breakpoint required (passes at this size and larger). */+ min?: Breakpoint;++ /** Maximum breakpoint allowed (passes at this size and smaller). */+ max?: Breakpoint;++ /** If true, passes only on touch devices; if false, only on non-touch. */+ touch?: boolean;+}+/*** Available viewport breakpoint names.* Values match the breakpoints defined in capabilities.viewport.- *- * @constant {ReadonlyArray<string>}*/-const BREAKPOINTS = Object.freeze(["sm", "md", "lg", "xl", "2xl"]);+const BREAKPOINTS: readonly Breakpoint[] = Object.freeze([+ "sm",+ "md",+ "lg",+ "xl",+ "2xl",+]);/*** A condition that evaluates based on viewport size and device capabilities.** Uses the standard Discourse breakpoints from the capabilities service:- * - sm: >= 40rem (640px)- * - md: >= 48rem (768px)- * - lg: >= 64rem (1024px)- * - xl: >= 80rem (1280px)- * - 2xl: >= 96rem (1536px)+ * - sm: \>= 40rem (640px)+ * - md: \>= 48rem (768px)+ * - lg: \>= 64rem (1024px)+ * - xl: \>= 80rem (1280px)+ * - 2xl: \>= 96rem (1536px)** **Note:** For simple show/hide based on viewport, CSS media queries are often* more performant. Use this condition when you need to completely remove components* from the DOM on certain viewports, or when the block content differs significantly* between viewports.*- * @class BlockViewportCondition- * @extends BlockCondition- *- * @param {string} [min] - Minimum breakpoint required (passes at this size and larger)- * @param {string} [max] - Maximum breakpoint allowed (passes at this size and smaller)- * @param {boolean} [touch] - If true, passes only on touch devices; if false, only on non-touch- ** @example+ * ```* // Large screens only (lg and up)* { type: "viewport", min: "lg" }+ * ```** @example+ * ```* // Small screens only (below md)* { type: "viewport", max: "sm" }+ * ```** @example+ * ```* // Medium to large screens only* { type: "viewport", min: "md", max: "xl" }+ * ```** @example+ * ```* // Touch devices only* { type: "viewport", touch: true }+ * ```*/@blockCondition({type: "viewport",args: {- min: { type: "string", enum: BREAKPOINTS },- max: { type: "string", enum: BREAKPOINTS },+ // `enum` widens to a mutable `unknown[]`; BREAKPOINTS stays a frozen,+ // precisely-typed `readonly Breakpoint[]` for use elsewhere in this file.+ min: { type: "string", enum: BREAKPOINTS as unknown[] },+ max: { type: "string", enum: BREAKPOINTS as unknown[] },touch: { type: "boolean" },},constraints: {atLeastOne: ["min", "max", "touch"],},validate(args) {- const { min, max } = args;+ const { min, max } = args as ViewportConditionArgs;// Check that min <= max when both are specifiedif (min && max) {@@ -79,16 +102,13 @@ const BREAKPOINTS = Object.freeze(["sm", "md", "lg", "xl", "2xl"]);},})export default class BlockViewportCondition extends BlockCondition {- @service capabilities;+ @service declare capabilities: CapabilitiesService;/*** Evaluates whether the viewport condition passes.- *- * @param {Object} args - The condition arguments.- * @returns {boolean} True if the condition passes.*/- evaluate(args) {- const { min, max, touch } = args;+ evaluate(args: Record<string, unknown>): boolean {+ const { min, max, touch } = args as ViewportConditionArgs;// Check touch capabilityif (touch !== undefined && touch !== this.capabilities.touch) {diff --git a/frontend/discourse/app/blocks/index.js b/frontend/discourse/app/blocks/index.tssimilarity index 63%rename from frontend/discourse/app/blocks/index.jsrename to frontend/discourse/app/blocks/index.tsindex 316b2303e08..8e6429e7cec 100644--- a/frontend/discourse/app/blocks/index.js+++ b/frontend/discourse/app/blocks/index.ts@@ -1,14 +1,23 @@-// @ts-check/*** Public API block exports.** @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.- *- * @module discourse/blocks*/// Public API for plugin developersexport { block } from "discourse/lib/blocks/-internals/decorator";export { BlockCondition } from "discourse/blocks/conditions";+export type {+ ArgSchema,+ ArgType,+ BlockClassNames,+ BlockConstraints,+ BlockMetadata,+ BlockNamespaceType,+ BlockOptions,+ BlockValidateFn,+ ChildArgSchema,+ LayoutEntry,+} from "discourse/blocks/types";diff --git a/frontend/discourse/app/blocks/types.ts b/frontend/discourse/app/blocks/types.tsnew file mode 100644index 00000000000..cea0ebd8b4c--- /dev/null+++ b/frontend/discourse/app/blocks/types.ts@@ -0,0 +1,212 @@+import type Component from "@glimmer/component";++/**+ * Public data shapes for the blocks API, shared by the `@block` decorator, the+ * registry, and the render pipeline. Author-facing types live here (rather than+ * under `-internals/`) so consumers can import them from `discourse/blocks`+ * without reaching across the internal boundary.+ */++/** The namespace category a block name resolves to. */+export type BlockNamespaceType = "core" | "plugin" | "theme";++/** The value type of a block argument. */+export type ArgType =+ | "string"+ | "number"+ | "boolean"+ | "array"+ | "object"+ | "any";++/**+ * Additional CSS classes for a block, as a string, an array of strings, or a+ * function computing them from the block's args.+ */+export type BlockClassNames =+ | string+ | string[]+ | ((args: Record<string, unknown>) => string);++/** Custom cross-arg validation invoked with the block's resolved args. */+export type BlockValidateFn = (args: Record<string, unknown>) => unknown;++/**+ * Cross-arg validation constraints. The precise shape is defined and enforced by+ * the constraints validator; treated opaquely at the type level here.+ */+export type BlockConstraints = Record<string, unknown>;++/** Schema describing and validating a single block argument. */+export interface ArgSchema {+ /** The argument's value type. */+ type: ArgType;++ /** Whether the argument must be provided. Defaults to `false`. */+ required?: boolean;++ /** Default value applied when the argument is omitted. */+ default?: unknown;++ /** Element type for `array` arguments. */+ itemType?: "string" | "number" | "boolean";++ /** Regular expression a `string` value must match. */+ pattern?: RegExp;++ /** Minimum length for a `string` or `array` value. */+ minLength?: number;++ /** Maximum length for a `string` or `array` value. */+ maxLength?: number;++ /** Minimum value for a `number`. */+ min?: number;++ /** Maximum value for a `number`. */+ max?: number;++ /** Whether a `number` must be an integer. */+ integer?: boolean;++ /** Allowed values for the argument. */+ enum?: unknown[];++ /** Allowed values for individual items of an `array` argument. */+ itemEnum?: unknown[];++ /** Nested schema for an `object` argument's properties, validated recursively. */+ properties?: Record<string, ArgSchema>;++ /**+ * Required class (or a `"model:*"` string, resolved via the registry) for an+ * `object` argument's value. Mutually exclusive with `properties`.+ */+ instanceOf?: (abstract new (...args: unknown[]) => object) | string;++ /**+ * Human-readable class name used in error messages when `instanceOf` is a+ * class reference. Needed because the class's own `.name` isn't reliable+ * (bundlers can rename anonymous classes; production builds minify names).+ */+ instanceOfName?: string;+}++/**+ * Schema for a single `childArgs` argument (see `BlockOptions.childArgs`).+ * Extends `ArgSchema` with the child-specific `unique` property.+ */+export interface ChildArgSchema extends ArgSchema {+ /**+ * Whether this arg's value must be unique among sibling children. Only+ * supported for primitive types (string, number, boolean).+ */+ unique?: boolean;+}++/** Options accepted by the `@block` decorator. */+export interface BlockOptions {+ /** If `true`, this block can contain nested child blocks. */+ container?: boolean;++ /** Human-readable description of the block. */+ description?: string;++ /** Schema for the block's arguments, keyed by arg name. */+ args?: Record<string, ArgSchema>;++ /**+ * Schema for args passed to this block's children. Only valid on container+ * blocks (`container: true`).+ */+ childArgs?: Record<string, ChildArgSchema>;++ /** Cross-arg validation constraints. */+ constraints?: BlockConstraints;++ /** Custom validation function run against the block's args. */+ validate?: BlockValidateFn;++ /** Additional CSS classes for the block. */+ classNames?: BlockClassNames;++ /** Glob patterns for the outlets this block is allowed to render in. */+ allowedOutlets?: string[];++ /** Glob patterns for the outlets this block is forbidden from rendering in. */+ deniedOutlets?: string[];+}++/**+ * Frozen metadata recorded for a class decorated with `@block`, returned by+ * `getBlockMetadata()`.+ */+export interface BlockMetadata {+ /** Full name identifier, e.g. `"theme:tactile:hero-banner"`. */+ blockName: string;++ /** Plain name without namespace, e.g. `"hero-banner"`. */+ shortName: string;++ /** Parsed namespace used for CSS, e.g. `"my-plugin"` / `"theme-tactile"`, or `null` for core. */+ namespace: string | null;++ /** The kind of namespace the block belongs to. */+ namespaceType: BlockNamespaceType;++ /** Human-readable description of the block. */+ description: string;++ /** Whether the block can contain nested child blocks. */+ isContainer: boolean;++ /** Additional CSS classes declared on the decorator. */+ decoratorClassNames: BlockClassNames | null;++ /** The block's args schema. */+ args: Record<string, ArgSchema> | null;++ /** The child-args schema (container blocks only). */+ childArgs: Record<string, ChildArgSchema> | null;++ /** Cross-arg validation constraints. */+ constraints: BlockConstraints | null;++ /** Custom validation function. */+ validate: BlockValidateFn | null;++ /** Allowed outlet glob patterns. */+ allowedOutlets: readonly string[] | null;++ /** Denied outlet glob patterns. */+ deniedOutlets: readonly string[] | null;+}++/**+ * A single entry in an outlet layout, as passed to `api.renderBlocks()`.+ */+export interface LayoutEntry {+ /**+ * The block to render: a `@block`-decorated component class, or the string+ * name of a registered block.+ */+ block: typeof Component | string;++ /** Args passed to the block component. */+ args?: Record<string, unknown>;++ /** Additional CSS classes for the block wrapper. */+ classNames?: string | string[];++ /** Nested entries, for container blocks only. */+ children?: LayoutEntry[];++ /** Conditions that must all pass for the block to render. */+ conditions?: object | object[];++ /** Values satisfying the parent container's `childArgs` schema. */+ containerArgs?: Record<string, unknown>;++ /** Unique identifier for targeting and BEM styling. */+ id?: string;+}diff --git a/frontend/discourse/app/initializers/freeze-block-registry.js b/frontend/discourse/app/initializers/freeze-block-registry.tssimilarity index 69%rename from frontend/discourse/app/initializers/freeze-block-registry.jsrename to frontend/discourse/app/initializers/freeze-block-registry.tsindex 7005cae7881..bc3f316e024 100644--- a/frontend/discourse/app/initializers/freeze-block-registry.js+++ b/frontend/discourse/app/initializers/freeze-block-registry.ts@@ -9,6 +9,25 @@ import {import { _freezeOutletRegistry } from "discourse/lib/blocks/-internals/registry/outlet";import { withPluginApi } from "discourse/lib/plugin-api";+/**+ * Narrows a value exported from `discourse/blocks/conditions` to a concrete+ * `BlockCondition` subclass, mirroring the runtime check the "any" branch of+ * the loop below relies on: only classes whose prototype chain reaches+ * `BlockCondition` (excluding the base class itself) are condition types —+ * the module's other exports (`blockCondition`, built-in condition classes'+ * shared base) are plain functions or the base class and must be skipped.+ */+function isConditionClass(+ candidate: unknown+): candidate is typeof conditions.BlockCondition {+ return (+ typeof candidate === "function" &&+ (candidate as { prototype: unknown }).prototype instanceof+ conditions.BlockCondition &&+ candidate !== conditions.BlockCondition+ );+}+/*** Initializes the blocks system by registering built-in blocks and conditions,* then freezing all registries.@@ -29,7 +48,7 @@ export default {after: "discourse-bootstrap",before: "inject-discourse-objects",- initialize() {+ initialize(): void {// Register built-in blockswithPluginApi((api) => {for (const BlockClass of Object.values(BuiltinBlocks)) {@@ -41,11 +60,7 @@ export default {// Register core condition typesfor (const exported of Object.values(conditions)) {- if (- typeof exported === "function" &&- exported.prototype instanceof conditions.BlockCondition &&- exported !== conditions.BlockCondition- ) {+ if (isConditionClass(exported)) {_registerConditionType(exported);}}diff --git a/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gjs b/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gjsdeleted file mode 100644index d4df79ae421..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gjs+++ /dev/null@@ -1,107 +0,0 @@-// @ts-check-/**- * Block layout wrapper for blocks.- *- * This module provides standard wrapper components for both leaf blocks- * (non-container) and container blocks. All blocks rendered through- * `BlockOutlet` use these wrappers to ensure consistent BEM-style class- * naming and layout structure.- *- * @module discourse/lib/blocks/-internals/components/block-layout-wrapper- */-import Component from "@glimmer/component";-import curryComponent from "ember-curry-component";-import cssIdentifier from "discourse/helpers/css-identifier";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";--/**- * @typedef {import("@glint/template").ComponentLike} CurriedComponent- */--/**- * @typedef {Object} WrappedBlockLayoutArgs- * @property {string} outletName - The outlet name for class generation.- * @property {string} name - The block's full registered name.- * @property {string|null} namespace - The block's namespace prefix.- * @property {boolean} isContainer - Whether this is a container block.- * @property {string|null} [id] - Optional block ID for BEM modifiers and targeting.- * @property {CurriedComponent} Component - The curried block component to render.- * @property {string} [classNames] - Additional CSS classes from layout entry.- * @property {string} [decoratorClassNames] - Extra CSS classes from the @block decorator.- */--/**- * @typedef {Object} WrappedBlockLayoutSignature- * @property {WrappedBlockLayoutArgs} Args- */--/**- * Wraps a block in a standard layout wrapper with BEM-style classes.- *- * @param {Object} blockData - Block rendering data.- * @param {string} blockData.outletName - The outlet name for class generation.- * @param {string} blockData.name - The block's full registered name.- * @param {string} blockData.namespace - The block's namespace prefix.- * @param {boolean} blockData.isContainer - Whether this is a container block.- * @param {string|null} [blockData.id] - Optional block ID for BEM modifiers.- * @param {CurriedComponent} blockData.Component - The curried block component.- * @param {string} [blockData.classNames] - Additional CSS classes from layout entry.- * @param {string} [blockData.decoratorClassNames] - Extra CSS classes from the @block decorator.- * @param {import("@ember/owner").default} owner - The application owner for currying.- * @returns {CurriedComponent} The wrapped component.- */-export function wrapBlockLayout(blockData, owner) {- return curryComponent(WrappedBlockLayout, blockData, owner);-}--/**- * Component that wraps all blocks with a standard class structure.- *- * All blocks (both containers and non-containers) receive:- * - `{outletName}__block` or `{outletName}__block-container` - Outlet-scoped class for styling- * - `{outletName}__block--{id}` or `{outletName}__block-container--{id}` - BEM modifier when `id` is provided- * - Custom classes from `@decoratorClassNames` (from the @block decorator)- * - Custom classes from `@classNames` (from the layout entry)- *- * Block identity is available via data attributes:- * - `data-block-name` - The block's full registered name- * - `data-block-namespace` - The block's namespace (if present)- * - `data-block-id` - The block's entry ID (if provided)- *- * @extends {Component<WrappedBlockLayoutSignature>}- */-class WrappedBlockLayout extends Component {- /**- * Generates the appropriate CSS class based on block type and optional ID.- * When an ID is provided, adds a BEM modifier class (e.g., `outlet__block--my-id`).- *- * @returns {string[]} An array of CSS class names.- */- get blockClassNames() {- const safeOutlet = cssIdentifier(this.args.outletName);- const baseClass = this.args.isContainer- ? `${safeOutlet}__block-container`- : `${safeOutlet}__block`;-- if (this.args.id) {- return [baseClass, `${baseClass}--${this.args.id}`];- }-- return [baseClass];- }-- <template>- <div- class={{dConcatClass- this.blockClassNames- @decoratorClassNames- @classNames- }}- data-block-id={{@id}}- data-block-name={{@name}}- data-block-namespace={{@namespace}}- >- <@Component />- </div>- </template>-}diff --git a/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gts b/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gtsnew file mode 100644index 00000000000..0f87de8dff2--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/components/block-layout-wrapper.gts@@ -0,0 +1,95 @@+/**+ * Block layout wrapper for blocks.+ *+ * This module provides standard wrapper components for both leaf blocks+ * (non-container) and container blocks. All blocks rendered through+ * `BlockOutlet` use these wrappers to ensure consistent BEM-style class+ * naming and layout structure.+ */+import Component from "@glimmer/component";+import type Owner from "@ember/owner";+import curryComponent from "ember-curry-component";+import cssIdentifier from "discourse/helpers/css-identifier";+import type { BlockComponent } from "discourse/lib/blocks/-internals/types";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++interface WrappedBlockLayoutArgs {+ // The outlet name for class generation.+ outletName: string;+ // The block's full registered name.+ name?: string;+ // The block's namespace prefix.+ namespace?: string | null;+ // Whether this is a container block.+ isContainer: boolean;+ // Optional block ID for BEM modifiers and targeting.+ id?: string;+ // The curried block component to render.+ Component: BlockComponent;+ // Additional CSS classes from the layout entry.+ classNames?: string;+ // Extra CSS classes from the @block decorator.+ decoratorClassNames?: string | null;+}++interface WrappedBlockLayoutSignature {+ Args: WrappedBlockLayoutArgs;+}++/**+ * Wraps a block in a standard layout wrapper with BEM-style classes.+ */+export function wrapBlockLayout(+ blockData: WrappedBlockLayoutArgs,+ owner: Owner+): BlockComponent {+ return curryComponent(WrappedBlockLayout, blockData, owner);+}++/**+ * Component that wraps all blocks with a standard class structure.+ *+ * All blocks (both containers and non-containers) receive:+ * - `{outletName}__block` or `{outletName}__block-container` - Outlet-scoped class for styling+ * - `{outletName}__block--{id}` or `{outletName}__block-container--{id}` - BEM modifier when `id` is provided+ * - Custom classes from `@decoratorClassNames` (from the `@block` decorator)+ * - Custom classes from `@classNames` (from the layout entry)+ *+ * Block identity is available via data attributes:+ * - `data-block-name` - The block's full registered name+ * - `data-block-namespace` - The block's namespace (if present)+ * - `data-block-id` - The block's entry ID (if provided)+ */+class WrappedBlockLayout extends Component<WrappedBlockLayoutSignature> {+ /**+ * Generates the appropriate CSS class based on block type and optional ID.+ * When an ID is provided, adds a BEM modifier class (e.g., `outlet__block--my-id`).+ */+ get blockClassNames(): string[] {+ const safeOutlet = cssIdentifier(this.args.outletName);+ const baseClass = this.args.isContainer+ ? `${safeOutlet}__block-container`+ : `${safeOutlet}__block`;++ if (this.args.id) {+ return [baseClass, `${baseClass}--${this.args.id}`];+ }++ return [baseClass];+ }++ <template>+ <div+ class={{dConcatClass+ this.blockClassNames+ @decoratorClassNames+ @classNames+ }}+ data-block-id={{@id}}+ data-block-name={{@name}}+ data-block-namespace={{@namespace}}+ >+ <@Component />+ </div>+ </template>+}diff --git a/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gjs b/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gjsdeleted file mode 100644index a7d966ed826..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gjs+++ /dev/null@@ -1,24 +0,0 @@-import Component from "@glimmer/component";-import { trustHTML } from "@ember/template";-import { extractErrorInfo } from "discourse/lib/ajax-error";-import DFlashMessage from "discourse/ui-kit/d-flash-message";--/**- * Displays an error inline within a block outlet.- * Uses FlashMessage to render the error in a consistent format.- *- * @param {Error|string|Object} error - The error to display. Can be an Error object,- * a string, an HTTP response object with responseJSON/responseText, or a jqXHR object.- */-export default class BlockOutletInlineError extends Component {- get errorMessage() {- const errorInfo = extractErrorInfo(this.args.error, undefined, {- skipConsoleError: true,- });- return errorInfo.html ? trustHTML(errorInfo.message) : errorInfo.message;- }-- <template>- <DFlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />- </template>-}diff --git a/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gts b/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gtsnew file mode 100644index 00000000000..ccaf04e07cd--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-inline-error.gts@@ -0,0 +1,34 @@+import Component from "@glimmer/component";+import { type TrustedHTML, trustHTML } from "@ember/template";+import { extractErrorInfo } from "discourse/lib/ajax-error";+import DFlashMessage from "discourse/ui-kit/d-flash-message";++interface BlockOutletInlineErrorSignature {+ Args: {+ // The error to display. `extractErrorInfo` also accepts a string, an HTTP+ // response object, or a jqXHR object, but every current consumer only+ // ever passes the `Error` surfaced by `DAsyncContent`'s `error` block.+ error: Error;+ };+}++/**+ * Displays an error inline within a block outlet.+ * Uses FlashMessage to render the error in a consistent format.+ */+export default class BlockOutletInlineError extends Component<BlockOutletInlineErrorSignature> {+ get errorMessage(): string | TrustedHTML {+ // `extractErrorInfo` is authored in untyped `.js`; annotate the fields we+ // read so the getter's return type stays precise rather than widening to `any`.+ const errorInfo: { html: boolean; message: string } = extractErrorInfo(+ this.args.error,+ undefined,+ { skipConsoleError: true }+ );+ return errorInfo.html ? trustHTML(errorInfo.message) : errorInfo.message;+ }++ <template>+ <DFlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />+ </template>+}diff --git a/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gjs b/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gtssimilarity index 81%rename from frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gjsrename to frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gtsindex fa79928f80f..a1f599ae40b 100644--- a/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gjs+++ b/frontend/discourse/app/lib/blocks/-internals/components/block-outlet-root-container.gts@@ -1,4 +1,3 @@-// @ts-checkimport Component from "@glimmer/component";import { cached } from "@glimmer/tracking";import { getOwner } from "@ember/owner";@@ -10,12 +9,33 @@ import {} from "discourse/lib/blocks/-internals/css";import { withDebugGroup } from "discourse/lib/blocks/-internals/debug-hooks";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";-import { processBlockEntries } from "discourse/lib/blocks/-internals/entry-processing";+import {+ type CreateChildBlockFn,+ type LeafCache,+ processBlockEntries,+} from "discourse/lib/blocks/-internals/entry-processing";import {FAILURE_TYPE,isOptionalMissing,} from "discourse/lib/blocks/-internals/patterns";import { tryResolveBlock } from "discourse/lib/blocks/-internals/registry/block";+import type {+ BlockEntry,+ ChildBlockResult,+} from "discourse/lib/blocks/-internals/types";+import type Blocks from "discourse/services/blocks";++interface BlockOutletRootContainerSignature {+ Args: {+ outletName: string;+ outletArgs: Record<string, unknown>;+ rawChildren: BlockEntry[];+ showGhosts: boolean;+ showVisualOverlay: boolean;+ isLoggingEnabled: boolean;+ createChildBlockFn: CreateChildBlockFn;+ };+}/*** Internal container component that processes and renders block children.@@ -32,10 +52,10 @@ import { tryResolveBlock } from "discourse/lib/blocks/-internals/registry/block"* The component receives the authorization-dependent function `createChildBlockFn`* as a prop to maintain the authorization model in the main block-outlet module.*- * @private+ * Internal — not part of the block authoring API.*/-export default class BlockOutletRootContainer extends Component {- @service blocks;+export default class BlockOutletRootContainer extends Component<BlockOutletRootContainerSignature> {+ @service declare blocks: Blocks;/*** Cache for curried components, keyed by their stable block key.@@ -47,19 +67,16 @@ export default class BlockOutletRootContainer extends Component {* - Keys use stable `__stableKey` values assigned once at registration time* - The same keys are reused on every render/navigation* - This cache instance is garbage collected when the owning component is destroyed- *- * @type {Map<string, {ComponentClass: typeof Component, args: Object, result: Object}>}*/- #componentCache = new Map();+ #componentCache: LeafCache = new Map();/*** The CSS-safe version of the outlet name, used as the class for the* outermost wrapper `<div>`.** @see {@link outletClassName} for the naming convention.- * @returns {string} The CSS-safe outlet name (e.g., "hero-blocks").*/- get safeOutletName() {+ get safeOutletName(): string {return outletClassName(this.args.outletName);}@@ -68,9 +85,8 @@ export default class BlockOutletRootContainer extends Component {* CSS container query context for child blocks.** @see {@link outletContainerClassName} for the naming convention.- * @returns {string} The container class name (e.g., "hero-blocks__container").*/- get containerClassName() {+ get containerClassName(): string {return outletContainerClassName(this.args.outletName);}@@ -79,9 +95,8 @@ export default class BlockOutletRootContainer extends Component {* block children.** @see {@link outletLayoutClassName} for the naming convention.- * @returns {string} The layout class name (e.g., "hero-blocks__layout").*/- get layoutClassName() {+ get layoutClassName(): string {return outletLayoutClassName(this.args.outletName);}@@ -92,11 +107,9 @@ export default class BlockOutletRootContainer extends Component {* services like `router` and `discovery` during condition evaluation here* (synchronously in a tracked getter), Ember establishes tracking* dependencies. Route changes trigger this getter to re-run.- *- * @returns {Array<import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult>}*/@cached- get processedChildren() {+ get processedChildren(): ChildBlockResult[] {const {rawChildren,showGhosts,@@ -107,13 +120,15 @@ export default class BlockOutletRootContainer extends Component {} = this.args;// force tracking the value+ // eslint-disable-next-line @typescript-eslint/no-unused-expressionsthis.args.showVisualOverlay;if (!rawChildren?.length) {return [];}- const owner = getOwner(this);+ // A rendered component is always Ember-owned.+ const owner = getOwner(this)!;const baseHierarchy = outletName;// Step 1: Evaluate conditions - THIS IS NOW TRACKED!@@ -129,7 +144,6 @@ export default class BlockOutletRootContainer extends Component {);// Step 2: Create components from processed entries- // @ts-ignore - TS2322: ChildBlockResult type compatible with return typereturn processBlockEntries({entries: processedEntries,cache: this.#componentCache,@@ -153,30 +167,22 @@ export default class BlockOutletRootContainer extends Component {** Container blocks have an implicit condition: they must have at least* one visible child. This is evaluated bottom-up (children first).- *- * @param {Array<Object>} entries - Array of block entries to process.- * @param {Object} outletArgs - Outlet arguments for condition evaluation.- * @param {Object} blocksService - Blocks service for condition evaluation.- * @param {boolean} showGhosts - If true, keep all blocks for ghost rendering.- * @param {boolean} isLoggingEnabled - If true, log condition evaluation.- * @param {string} baseHierarchy - Base hierarchy path for logging.- * @returns {Array<Object>} Processed entries with visibility metadata.*/#preprocessEntries(- entries,- outletArgs,- blocksService,- showGhosts,- isLoggingEnabled,- baseHierarchy- ) {- const result = [];+ entries: BlockEntry[],+ outletArgs: Record<string, unknown>,+ blocksService: Blocks,+ showGhosts: boolean,+ isLoggingEnabled: boolean,+ baseHierarchy: string+ ): BlockEntry[] {+ const result: BlockEntry[] = [];for (const entry of entries) {// Shallow clone to add visibility metadata without mutating the original// layout entry. The layout is immutable after registration, so we create// a copy to attach __visible and __failureReason properties.- const entryClone = { ...entry };+ const entryClone: BlockEntry = { ...entry };// Resolve block referenceconst resolvedBlock = tryResolveBlock(entryClone.block);@@ -190,10 +196,7 @@ export default class BlockOutletRootContainer extends Component {continue;}- const blockClass =- /** @type {import("discourse/lib/blocks/-internals/registry/block").BlockClass} */ (- resolvedBlock- );+ const blockClass = resolvedBlock;const blockMeta = getBlockMetadata(blockClass);const blockName = blockMeta?.blockName || "unknown";const isContainer = blockMeta?.isContainer ?? false;@@ -205,7 +208,7 @@ export default class BlockOutletRootContainer extends Component {const conditionsPassed = entryClone.conditions? withDebugGroup(blockName,- entryClone.id,+ entryClone.id ?? null,baseHierarchy,isLoggingEnabled,() =>@@ -219,12 +222,13 @@ export default class BlockOutletRootContainer extends Component {// For containers: recursively process children first (bottom-up evaluation)// This determines which children are visible before we check if container has anylet hasVisibleChildren = true; // Non-containers always "have" visible children- if (isContainer && entryClone.children?.length) {+ const children = entryClone.children;+ if (isContainer && children?.length) {// Recursively preprocess children - this computes their visibility.// Include the container's ID in the hierarchy for better debug identification.const containerSuffix = entryClone.id ? `(#${entryClone.id})` : "";const processedChildren = this.#preprocessEntries(- entryClone.children,+ children,outletArgs,blocksService,showGhosts,diff --git a/frontend/discourse/app/lib/blocks/-internals/css.js b/frontend/discourse/app/lib/blocks/-internals/css.jsdeleted file mode 100644index 1ca69d7eaef..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/css.js+++ /dev/null@@ -1,54 +0,0 @@-// @ts-check-import cssIdentifier from "discourse/helpers/css-identifier";--/**- * Returns the CSS-safe version of an outlet name.- *- * Converts namespaced outlet names (e.g., "plugin:outlet") to valid CSS- * identifiers by replacing colons with hyphens and dasherizing.- *- * @param {string} outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").- * @returns {string} The CSS-safe name (e.g., "hero-blocks", "plugin-sidebar").- */-export function outletClassName(outletName) {- return cssIdentifier(outletName);-}--/**- * Returns the container CSS class name for a block outlet.- *- * Follows the BEM-like pattern: `{safe-outlet-name}__container`.- * For example, outlet "hero-blocks" produces "hero-blocks__container".- *- * @param {string} outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").- * @returns {string} The CSS class name (e.g., "hero-blocks__container").- */-export function outletContainerClassName(outletName) {- return `${outletClassName(outletName)}__container`;-}--/**- * Returns the layout CSS class name for a block outlet.- *- * Follows the BEM-like pattern: `{safe-outlet-name}__layout`.- * For example, outlet "hero-blocks" produces "hero-blocks__layout".- *- * @param {string} outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").- * @returns {string} The CSS class name (e.g., "hero-blocks__layout").- */-export function outletLayoutClassName(outletName) {- return `${outletClassName(outletName)}__layout`;-}--/**- * Returns the CSS container query rule for a block outlet.- *- * Generates the CSS that enables `@container` queries inside block outlets- * by setting the `container` property on the outlet's container element.- *- * @param {string} outletName - The outlet name (e.g., "hero-blocks").- * @returns {string} The CSS rule (e.g., `.hero-blocks__container { container: hero-blocks / inline-size; }`).- */-export function outletContainerRule(outletName) {- return `.${outletContainerClassName(outletName)} { container: ${outletName} / inline-size; }`;-}diff --git a/frontend/discourse/app/lib/blocks/-internals/css.ts b/frontend/discourse/app/lib/blocks/-internals/css.tsnew file mode 100644index 00000000000..94a6b8fbcf4--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/css.ts@@ -0,0 +1,50 @@+import cssIdentifier from "discourse/helpers/css-identifier";++/**+ * Returns the CSS-safe version of an outlet name.+ *+ * Converts namespaced outlet names (e.g., "plugin:outlet") to valid CSS+ * identifiers by replacing colons with hyphens and dasherizing.+ *+ * @param outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").+ * @returns The CSS-safe name (e.g., "hero-blocks", "plugin-sidebar").+ */+export function outletClassName(outletName: string): string {+ return cssIdentifier(outletName);+}++/**+ * Returns the container CSS class name for a block outlet, following the+ * BEM-like pattern `{safe-outlet-name}__container` (e.g. "hero-blocks" →+ * "hero-blocks__container").+ *+ * @param outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").+ * @returns The CSS class name (e.g., "hero-blocks__container").+ */+export function outletContainerClassName(outletName: string): string {+ return `${outletClassName(outletName)}__container`;+}++/**+ * Returns the layout CSS class name for a block outlet, following the BEM-like+ * pattern `{safe-outlet-name}__layout` (e.g. "hero-blocks" →+ * "hero-blocks__layout").+ *+ * @param outletName - The outlet name (e.g., "hero-blocks", "plugin:sidebar").+ * @returns The CSS class name (e.g., "hero-blocks__layout").+ */+export function outletLayoutClassName(outletName: string): string {+ return `${outletClassName(outletName)}__layout`;+}++/**+ * Returns the CSS container-query rule for a block outlet, enabling+ * `@container` queries inside the outlet by setting the `container` property on+ * its container element.+ *+ * @param outletName - The outlet name (e.g., "hero-blocks").+ * @returns The CSS rule (e.g., `.hero-blocks__container { container: hero-blocks / inline-size; }`).+ */+export function outletContainerRule(outletName: string): string {+ return `.${outletContainerClassName(outletName)} { container: ${outletName} / inline-size; }`;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/debug-hooks.js b/frontend/discourse/app/lib/blocks/-internals/debug-hooks.tssimilarity index 50%rename from frontend/discourse/app/lib/blocks/-internals/debug-hooks.jsrename to frontend/discourse/app/lib/blocks/-internals/debug-hooks.tsindex c58c79022c9..eaf20bb50cb 100644--- a/frontend/discourse/app/lib/blocks/-internals/debug-hooks.js+++ b/frontend/discourse/app/lib/blocks/-internals/debug-hooks.ts@@ -1,4 +1,3 @@-// @ts-check/*** Debug hooks for block dev-tools integration.*@@ -9,12 +8,16 @@** The debug hooks use TrackedMap for reactivity, enabling Ember's reactivity system* to trigger re-renders when callbacks are set/cleared.- *- * @module discourse/lib/blocks/-internals/debug-hooks*/-+import type Component from "@glimmer/component";+import type Owner from "@ember/owner";import { trackedMap } from "@ember/reactive/collections";import { FAILURE_TYPE } from "discourse/lib/blocks/-internals/patterns";+import type {+ BlockClass,+ BlockEntry,+ ChildBlockResult,+} from "discourse/lib/blocks/-internals/types";/*** Callback key constants for the debug hooks registry.@@ -38,6 +41,26 @@ export const DEBUG_CALLBACK = Object.freeze({GHOST_CHILDREN_CREATOR: "ghostChildrenCreator",});+/**+ * A debug callback registered by dev-tools. Callbacks vary in arity and+ * return shape depending on which `DEBUG_CALLBACK` key they're registered+ * under, so callers narrow the return value at the call site.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type DebugCallback = (...args: any[]) => unknown;++/**+ * The logger interface handed to conditions for logging, as returned by the+ * LOGGER_INTERFACE callback.+ */+export interface DebugLoggerInterface {+ logCondition: DebugCallback;+ updateCombinatorResult: DebugCallback;+ updateConditionResult: DebugCallback;+ logParamGroup: DebugCallback;+ logRouteState: DebugCallback;+}+/*** Singleton class that manages debug callback hooks for the block rendering system.* Uses TrackedMap for reactivity, so components accessing these values will re-render@@ -47,20 +70,19 @@ class DebugHooks {/*** Tracked callback registry for debug hooks.* Using TrackedMap enables reactivity when callbacks are set/cleared.- *- * @type {Map<string, Function|null>}*/- #callbacks = trackedMap(- Object.values(DEBUG_CALLBACK).map((key) => [key, null])- );+ #callbacks: Map<string, DebugCallback | null> = trackedMap<+ string,+ DebugCallback | null+ >(Object.values(DEBUG_CALLBACK).map((key): [string, null] => [key, null]));/*** Gets a debug callback from the registry.*- * @param {string} key - The callback key (use DEBUG_CALLBACK constants).- * @returns {Function|null} The callback function, or null if not set.+ * @param key - The callback key (use DEBUG_CALLBACK constants).+ * @returns The callback function, or null/undefined if not set.*/- getCallback(key) {+ getCallback(key: string): DebugCallback | null | undefined {return this.#callbacks.get(key);}@@ -68,11 +90,11 @@ class DebugHooks {* Sets a debug callback in the registry.* Used by dev-tools to register debug hooks.*- * @param {string} key - The callback key (use DEBUG_CALLBACK constants).- * @param {Function|null} value - The callback function, or null to clear.- * @throws {Error} If the key is not a valid callback key.+ * @param key - The callback key (use DEBUG_CALLBACK constants).+ * @param value - The callback function, or null to clear.+ * @throws If the key is not a valid callback key.*/- setCallback(key, value) {+ setCallback(key: string, value: DebugCallback | null): void {if (!this.#callbacks.has(key)) {const validKeys = Object.values(DEBUG_CALLBACK).join(", ");throw new Error(@@ -86,49 +108,64 @@ class DebugHooks {* Returns whether console logging is enabled.* Convenience getter that invokes the blockLogging callback.*- * @returns {boolean} True if logging is enabled.+ * @returns True if logging is enabled.*/- get isBlockLoggingEnabled() {- return this.#callbacks.get(DEBUG_CALLBACK.BLOCK_LOGGING)?.() ?? false;+ get isBlockLoggingEnabled(): boolean {+ return (+ (this.#callbacks.get(DEBUG_CALLBACK.BLOCK_LOGGING)?.() as+ | boolean+ | undefined) ?? false+ );}/*** Returns the outlet info component if outlet boundaries are enabled.* Invokes the OUTLET_INFO_COMPONENT callback which returns the component- * when enabled, or null when disabled.+ * when enabled, or a nullish value when disabled.*- * @returns {typeof import("@glimmer/component").default|null} The outlet info component, or null.+ * @returns The outlet info component, or null.*/- get outletInfoComponent() {- return this.#callbacks.get(DEBUG_CALLBACK.OUTLET_INFO_COMPONENT)?.();+ get outletInfoComponent(): typeof Component | null | undefined {+ return this.#callbacks.get(DEBUG_CALLBACK.OUTLET_INFO_COMPONENT)?.() as+ | typeof Component+ | null+ | undefined;}/*** Returns whether outlet boundaries should be shown.* Derived from whether the outlet info component is available.*- * @returns {boolean} True if boundaries should be shown.+ * @returns True if boundaries should be shown.*/- get isOutletBoundaryEnabled() {+ get isOutletBoundaryEnabled(): boolean {return !!this.outletInfoComponent;}/*** Returns whether visual overlay is enabled.*- * @returns {boolean} True if visual overlay is enabled.+ * @returns True if visual overlay is enabled.*/- get isVisualOverlayEnabled() {- return this.#callbacks.get(DEBUG_CALLBACK.VISUAL_OVERLAY)?.() ?? false;+ get isVisualOverlayEnabled(): boolean {+ return (+ (this.#callbacks.get(DEBUG_CALLBACK.VISUAL_OVERLAY)?.() as+ | boolean+ | undefined) ?? false+ );}/*** Returns whether ghost blocks are enabled.*- * @returns {boolean} True if ghost blocks are enabled.+ * @returns True if ghost blocks are enabled.*/- get isGhostBlocksEnabled() {- return this.#callbacks.get(DEBUG_CALLBACK.GHOST_BLOCKS)?.() ?? false;+ get isGhostBlocksEnabled(): boolean {+ return (+ (this.#callbacks.get(DEBUG_CALLBACK.GHOST_BLOCKS)?.() as+ | boolean+ | undefined) ?? false+ );}/**@@ -138,10 +175,15 @@ class DebugHooks {* The interface has methods: logCondition, updateCombinatorResult,* updateConditionResult, logParamGroup, logRouteState.*- * @returns {Object|null} The logger interface, or null if not available.+ * @returns The logger interface, or null if not available.*/- get loggerInterface() {- return this.#callbacks.get(DEBUG_CALLBACK.LOGGER_INTERFACE)?.() ?? null;+ get loggerInterface(): DebugLoggerInterface | null {+ return (+ (this.#callbacks.get(DEBUG_CALLBACK.LOGGER_INTERFACE)?.() as+ | DebugLoggerInterface+ | null+ | undefined) ?? null+ );}}@@ -151,21 +193,69 @@ class DebugHooks {*/export const debugHooks = new DebugHooks();+/**+ * Ghost component data produced by the BLOCK_DEBUG dev-tools callback, before+ * the caller attaches a stable rendering `key`.+ */+export type DebugGhostData = Omit<ChildBlockResult, "key">;++/**+ * Data describing a block to ghost, passed to the BLOCK_DEBUG callback.+ */+export interface DebugGhostBlockData {+ /** The block name; absent when the block carries no decorator metadata. */+ name: string | undefined;+ /** The block's unique ID (if set). */+ id?: string;+ /** Block arguments. */+ args?: Record<string, unknown>;+ /** Container arguments. */+ containerArgs?: Record<string, unknown>;+ /** Block conditions. */+ conditions?: BlockEntry["conditions"];+ /** Type of failure (from FAILURE_TYPE). */+ failureType?: string;+ /** Custom failure reason message. */+ failureReason?: string;+ /** Ghost children for containers. */+ children?: ChildBlockResult[] | null;+}++/**+ * Context passed to the BLOCK_DEBUG callback alongside the ghost block data.+ */+export interface DebugGhostContext {+ /** The outlet/hierarchy name for display. */+ outletName: string;+ /** Outlet arguments. */+ outletArgs?: Record<string, unknown>;+}++/**+ * Options for `handleOptionalMissingBlock()`.+ */+export interface HandleOptionalMissingBlockOptions {+ /** The name of the missing block. */+ blockName: string;+ /** The block entry. */+ entry: BlockEntry;+ /** The hierarchy path for logging. */+ hierarchy: string;+ /** Whether debug logging is enabled. */+ isLoggingEnabled: boolean;+ /** Whether to show ghost components. */+ showGhosts: boolean;+ /** Stable unique key for this block. */+ key: string;+}+/*** Handles an optional missing block by logging and optionally creating a ghost.** When a block reference ends with `?` but the block is not registered, this* function handles the logging and ghost component creation.*- * @param {Object} options - Options for handling the missing block.- * @param {string} options.blockName - The name of the missing block.- * @param {Object} options.entry - The block entry.- * @param {string} options.hierarchy - The hierarchy path for logging.- * @param {boolean} options.isLoggingEnabled - Whether debug logging is enabled.- * @param {boolean} options.showGhosts - Whether to show ghost components.- * @param {string} options.key - Stable unique key for this block.- * @returns {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult|null}- * Ghost component data with key if showGhosts is true, null otherwise.+ * @returns Ghost component data with key if showGhosts is true, null otherwise.*/export function handleOptionalMissingBlock({blockName,@@ -174,7 +264,7 @@ export function handleOptionalMissingBlock({isLoggingEnabled,showGhosts,key,-}) {+}: HandleOptionalMissingBlockOptions): ChildBlockResult | null {// Log if debug logging is enabledif (isLoggingEnabled) {debugHooks.getCallback(DEBUG_CALLBACK.OPTIONAL_MISSING_LOG)?.(@@ -213,18 +303,18 @@ export function handleOptionalMissingBlock({* If a block has an id, it replaces the index (since the id is unique):* - `baseHierarchy/group(#my-id)`*- * @param {string} blockName - The block name.- * @param {string|null} blockId - The block's unique id (if set).- * @param {string} baseHierarchy - The base hierarchy path.- * @param {Map<string, number>} containerCounts - Map tracking container counts.- * @returns {string} The full container path.+ * @param blockName - The block name.+ * @param blockId - The block's unique id (if set).+ * @param baseHierarchy - The base hierarchy path.+ * @param containerCounts - Map tracking container counts.+ * @returns The full container path.*/export function buildContainerPath(- blockName,- blockId,- baseHierarchy,- containerCounts-) {+ blockName: string,+ blockId: string | null | undefined,+ baseHierarchy: string,+ containerCounts: Map<string, number>+): string {// Always increment the counter for consistent indexing of blocks without ids.const count = containerCounts.get(blockName) ?? 0;containerCounts.set(blockName, count + 1);@@ -241,22 +331,15 @@ export function buildContainerPath(* Used by both `createGhostBlock` (entry-processing time) and `asGhost`* (render time) to avoid duplicating the callback invocation logic.*- * @param {Object} blockData - Data describing the block to ghost.- * @param {string} blockData.name - The block name.- * @param {string} [blockData.id] - The block's unique ID (if set).- * @param {Object} [blockData.args] - Block arguments.- * @param {Object} [blockData.containerArgs] - Container arguments.- * @param {Array} [blockData.conditions] - Block conditions.- * @param {string} [blockData.failureType] - Type of failure (from FAILURE_TYPE).- * @param {string} [blockData.failureReason] - Custom failure reason message.- * @param {Array} [blockData.children] - Ghost children for containers.- * @param {Object} context - Context for the ghost.- * @param {string} context.outletName - The outlet/hierarchy name for display.- * @param {Object} [context.outletArgs] - Outlet arguments.- * @returns {Object|null} Ghost data with Component property, or null if callback+ * @param blockData - Data describing the block to ghost.+ * @param context - Context for the ghost.+ * @returns Ghost data with Component property, or null if callback* not set or didn't return a component.*/-export function createDebugGhost(blockData, context) {+export function createDebugGhost(+ blockData: DebugGhostBlockData,+ context: DebugGhostContext+): DebugGhostData | null {const ghostData = debugHooks.getCallback(DEBUG_CALLBACK.BLOCK_DEBUG)?.({...blockData,@@ -264,9 +347,43 @@ export function createDebugGhost(blockData, context) {conditionsPassed: false,},context- );+ ) as DebugGhostData | undefined;- return ghostData?.Component ? ghostData : null;+ return ghostData && ghostData.Component ? ghostData : null;+}++/**+ * A function that resolves a block reference (string name or class) to a+ * block class, an optional-missing marker, or null when unresolved. Used+ * here only as a value relayed to the GHOST_CHILDREN_CREATOR callback, not+ * called directly by this module.+ */+export type ResolveBlockFn = (blockRef: string | BlockClass) => unknown;++/**+ * Options for `createGhostBlock()`.+ */+export interface CreateGhostBlockOptions {+ /** The block name. */+ blockName: string;+ /** The block entry. */+ entry: BlockEntry;+ /** The hierarchy path for display. */+ hierarchy: string;+ /** Container path for child hierarchies. */+ containerPath?: string;+ /** Whether this block is a container. */+ isContainer: boolean;+ /** The application owner. */+ owner: Owner;+ /** Outlet arguments. */+ outletArgs?: Record<string, unknown>;+ /** Whether debug logging is enabled. */+ isLoggingEnabled: boolean;+ /** Function to resolve block references. */+ resolveBlockFn: ResolveBlockFn;+ /** Stable unique key for this block. */+ key: string;}/**@@ -275,19 +392,7 @@ export function createDebugGhost(blockData, context) {* Ghost components are shown in debug mode to visualize blocks that failed* their conditions or have no visible children.*- * @param {Object} options - Options for creating the ghost.- * @param {string} options.blockName - The block name.- * @param {Object} options.entry - The block entry.- * @param {string} options.hierarchy - The hierarchy path for display.- * @param {string|undefined} options.containerPath - Container path for child hierarchies.- * @param {boolean} options.isContainer - Whether this block is a container.- * @param {import("@ember/owner").default} options.owner - The application owner.- * @param {Object} options.outletArgs - Outlet arguments.- * @param {boolean} options.isLoggingEnabled - Whether debug logging is enabled.- * @param {Function} options.resolveBlockFn - Function to resolve block references.- * @param {string} options.key - Stable unique key for this block.- * @returns {import("discourse/lib/blocks/-internals/entry-processing").ChildBlockResult|null}- * Ghost component data with key if successful, null otherwise.+ * @returns Ghost component data with key if successful, null otherwise.*/export function createGhostBlock({blockName,@@ -300,10 +405,10 @@ export function createGhostBlock({isLoggingEnabled,resolveBlockFn,key,-}) {+}: CreateGhostBlockOptions): ChildBlockResult | null {// For container blocks with children that failed due to no visible children,// recursively create ghost children so they appear nested in the debug overlay.- let ghostChildren = null;+ let ghostChildren: ChildBlockResult[] | null | undefined = null;if (isContainer &&entry.children?.length &&@@ -318,7 +423,7 @@ export function createGhostBlock({outletArgs,isLoggingEnabled,resolveBlockFn- );+ ) as ChildBlockResult[] | undefined;}const ghostData = createDebugGhost(@@ -342,20 +447,20 @@ export function createGhostBlock({* Executes a function within a debug console group.* Ensures START_GROUP and END_GROUP callbacks are always paired.*- * @param {string} blockName - The block name for the group label.- * @param {string|null} blockId - The block's unique ID (if set).- * @param {string} hierarchy - The hierarchy path for context.- * @param {boolean} isLoggingEnabled - Whether debug logging is active.- * @param {() => boolean} fn - Function to execute that returns the condition result.- * @returns {boolean} The result of the function execution.+ * @param blockName - The block name for the group label.+ * @param blockId - The block's unique ID (if set).+ * @param hierarchy - The hierarchy path for context.+ * @param isLoggingEnabled - Whether debug logging is active.+ * @param fn - Function to execute that returns the condition result.+ * @returns The result of the function execution.*/export function withDebugGroup(- blockName,- blockId,- hierarchy,- isLoggingEnabled,- fn-) {+ blockName: string,+ blockId: string | null,+ hierarchy: string,+ isLoggingEnabled: boolean,+ fn: () => boolean+): boolean {if (!isLoggingEnabled) {return fn();}diff --git a/frontend/discourse/app/lib/blocks/-internals/decorator.js b/frontend/discourse/app/lib/blocks/-internals/decorator.jsdeleted file mode 100644index 7a48aea5855..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/decorator.js+++ /dev/null@@ -1,376 +0,0 @@-// @ts-check-/**- * Block Decorator Module- *- * This module provides the @block decorator and related authorization utilities.- * The authorization model uses private symbols and WeakMaps to prevent external- * code from spoofing block authorization or bypassing validation.- *- * Key concepts:- * - AUTH_TOKEN: A private symbol used to verify authorized block rendering contexts- * - blockMetadataMap: WeakMap tracking which classes are blocks and their metadata- * - rootBlockClass: Single variable holding the root block class (set via registerRootBlock)- *- * @module discourse/lib/blocks/-internals/decorator- */-import Component from "@glimmer/component";-import {- getInternalComponentManager,- setInternalComponentManager,- // @ts-ignore - @glimmer/manager types not provided by ember-source-} from "@glimmer/manager";-import { raiseBlockError } from "discourse/lib/blocks/-internals/error";-import {- validateArgsSchema,- validateChildArgsSchema,-} from "discourse/lib/blocks/-internals/validation/block-args";-import {- validateAndParseBlockName,- validateBlockOptions,- validateOutletRestrictions,-} from "discourse/lib/blocks/-internals/validation/block-decorator";-import { validateConstraintsSchema } from "discourse/lib/blocks/-internals/validation/constraints";--/*- * Authorization System- *- * IMPORTANT: These values MUST NOT be exported.- *- * The authorization model works as follows:- * 1. AUTH_TOKEN is a secret symbol known only to this module- * 2. blockMetadataMap tracks which classes are decorated with @block- * 3. rootBlockClass holds the single block that can be rendered directly (set via registerRootBlock)- * 4. Child blocks receive AUTH_TOKEN via the __block$ arg from their parent- * 5. BlockComponentManager verifies authorization before instantiation- *- * This prevents:- * - Using blocks directly in templates (bypassing BlockOutlet)- * - Spoofing block authorization by setting properties on classes- * - Accessing authorization state from external code- */--/**- * Secret token used to authorize block rendering.- * Passed via __block$ arg from parent containers to child blocks.- */-const AUTH_TOKEN = Symbol("block-auth-token");--/**- * @typedef {Object} BlockMetadataEntry- * @property {boolean} isContainer - Whether the block is a container.- * @property {string} blockName - The block's full name identifier (e.g., "theme:tactile:hero-banner").- * @property {string} shortName - The block's plain name without namespace (e.g., "hero-banner").- * @property {string|null} namespace - The parsed namespace for CSS (e.g., "my-plugin" or "theme-tactile").- * @property {"core"|"plugin"|"theme"} namespaceType - The type of namespace.- * @property {string} description - Human-readable description of the block.- * @property {string|string[]|Function|null} decoratorClassNames - CSS classNames from decorator.- * @property {Object|null} args - Args schema for the block.- * @property {Object|null} childArgs - Child args schema (containers only).- * @property {Object|null} constraints - Cross-arg validation constraints.- * @property {Function|null} validate - Custom validation function.- * @property {readonly string[]|null} allowedOutlets - Allowed outlet patterns.- * @property {readonly string[]|null} deniedOutlets - Denied outlet patterns.- */--/**- * Maps block classes to their metadata.- * Using WeakMap ensures:- * - Classes are garbage collected when no longer referenced- * - Authorization state cannot be discovered via Object.getOwnPropertySymbols()- *- * @type {WeakMap<Function, BlockMetadataEntry>}- */-const blockMetadataMap = new WeakMap();--/**- * The single root block class (BlockOutlet).- * Only one block can be the root - once set, it cannot be changed.- * This prevents any other block from claiming root status.- *- * @type {Function|null}- */-let rootBlockClass = null;--/**- * Registers a block class as the root block that can be rendered directly- * without authorization. Only one root block can be registered.- *- * @param {Function} klass - The block class to register as root.- */-export function registerRootBlock(klass) {- if (rootBlockClass !== null) {- raiseBlockError(- `Only one root block is allowed. ` +- `"${rootBlockClass.name}" is already registered as the root block.`- );- }- rootBlockClass = klass;-}--/**- * Custom component manager proxy that enforces block authorization.- *- * Blocks can only be instantiated in two authorized scenarios:- * 1. As a root block - The class is the rootBlockClass (set via registerRootBlock)- * 2. As a child of a container - The parent passes __block$ arg with AUTH_TOKEN- *- * This prevents blocks from being used directly in templates, ensuring they- * can only be rendered through the BlockOutlet system.- */-const BlockComponentManager = new Proxy(- getInternalComponentManager(Component),- {- get(target, prop) {- if (prop === "create") {- return function (owner, klass, args) {- // Check if this is the root block (BlockOutlet)- const isRootBlock = klass === rootBlockClass;-- // Check if this is an authorized child (parent passes __block$ secret token)- let isAuthorizedChild = false;- const named = args?.named;- if (named?.names?.includes("__block$")) {- const ref = named.get("__block$");- isAuthorizedChild = ref.compute() === AUTH_TOKEN;- }-- if (!isRootBlock && !isAuthorizedChild) {- const blockName =- blockMetadataMap.get(klass)?.blockName || klass.name;- throw new Error(- `Block "${blockName}" cannot be used directly in templates. ` +- `Blocks can only be rendered inside BlockOutlets or container blocks.`- );- }-- return target.create(...arguments);- };- }- return Reflect.get(target, prop);- },- }-);--/**- * Schema for block argument validation.- *- * @typedef {Object} ArgSchema- * @property {"string"|"number"|"boolean"|"array"|"any"} type - The argument type (required)- * @property {boolean} [required=false] - Whether the argument is required- * @property {*} [default] - Default value for the argument- * @property {"string"|"number"|"boolean"} [itemType] - Item type for array arguments- * @property {RegExp} [pattern] - Regex pattern for string validation- * @property {number} [minLength] - Minimum length for string or array- * @property {number} [maxLength] - Maximum length for string or array- * @property {number} [min] - Minimum value for number- * @property {number} [max] - Maximum value for number- * @property {boolean} [integer] - Whether number must be an integer- * @property {Array} [enum] - Allowed values for the argument- * @property {Array} [itemEnum] - Allowed values for array items- */--/**- * Decorator that transforms a Glimmer component into a block component.- *- * Block components have special authorization constraints:- * - They can only be rendered inside BlockOutlets or container blocks- * - They cannot be used directly in templates- * - They receive special args for authorization and hierarchy management- *- * @experimental This API is under active development and may change or be removed- * in future releases without prior notice. Use with caution in production environments.- *- * @param {string} name - Unique identifier for the block. Supports three namespacing formats:- * - Core blocks: `"block-name"` (e.g., "hero-banner", "sidebar-panel")- * - Plugin blocks: `"plugin-name:block-name"` (e.g., "my-plugin:custom-card")- * - Theme blocks: `"theme:theme-name:block-name"` (e.g., "theme:tactile:hero-section")- * Names must use lowercase letters, numbers, and hyphens only.- *- * @param {Object} [options] - Configuration options for the block.- *- * @param {boolean} [options.container=false] - If true, this block can contain nested child blocks.- *- * @param {string} [options.description] - Human-readable description of the block.- *- * @param {Object.<string, ArgSchema>} [options.args] - Schema for block arguments.- *- * @param {Object.<string, ArgSchema>} [options.childArgs] - Schema for args passed to children- * of this container block. Only valid when container: true.- *- * @param {Object} [options.constraints] - Cross-arg validation constraints.- *- * @param {Function} [options.validate] - Custom validation function.- *- * @param {string|string[]|((args: Object) => string)} [options.classNames] - Additional CSS classes.- *- * @param {string[]} [options.allowedOutlets] - Glob patterns for allowed outlets.- *- * @param {string[]} [options.deniedOutlets] - Glob patterns for denied outlets.- *- * @returns {Function} Decorator function that returns the decorated class- *- * @example- * // Simple block- * @block("my-card")- * class MyCard extends Component { ... }- *- * @example- * // Container block- * @block("my-section", { container: true })- * class MySection extends Component { ... }- *- */-export function block(name, options = {}) {- // === Decoration-time validation ===- validateBlockOptions(name, options);- const parsed = validateAndParseBlockName(name);-- // Extract all options with defaults- const {- container: isContainer = false,- classNames: decoratorClassNames = null,- description = "",- args: argsSchema = null,- childArgs: childArgsSchema = null,- constraints = null,- validate: validateFn = null,- allowedOutlets = null,- deniedOutlets = null,- } = options;-- // Validate arg schema structure and types- validateArgsSchema(argsSchema, name);-- // Validate childArgs is only allowed on container blocks- if (childArgsSchema && !isContainer) {- raiseBlockError(- `Block "${name}": "childArgs" is only valid for container blocks (container: true).`- );- }-- // Validate classNames type (string, array, or function)- if (- decoratorClassNames != null &&- typeof decoratorClassNames !== "string" &&- typeof decoratorClassNames !== "function" &&- !Array.isArray(decoratorClassNames)- ) {- raiseBlockError(- `Block "${name}": "classNames" must be a string, array, or function.`- );- }-- // Validate childArgs schema structure and types- validateChildArgsSchema(childArgsSchema, name);-- // Validate constraints schema- validateConstraintsSchema(constraints, argsSchema, name);-- // Validate that validate is a function if provided- if (validateFn !== null && typeof validateFn !== "function") {- raiseBlockError(- `Block "${name}": "validate" must be a function, got ${typeof validateFn}.`- );- }-- // Validate outlet restriction patterns- validateOutletRestrictions(name, allowedOutlets, deniedOutlets);-- return function (target) {- setInternalComponentManager(BlockComponentManager, target);-- if (!(target.prototype instanceof Component)) {- raiseBlockError("@block target must be a Glimmer component class");- return target;- }-- // Create and register metadata object with all block information- const metadata = Object.freeze({- allowedOutlets: allowedOutlets- ? Object.freeze([...allowedOutlets])- : null,- args: argsSchema ? Object.freeze(argsSchema) : null,- blockName: name,- childArgs: childArgsSchema ? Object.freeze(childArgsSchema) : null,- constraints: constraints ? Object.freeze(constraints) : null,- decoratorClassNames,- deniedOutlets: deniedOutlets ? Object.freeze([...deniedOutlets]) : null,- description,- isContainer,- namespace: parsed.namespace,- namespaceType: parsed.type,- shortName: parsed.name,- validate: validateFn,- });-- blockMetadataMap.set(target, metadata);-- return target;- };-}--/**- * Creates the args object for a child block with reactive getters for context args.- *- * This function embeds the AUTH_TOKEN in the __block$ property, which is how- * child blocks are authorized to render. The token is not exposed - it's- * embedded in the returned object.- *- * Context args are defined as getters rather than direct properties. This allows- * `curryComponent` to maintain a stable component identity while enabling reactive- * updates when the getter values change. Without getters, changing any arg would- * require creating a new curried component, breaking Ember's identity-based rendering.- *- * @param {Object} entryArgs - User-provided args from the layout entry.- * @param {Object} contextArgs - Rendering context to define as reactive getters.- * @returns {Object} The merged args object ready for `curryComponent`.- */-export function createBlockArgsWithReactiveGetters(entryArgs, contextArgs) {- const blockArgs = {- ...entryArgs,- __block$: AUTH_TOKEN,- };-- // Dynamically define reactive getters for each context arg- /** @type {PropertyDescriptorMap} */- const propertyDescriptors = {};- for (const [key, value] of Object.entries(contextArgs)) {- propertyDescriptors[key] = {- get() {- return value;- },- enumerable: true,- };- }- Object.defineProperties(blockArgs, propertyDescriptors);-- return blockArgs;-}--/**- * Gets all metadata for a component registered with @block.- *- * Returns a flat object containing all block information:- * - `blockName` - Full block name (e.g., "theme:my-theme:heading")- * - `shortName` - Plain name without namespace (e.g., "heading")- * - `namespace` - Full namespace for CSS ("my-plugin" or "theme-tactile") or null for core- * - `namespaceType` - "core" | "plugin" | "theme"- * - `isContainer` - Whether block is a container- * - `description` - Human-readable description- * - `decoratorClassNames` - CSS classNames from decorator- * - `args` - Args schema- * - `childArgs` - Child args schema (containers only)- * - `constraints` - Cross-arg validation constraints- * - `validate` - Custom validation function- * - `allowedOutlets` - Allowed outlet patterns- * - `deniedOutlets` - Denied outlet patterns- *- * @experimental This API is under active development and may change or be removed- * in future releases without prior notice. Use with caution in production environments.- *- * @param {Function} component - The component to get metadata for.- * @returns {Object|null} The block metadata object, or null if not a block.- */-export function getBlockMetadata(component) {- return blockMetadataMap.get(component) ?? null;-}diff --git a/frontend/discourse/app/lib/blocks/-internals/decorator.ts b/frontend/discourse/app/lib/blocks/-internals/decorator.tsnew file mode 100644index 00000000000..519083bd154--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/decorator.ts@@ -0,0 +1,330 @@+/**+ * Block Decorator Module+ *+ * This module provides the `@block` decorator and related authorization+ * utilities. The authorization model uses private symbols and WeakMaps to+ * prevent external code from spoofing block authorization or bypassing+ * validation.+ *+ * Key concepts:+ * - `AUTH_TOKEN`: a private symbol used to verify authorized block rendering contexts.+ * - `blockMetadataMap`: a WeakMap tracking which classes are blocks and their metadata.+ * - `rootBlockClass`: a single variable holding the root block class (set via `registerRootBlock`).+ */+import Component from "@glimmer/component";+import {+ getInternalComponentManager,+ setInternalComponentManager,+} from "@glimmer/manager";+import type { BlockMetadata, BlockOptions } from "discourse/blocks/types";+import { raiseBlockError } from "discourse/lib/blocks/-internals/error";+import type { BlockClass } from "discourse/lib/blocks/-internals/types";+import {+ validateArgsSchema,+ validateChildArgsSchema,+} from "discourse/lib/blocks/-internals/validation/block-args";+import {+ validateAndParseBlockName,+ validateBlockOptions,+ validateOutletRestrictions,+} from "discourse/lib/blocks/-internals/validation/block-decorator";+import { validateConstraintsSchema } from "discourse/lib/blocks/-internals/validation/constraints";++/*+ * Authorization System+ *+ * IMPORTANT: These values MUST NOT be exported.+ *+ * The authorization model works as follows:+ * 1. AUTH_TOKEN is a secret symbol known only to this module.+ * 2. blockMetadataMap tracks which classes are decorated with @block.+ * 3. rootBlockClass holds the single block that can be rendered directly (set via registerRootBlock).+ * 4. Child blocks receive AUTH_TOKEN via the __block$ arg from their parent.+ * 5. BlockComponentManager verifies authorization before instantiation.+ *+ * This prevents:+ * - Using blocks directly in templates (bypassing BlockOutlet).+ * - Spoofing block authorization by setting properties on classes.+ * - Accessing authorization state from external code.+ */++/**+ * Secret token used to authorize block rendering. Passed via the `__block$` arg+ * from parent containers to child blocks.+ */+const AUTH_TOKEN = Symbol("block-auth-token");++/**+ * The minimal surface of Glimmer's internal component manager that this module+ * relies on. Wrapped in a Proxy to enforce block authorization on `create`.+ */+interface InternalManager {+ create(...args: unknown[]): unknown;+}++/**+ * The captured named-args reference Glimmer passes to `create`. Only the members+ * needed to read the `__block$` authorization token are described.+ */+interface CapturedArgs {+ named?: {+ names: string[];+ get(name: string): { compute(): unknown };+ };+}++/**+ * Maps block classes to their metadata. A WeakMap ensures classes are garbage+ * collected when no longer referenced and that authorization state cannot be+ * discovered via `Object.getOwnPropertySymbols()`. The key is widened to+ * `object` (rather than a block-class type) because the registry probes it with+ * lazy block factory functions too, and both classes and factories are objects.+ */+const blockMetadataMap = new WeakMap<object, BlockMetadata>();++/**+ * The single root block class (BlockOutlet). Only one block can be the root;+ * once set it cannot be changed, which prevents any other block from claiming+ * root status.+ */+let rootBlockClass: BlockClass | null = null;++/**+ * Registers a block class as the root block that can be rendered directly+ * without authorization. Only one root block can be registered.+ *+ * @param klass - The block class to register as the root.+ */+export function registerRootBlock(klass: BlockClass): void {+ if (rootBlockClass !== null) {+ // `BlockClass` is a construct signature, so `.name` (a runtime Function+ // static) is read through a cast.+ const existingName = (rootBlockClass as { name: string }).name;+ raiseBlockError(+ `Only one root block is allowed. ` ++ `"${existingName}" is already registered as the root block.`+ );+ }+ rootBlockClass = klass;+}++/**+ * Custom component-manager proxy that enforces block authorization. Blocks can+ * only be instantiated in two authorized scenarios:+ * 1. As the root block (the class is `rootBlockClass`, set via `registerRootBlock`).+ * 2. As a child of a container (the parent passes the `__block$` arg with `AUTH_TOKEN`).+ *+ * This prevents blocks from being used directly in templates, ensuring they can+ * only be rendered through the BlockOutlet system.+ */+const baseManager = getInternalComponentManager(Component) as InternalManager;++const BlockComponentManager = new Proxy(baseManager, {+ get(target, prop) {+ if (prop === "create") {+ // Glimmer calls `create` with more positional args than the three we+ // inspect (env, dynamic scope, caller, ...). Capture them all with a rest+ // param and forward the full list so no rendering context is dropped.+ return function (...createArgs: unknown[]): unknown {+ const klass = createArgs[1] as BlockClass;+ const args = createArgs[2] as CapturedArgs;++ // Check if this is the root block (BlockOutlet).+ const isRootBlock = klass === rootBlockClass;++ // Check if this is an authorized child (parent passes __block$ secret token).+ let isAuthorizedChild = false;+ const named = args?.named;+ if (named?.names?.includes("__block$")) {+ const ref = named.get("__block$");+ isAuthorizedChild = ref.compute() === AUTH_TOKEN;+ }++ if (!isRootBlock && !isAuthorizedChild) {+ const blockName =+ blockMetadataMap.get(klass)?.blockName ||+ (klass as { name: string }).name;+ throw new Error(+ `Block "${blockName}" cannot be used directly in templates. ` ++ `Blocks can only be rendered inside BlockOutlets or container blocks.`+ );+ }++ return target.create(...createArgs);+ };+ }+ return Reflect.get(target, prop);+ },+});++/**+ * Decorator that transforms a Glimmer component into a block component.+ *+ * Block components have special authorization constraints:+ * - They can only be rendered inside BlockOutlets or container blocks.+ * - They cannot be used directly in templates.+ * - They receive special args for authorization and hierarchy management.+ *+ * @experimental This API is under active development and may change or be+ * removed in future releases without prior notice.+ *+ * @param name - Unique identifier for the block. Supports three namespacing+ * formats: core blocks `"block-name"`, plugin blocks `"plugin-name:block-name"`,+ * and theme blocks `"theme:theme-name:block-name"`. Names must use lowercase+ * letters, numbers, and hyphens only.+ * @param options - Configuration options for the block (see `BlockOptions`).+ * @returns A decorator that returns the decorated class.+ *+ * @example+ * ```js+ * @block("my-card")+ * class MyCard extends Component {}+ *+ * @block("my-section", { container: true })+ * class MySection extends Component {}+ * ```+ */+export function block(+ name: string,+ options: BlockOptions = {}+): <T extends BlockClass & { prototype: unknown }>(target: T) => T {+ // Decoration-time validation.+ validateBlockOptions(name, options);+ const parsed = validateAndParseBlockName(name);++ const {+ container: isContainer = false,+ classNames: decoratorClassNames = null,+ description = "",+ args: argsSchema = null,+ childArgs: childArgsSchema = null,+ constraints = null,+ validate: validateFn = null,+ allowedOutlets = null,+ deniedOutlets = null,+ } = options;++ // Validate arg schema structure and types.+ validateArgsSchema(argsSchema, name);++ // childArgs is only allowed on container blocks.+ if (childArgsSchema && !isContainer) {+ raiseBlockError(+ `Block "${name}": "childArgs" is only valid for container blocks (container: true).`+ );+ }++ // classNames must be a string, array, or function.+ if (+ decoratorClassNames != null &&+ typeof decoratorClassNames !== "string" &&+ typeof decoratorClassNames !== "function" &&+ !Array.isArray(decoratorClassNames)+ ) {+ raiseBlockError(+ `Block "${name}": "classNames" must be a string, array, or function.`+ );+ }++ // Validate childArgs schema structure and types.+ validateChildArgsSchema(childArgsSchema, name);++ // Validate constraints schema.+ validateConstraintsSchema(constraints, argsSchema, name);++ // validate must be a function if provided.+ if (validateFn !== null && typeof validateFn !== "function") {+ raiseBlockError(+ `Block "${name}": "validate" must be a function, got ${typeof validateFn}.`+ );+ }++ // Validate outlet restriction patterns.+ validateOutletRestrictions(name, allowedOutlets, deniedOutlets);++ return (target) => {+ setInternalComponentManager(BlockComponentManager, target);++ if (!(target.prototype instanceof Component)) {+ raiseBlockError("@block target must be a Glimmer component class");+ }++ // Create and register the frozen metadata object with all block information.+ const metadata: BlockMetadata = Object.freeze({+ allowedOutlets: allowedOutlets+ ? Object.freeze([...allowedOutlets])+ : null,+ args: argsSchema ? Object.freeze(argsSchema) : null,+ blockName: name,+ childArgs: childArgsSchema ? Object.freeze(childArgsSchema) : null,+ constraints: constraints ? Object.freeze(constraints) : null,+ decoratorClassNames,+ deniedOutlets: deniedOutlets ? Object.freeze([...deniedOutlets]) : null,+ description,+ isContainer,+ namespace: parsed.namespace,+ namespaceType: parsed.type,+ shortName: parsed.name,+ validate: validateFn,+ });++ blockMetadataMap.set(target, metadata);++ return target;+ };+}++/**+ * Creates the args object for a child block with reactive getters for context+ * args.+ *+ * This embeds the `AUTH_TOKEN` in the `__block$` property, which is how child+ * blocks are authorized to render. Context args are defined as getters rather+ * than direct properties so `curryComponent` can maintain a stable component+ * identity while still updating reactively when the getter values change.+ * Without getters, changing any arg would require a new curried component,+ * breaking Ember's identity-based rendering.+ *+ * @param entryArgs - User-provided args from the layout entry.+ * @param contextArgs - Rendering context to define as reactive getters.+ * @returns The merged args object ready for `curryComponent`.+ */+export function createBlockArgsWithReactiveGetters(+ entryArgs: Record<string, unknown>,+ contextArgs: Record<string, unknown>+): Record<string, unknown> {+ const blockArgs: Record<string, unknown> = {+ ...entryArgs,+ __block$: AUTH_TOKEN,+ };++ // Dynamically define reactive getters for each context arg.+ const propertyDescriptors: PropertyDescriptorMap = {};+ for (const [key, value] of Object.entries(contextArgs)) {+ propertyDescriptors[key] = {+ get() {+ return value;+ },+ enumerable: true,+ };+ }+ Object.defineProperties(blockArgs, propertyDescriptors);++ return blockArgs;+}++/**+ * Gets all metadata for a component registered with `@block`.+ *+ * @experimental This API is under active development and may change or be+ * removed in future releases without prior notice.+ *+ * @param component - The component (or factory) to get metadata for. Accepts+ * nullish values so untyped registration paths can probe safely.+ * @returns The block metadata object, or `null` if not a block.+ */+export function getBlockMetadata(+ component: object | null | undefined+): BlockMetadata | null {+ return component ? (blockMetadataMap.get(component) ?? null) : null;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/entry-processing.js b/frontend/discourse/app/lib/blocks/-internals/entry-processing.jsdeleted file mode 100644index 7fcb4e79cc2..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/entry-processing.js+++ /dev/null@@ -1,254 +0,0 @@-// @ts-check-/**- * Block Entry Processing- *- * This module contains utilities for processing block entries and creating- * renderable components. These functions iterate through pre-processed block- * entries and transform them into curried Glimmer components.- *- * The functions use dependency injection for the authorization-dependent operation- * `createChildBlockFn` to maintain the authorization model in the main block-outlet- * module.- *- * @module discourse/lib/blocks/-internals/entry-processing- */-import {- buildContainerPath,- createGhostBlock,- handleOptionalMissingBlock,-} from "discourse/lib/blocks/-internals/debug-hooks";-import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";-import { isOptionalMissing } from "discourse/lib/blocks/-internals/patterns";-import { tryResolveBlock } from "discourse/lib/blocks/-internals/registry/block";-import { shallowArgsEqual } from "discourse/lib/blocks/-internals/utils";--/**- * Gets or creates a curried component for a leaf block, using cache when possible.- *- * Only leaf blocks (blocks without children) are cached. Container blocks are- * always recreated because their children's visibility may change between- * renders, and caching would result in stale children being displayed.- *- * Cache hit conditions:- * 1. The component class must be the same reference- * 2. The args object must be shallowly equal- *- * @param {Map<string, {ComponentClass: typeof import("@glimmer/component").default, args: Object, result: Object}>} cache - The component cache keyed by stable block keys.- * @param {Object} entry - The block entry with __stableKey and optional children.- * @param {typeof import("@glimmer/component").default} resolvedBlock - The resolved block component class.- * @param {Object} debugContext - Debug context for visual overlay and hierarchy tracking.- * @param {string} debugContext.key - Stable unique key for this block.- * @param {string} debugContext.displayHierarchy - Where the block is rendered (for tooltip display).- * @param {string} debugContext.outletName - The outlet name for wrapper class generation.- * @param {string} [debugContext.containerPath] - Container's full path (for children's __hierarchy).- * @param {Object} [debugContext.conditions] - The block's conditions.- * @param {Object} debugContext.outletArgs - Outlet arguments passed from the parent.- * @param {Array<Object>} [debugContext.processedChildren] - Pre-processed children for container blocks.- * @param {import("@ember/owner").default} owner - The application owner for service lookup.- * @param {Function} createChildBlockFn - Function to create child block components (injected from block-outlet.gjs).- * @returns {ChildBlockResult} The cached or newly created component data with stable key for list rendering.- */-function getOrCreateLeafBlockComponent(- cache,- entry,- resolvedBlock,- debugContext,- owner,- createChildBlockFn-) {- const { key } = debugContext;- const cachedEntry = cache.get(key);- const hasChildren = entry.children?.length > 0;-- // Only cache leaf blocks (no children). Container blocks are always recreated- // to ensure their children reflect current visibility state.- if (- !hasChildren &&- cachedEntry &&- cachedEntry.ComponentClass === resolvedBlock &&- shallowArgsEqual(cachedEntry.args, entry.args)- ) {- return cachedEntry.result;- }-- // Create new curried component- const result = createChildBlockFn(- { ...entry, block: resolvedBlock },- owner,- debugContext- );-- // Cache leaf blocks for future reuse- if (!hasChildren) {- cache.set(key, {- ComponentClass: resolvedBlock,- args: entry.args,- result,- });- }-- return result;-}--/**- * Processes block entries and creates renderable child components.- *- * This function iterates through a list of pre-processed block entries and- * transforms them into renderable components, handling ghost blocks for- * debug mode and optional missing blocks.- *- * @typedef {Object} BlockEntry- * @property {string|typeof import("@glimmer/component").default} block - Block reference (string name or class).- * @property {Object} [args] - Arguments to pass to the block.- * @property {Object} [containerArgs] - Values for parent container's childArgs schema.- * @property {Array<BlockEntry>} [children] - Nested block entries for containers.- * @property {Object|Array<Object>} [conditions] - Conditions that must pass for block to render.- * @property {string} [classNames] - Additional CSS classes for the block wrapper.- * @property {string} [id] - Unique identifier for BEM styling and targeting.- * @property {boolean} __visible - Whether the block passed condition evaluation.- * @property {number} __stableKey - Stable key assigned at registration time.- * @property {string} [__failureType] - The failure type constant (debug mode only).- * @property {string} [__failureReason] - Custom failure reason message (debug mode only).- *- * @typedef {Object} ChildBlockResult- * @property {import("@glint/template").ComponentLike} Component - Curried component ready to render.- * @property {Object} [containerArgs] - Values for parent container's childArgs schema.- * @property {string} key - Stable unique key for list rendering.- * @property {boolean} [isGhost] - True if this is a ghost block (debug mode only).- * @property {(reason: string) => ChildBlockResult|null} [asGhost] - Returns a ghost version of this child with the given reason.- * For regular children, creates a new ghost component (or null if debug mode is disabled).- * For ghost children, returns self (no-op).- *- * @param {Object} options - Rendering options.- * @param {Array<BlockEntry>} options.entries - Pre-processed block entries with visibility metadata.- * @param {Map<string, {ComponentClass: typeof import("@glimmer/component").default, args: Object, result: ChildBlockResult}>} options.cache - Component cache keyed by stable block keys.- * @param {import("@ember/owner").default} options.owner - Application owner for service lookup.- * @param {string} options.baseHierarchy - Current hierarchy path (e.g., "homepage-blocks/section-1").- * @param {string} options.outletName - The outlet name for CSS class generation.- * @param {Object} options.outletArgs - Arguments passed from the outlet to blocks.- * @param {boolean} options.showGhosts - Whether to render ghost blocks for invisible entries.- * @param {boolean} options.isLoggingEnabled - Whether debug logging is active.- * @param {Function} options.createChildBlockFn - Function to create child block components (injected from block-outlet.gjs).- * @returns {Array<ChildBlockResult>} Array of renderable child objects with Component and containerArgs.- */-export function processBlockEntries({- entries,- cache,- owner,- baseHierarchy,- outletName,- outletArgs,- showGhosts,- isLoggingEnabled,- createChildBlockFn,-}) {- const result = [];- const containerCounts = new Map();-- for (const entry of entries) {- // @ts-ignore - entry.block can be string or BlockClass- const resolvedBlock = tryResolveBlock(entry.block);-- // Handle optional missing block (block ref ended with `?` but not registered)- if (isOptionalMissing(resolvedBlock)) {- const key = `optional-missing:${resolvedBlock.name}:${entry.__stableKey}`;- const ghostData = handleOptionalMissingBlock({- blockName: resolvedBlock.name,- entry,- hierarchy: baseHierarchy,- isLoggingEnabled,- showGhosts,- key,- });- if (ghostData) {- result.push(ghostData);- }- continue;- }-- // Skip blocks that haven't resolved yet. Block factories may be resolving- // asynchronously (e.g., lazy-loaded plugins). The component will automatically- // re-render when the factory resolves (via TrackedMap reactivity).- if (!resolvedBlock) {- continue;- }-- const blockClass =- /** @type {import("discourse/lib/blocks/-internals/registry/block").BlockClass} */ (- resolvedBlock- );- const blockMeta = getBlockMetadata(blockClass);- const blockName = blockMeta?.blockName || "unknown";- const isContainer = blockMeta?.isContainer ?? false;-- // Use the stable key assigned at registration time. This key survives- // shallow cloning and ensures DOM identity is maintained when blocks- // are hidden/shown by conditions.- const key = `${blockName}:${entry.__stableKey}`;-- // For containers, build their full path for children's hierarchy.- // The id is included in the path for easier identification in debug tools.- const containerPath = isContainer- ? buildContainerPath(blockName, entry.id, baseHierarchy, containerCounts)- : undefined;-- // For containers with children, recursively process children FIRST- // This creates the child components at the root level, so containers- // receive pre-processed children via @children arg instead of raw entries.- let processedChildren;- if (isContainer && entry.children?.length) {- processedChildren = processBlockEntries({- entries: entry.children,- cache, // Same root cache for all levels- owner,- baseHierarchy: containerPath,- outletName,- outletArgs,- showGhosts,- isLoggingEnabled,- createChildBlockFn,- });- }-- // Render visible blocks- if (entry.__visible) {- result.push(- getOrCreateLeafBlockComponent(- cache,- entry,- blockClass,- {- displayHierarchy: baseHierarchy,- outletName,- containerPath,- conditions: entry.conditions,- outletArgs,- key,- processedChildren, // Pass pre-processed children for containers- },- owner,- createChildBlockFn- )- );- } else if (showGhosts) {- // Show ghost for invisible blocks in debug mode- const ghostData = createGhostBlock({- blockName,- entry,- hierarchy: baseHierarchy,- containerPath,- isContainer,- owner,- outletArgs,- isLoggingEnabled,- resolveBlockFn: tryResolveBlock,- key,- });- if (ghostData) {- result.push(ghostData);- }- }- }-- return result;-}diff --git a/frontend/discourse/app/lib/blocks/-internals/entry-processing.ts b/frontend/discourse/app/lib/blocks/-internals/entry-processing.tsnew file mode 100644index 00000000000..342a77bc4af--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/entry-processing.ts@@ -0,0 +1,284 @@+/**+ * Block Entry Processing+ *+ * This module contains utilities for processing block entries and creating+ * renderable components. These functions iterate through pre-processed block+ * entries and transform them into curried Glimmer components.+ *+ * The functions use dependency injection for the authorization-dependent+ * operation `createChildBlockFn` to keep the authorization model in the main+ * block-outlet module.+ */+import type Owner from "@ember/owner";+import {+ buildContainerPath,+ createGhostBlock,+ handleOptionalMissingBlock,+} from "discourse/lib/blocks/-internals/debug-hooks";+import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";+import { isOptionalMissing } from "discourse/lib/blocks/-internals/patterns";+import { tryResolveBlock } from "discourse/lib/blocks/-internals/registry/block";+import type {+ BlockClass,+ BlockEntry,+ ChildBlockResult,+} from "discourse/lib/blocks/-internals/types";+import { shallowArgsEqual } from "discourse/lib/blocks/-internals/utils";++/** Rendering context threaded through block processing for a single entry. */+interface DebugContext {+ /** Stable unique key for this block. */+ key: string;++ /** Where the block is rendered (used for tooltip display). */+ displayHierarchy: string;++ /** The outlet name, used for wrapper class generation. */+ outletName: string;++ /** The container's full path, used for children's hierarchy. */+ containerPath?: string;++ /** The block's conditions. */+ conditions?: BlockEntry["conditions"];++ /** Outlet arguments passed from the parent. */+ outletArgs: Record<string, unknown>;++ /** Pre-processed children for container blocks. */+ processedChildren?: ChildBlockResult[];+}++/**+ * Creates a renderable child block. Injected from `block-outlet.gts` so the+ * authorization-token logic stays in that module.+ */+export type CreateChildBlockFn = (+ entry: BlockEntry,+ owner: Owner,+ debugContext: DebugContext+) => ChildBlockResult;++/** A cached leaf-block entry, keyed by the block's stable key. */+interface LeafCacheEntry {+ ComponentClass: BlockClass;+ args?: Record<string, unknown>;+ result: ChildBlockResult;+}++export type LeafCache = Map<string, LeafCacheEntry>;++/**+ * Gets or creates a curried component for a leaf block, using the cache when+ * possible.+ *+ * Only leaf blocks (blocks without children) are cached. Container blocks are+ * always recreated because their children's visibility may change between+ * renders, and caching would show stale children.+ *+ * Cache hit conditions: the component class is the same reference, and the args+ * object is shallowly equal.+ *+ * @param cache - The component cache keyed by stable block keys.+ * @param entry - The block entry with `__stableKey` and optional children.+ * @param resolvedBlock - The resolved block component class.+ * @param debugContext - Debug context for the visual overlay and hierarchy tracking.+ * @param owner - The application owner for service lookup.+ * @param createChildBlockFn - Creates child block components (injected from block-outlet).+ * @returns The cached or newly created component data.+ */+function getOrCreateLeafBlockComponent(+ cache: LeafCache,+ entry: BlockEntry,+ resolvedBlock: BlockClass,+ debugContext: DebugContext,+ owner: Owner,+ createChildBlockFn: CreateChildBlockFn+): ChildBlockResult {+ const { key } = debugContext;+ const cachedEntry = cache.get(key);+ const hasChildren = entry.children?.length > 0;++ // Only cache leaf blocks (no children). Container blocks are always recreated+ // to ensure their children reflect current visibility state.+ if (+ !hasChildren &&+ cachedEntry &&+ cachedEntry.ComponentClass === resolvedBlock &&+ shallowArgsEqual(cachedEntry.args, entry.args)+ ) {+ return cachedEntry.result;+ }++ // Create new curried component.+ const result = createChildBlockFn(+ { ...entry, block: resolvedBlock },+ owner,+ debugContext+ );++ // Cache leaf blocks for future reuse.+ if (!hasChildren) {+ cache.set(key, {+ ComponentClass: resolvedBlock,+ args: entry.args,+ result,+ });+ }++ return result;+}++/** Options for {@link processBlockEntries}. */+interface ProcessBlockEntriesOptions {+ /** Pre-processed block entries with visibility metadata. */+ entries: BlockEntry[];++ /** Component cache keyed by stable block keys. */+ cache: LeafCache;++ /** Application owner for service lookup. */+ owner: Owner;++ /** Current hierarchy path (e.g. "homepage-blocks/section-1"). */+ baseHierarchy: string;++ /** The outlet name, used for CSS class generation. */+ outletName: string;++ /** Arguments passed from the outlet to blocks. */+ outletArgs: Record<string, unknown>;++ /** Whether to render ghost blocks for invisible entries. */+ showGhosts: boolean;++ /** Whether debug logging is active. */+ isLoggingEnabled: boolean;++ /** Creates child block components (injected from block-outlet). */+ createChildBlockFn: CreateChildBlockFn;+}++/**+ * Processes block entries and creates renderable child components, handling+ * ghost blocks for debug mode and optional missing blocks.+ *+ * @param options - Rendering options.+ * @returns Renderable child objects with their `Component` and `containerArgs`.+ */+export function processBlockEntries({+ entries,+ cache,+ owner,+ baseHierarchy,+ outletName,+ outletArgs,+ showGhosts,+ isLoggingEnabled,+ createChildBlockFn,+}: ProcessBlockEntriesOptions): ChildBlockResult[] {+ const result: ChildBlockResult[] = [];+ const containerCounts = new Map<string, number>();++ for (const entry of entries) {+ const resolvedBlock = tryResolveBlock(entry.block);++ // Handle optional missing block (block ref ended with `?` but not registered).+ if (isOptionalMissing(resolvedBlock)) {+ const key = `optional-missing:${resolvedBlock.name}:${entry.__stableKey}`;+ const ghostData = handleOptionalMissingBlock({+ blockName: resolvedBlock.name,+ entry,+ hierarchy: baseHierarchy,+ isLoggingEnabled,+ showGhosts,+ key,+ });+ if (ghostData) {+ result.push(ghostData);+ }+ continue;+ }++ // Skip blocks that haven't resolved yet. Block factories may be resolving+ // asynchronously (e.g. lazy-loaded plugins); the component re-renders+ // automatically when the factory resolves (via TrackedMap reactivity).+ if (!resolvedBlock) {+ continue;+ }++ const blockClass = resolvedBlock;+ const blockMeta = getBlockMetadata(blockClass);+ const blockName = blockMeta?.blockName || "unknown";+ const isContainer = blockMeta?.isContainer ?? false;++ // Use the stable key assigned at registration time. This key survives shallow+ // cloning and keeps DOM identity when blocks are hidden/shown by conditions.+ const key = `${blockName}:${entry.__stableKey}`;++ // For containers, build their full path for children's hierarchy. The id is+ // included in the path for easier identification in debug tools.+ const containerPath = isContainer+ ? buildContainerPath(blockName, entry.id, baseHierarchy, containerCounts)+ : undefined;++ // For containers with children, recursively process children FIRST. This+ // creates the child components at the root level, so containers receive+ // pre-processed children via the `@children` arg instead of raw entries.+ let processedChildren: ChildBlockResult[] | undefined;+ if (isContainer && entry.children?.length) {+ processedChildren = processBlockEntries({+ entries: entry.children,+ cache, // Same root cache for all levels.+ owner,+ baseHierarchy: containerPath,+ outletName,+ outletArgs,+ showGhosts,+ isLoggingEnabled,+ createChildBlockFn,+ });+ }++ // Render visible blocks.+ if (entry.__visible) {+ result.push(+ getOrCreateLeafBlockComponent(+ cache,+ entry,+ blockClass,+ {+ displayHierarchy: baseHierarchy,+ outletName,+ containerPath,+ conditions: entry.conditions,+ outletArgs,+ key,+ processedChildren, // Pass pre-processed children for containers.+ },+ owner,+ createChildBlockFn+ )+ );+ } else if (showGhosts) {+ // Show ghost for invisible blocks in debug mode.+ const ghostData = createGhostBlock({+ blockName,+ entry,+ hierarchy: baseHierarchy,+ containerPath,+ isContainer,+ owner,+ outletArgs,+ isLoggingEnabled,+ resolveBlockFn: tryResolveBlock,+ key,+ });+ if (ghostData) {+ result.push(ghostData);+ }+ }+ }++ return result;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/error.js b/frontend/discourse/app/lib/blocks/-internals/error.tssimilarity index 65%rename from frontend/discourse/app/lib/blocks/-internals/error.jsrename to frontend/discourse/app/lib/blocks/-internals/error.tsindex 01d204aafd1..6682bbeb710 100644--- a/frontend/discourse/app/lib/blocks/-internals/error.js+++ b/frontend/discourse/app/lib/blocks/-internals/error.ts@@ -1,14 +1,12 @@-// @ts-check/*** Block error handling and entry formatting utilities.** This module provides error classes, formatting utilities for error display,* and helpers for human-readable console output during block validation.- *- * @module discourse/lib/blocks/-internals/error*/import { DEBUG } from "@glimmer/env";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";+import type { ValidationContext } from "discourse/lib/blocks/-internals/utils";/* Value Display Helpers */@@ -16,10 +14,10 @@ import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";* Formats a simple value (primitive, function, or block reference) for display.* Returns null if the value is a complex type (array/object) that needs special handling.*- * @param {*} obj - The value to format.- * @returns {string|null} String representation, or null if complex type.+ * @param obj - The value to format.+ * @returns String representation, or null if complex type.*/-function formatSimpleValue(obj) {+function formatSimpleValue(obj: unknown): string | null {if (obj === undefined) {return "undefined";}@@ -42,15 +40,15 @@ function formatSimpleValue(obj) {/*** Formats a value as a truncated string for console display.- * Returns shallow representations like "{ ... }" or "[ 3 items ]".+ * Returns shallow representations like `{ ... }` or `[ 3 items ]`.** Note: This returns STRINGS for console output. For JSON-serializable* truncation, use truncateForDisplay() instead.*- * @param {*} obj - The value to format.- * @returns {string} Truncated string representation.+ * @param obj - The value to format.+ * @returns Truncated string representation.*/-function formatTruncatedValue(obj) {+function formatTruncatedValue(obj: unknown): string {const simple = formatSimpleValue(obj);if (simple !== null) {return simple;@@ -60,7 +58,11 @@ function formatTruncatedValue(obj) {return obj.length === 0 ? "[]" : `[ ${obj.length} items ]`;}- const keys = Object.keys(obj);+ // `formatSimpleValue()` only returns `null` for a non-null, non-array+ // object (every other type is handled by it directly), so `obj` is+ // guaranteed to be an object here even though the type-checker can't see+ // through that call.+ const keys = Object.keys(obj as object);return keys.length === 0 ? "{}" : "{ ... }";}@@ -70,15 +72,17 @@ function formatTruncatedValue(obj) {* Parses a condition path string into path segments.* Handles both dot notation (`.key`) and bracket notation (`[0]`).*- * @param {string} path - The path string (e.g., "conditions.any[0][1].queryParams").- * @returns {Array<string|number>} Array of path segments.+ * @param path - The path string (e.g., "conditions.any[0][1].queryParams").+ * @returns Array of path segments.** @example+ * ```* parseConditionPath("conditions.any[0][1].type")* // Returns: ["conditions", "any", 0, 1, "type"]+ * ```*/-export function parseConditionPath(path) {- const segments = [];+export function parseConditionPath(path: string): (string | number)[] {+ const segments: (string | number)[] = [];let current = "";for (let i = 0; i < path.length; i++) {@@ -116,27 +120,31 @@ export function parseConditionPath(path) {/* Path-Aware Entry Rendering */+/**+ * Formatting options accepted by `formatEntryWithErrorPath()` and, in turn,+ * `PathHighlightRenderer`.+ */+export interface FormatEntryOptions {+ /** Prefix to skip in the path. */+ prefix?: string;+ /** Label to show before the entry. */+ label?: string;+}+/*** Renders block entries with error path highlighting.* Displays the structure with proper indentation and marks where errors occurred.*/class PathHighlightRenderer {- /** @type {Array<string|number>} */- #errorSegments;-- /** @type {string|number} */- #errorKey;-- /** @type {string|undefined} */- #label;+ #errorSegments: (string | number)[];+ #errorKey: string | number | undefined;+ #label: string | undefined;/**- * @param {string} errorPath - Path to the error (e.g., "conditions.any[0].type").- * @param {Object} [options] - Formatting options.- * @param {string} [options.prefix] - Prefix to skip in the path.- * @param {string} [options.label] - Label to show before the entry.+ * @param errorPath - Path to the error (e.g., "conditions.any[0].type").+ * @param options - Formatting options.*/- constructor(errorPath, options = {}) {+ constructor(errorPath: string, options: FormatEntryOptions = {}) {const { prefix, label } = options;const pathSegments = parseConditionPath(errorPath);@@ -149,10 +157,10 @@ class PathHighlightRenderer {/*** Renders the entry with the error path highlighted.*- * @param {Object|Array} entry - The block entry object to render.- * @returns {string} Formatted string with error location highlighted.+ * @param entry - The block entry object (or array) to render.+ * @returns Formatted string with error location highlighted.*/- render(entry) {+ render(entry: unknown): string {const rendered = this.#renderValue(entry, 0, []);return this.#label ? `${this.#label} ${rendered}` : rendered;}@@ -160,10 +168,10 @@ class PathHighlightRenderer {/*** Checks if the current path is on the error path.*- * @param {Array<string|number>} currentPath - Current path segments.- * @returns {boolean} True if on error path.+ * @param currentPath - Current path segments.+ * @returns True if on error path.*/- #isOnErrorPath(currentPath) {+ #isOnErrorPath(currentPath: (string | number)[]): boolean {return currentPath.every((seg, i) =>i >= this.#errorSegments.length || seg === this.#errorSegments[i]@@ -173,22 +181,26 @@ class PathHighlightRenderer {/*** Checks if we've passed the error location in the tree.*- * @param {Array<string|number>} currentPath - Current path segments.- * @returns {boolean} True if past error location.+ * @param currentPath - Current path segments.+ * @returns True if past error location.*/- #isPastErrorLocation(currentPath) {+ #isPastErrorLocation(currentPath: (string | number)[]): boolean {return currentPath.length > this.#errorSegments.length;}/*** Renders any value, dispatching to the appropriate handler.*- * @param {*} obj - The value to render.- * @param {number} depth - Current indentation depth.- * @param {Array<string|number>} currentPath - Path segments to current location.- * @returns {string} Rendered string.+ * @param obj - The value to render.+ * @param depth - Current indentation depth.+ * @param currentPath - Path segments to current location.+ * @returns Rendered string.*/- #renderValue(obj, depth, currentPath) {+ #renderValue(+ obj: unknown,+ depth: number,+ currentPath: (string | number)[]+ ): string {if (this.#isPastErrorLocation(currentPath)) {return formatTruncatedValue(obj);}@@ -202,18 +214,28 @@ class PathHighlightRenderer {return this.#renderArray(obj, depth, currentPath);}- return this.#renderObject(obj, depth, currentPath);+ // `formatSimpleValue()` only returns `null` for a non-null, non-array+ // object, so `obj` is guaranteed to be a plain object here.+ return this.#renderObject(+ obj as Record<string, unknown>,+ depth,+ currentPath+ );}/*** Renders an array with path highlighting.*- * @param {Array} arr - The array to render.- * @param {number} depth - Current indentation depth.- * @param {Array<string|number>} currentPath - Path segments to current location.- * @returns {string} Rendered string.+ * @param arr - The array to render.+ * @param depth - Current indentation depth.+ * @param currentPath - Path segments to current location.+ * @returns Rendered string.*/- #renderArray(arr, depth, currentPath) {+ #renderArray(+ arr: unknown[],+ depth: number,+ currentPath: (string | number)[]+ ): string {if (arr.length === 0) {return "[]";}@@ -242,11 +264,11 @@ class PathHighlightRenderer {/*** Finds which array item (if any) is on the error path.*- * @param {Array} arr - The array to search.- * @param {Array<string|number>} currentPath - Current path segments.- * @returns {number} Index of item on path, or -1 if none.+ * @param arr - The array to search.+ * @param currentPath - Current path segments.+ * @returns Index of item on path, or -1 if none.*/- #findItemOnPath(arr, currentPath) {+ #findItemOnPath(arr: unknown[], currentPath: (string | number)[]): number {for (let i = 0; i < arr.length; i++) {const itemPath = [...currentPath, i];if (this.#isOnErrorPath(itemPath)) {@@ -259,21 +281,21 @@ class PathHighlightRenderer {/*** Renders an array with a highlighted item on the error path.*- * @param {Array} arr - The array to render.- * @param {number} itemIndex - Index of the highlighted item.- * @param {number} depth - Current indentation depth.- * @param {Array<string|number>} currentPath - Current path segments.- * @param {string} indent - Current indentation string.- * @param {Array<string>} lines - Output lines array.+ * @param arr - The array to render.+ * @param itemIndex - Index of the highlighted item.+ * @param depth - Current indentation depth.+ * @param currentPath - Current path segments.+ * @param indent - Current indentation string.+ * @param lines - Output lines array.*/#renderArrayWithHighlightedItem(- arr,- itemIndex,- depth,- currentPath,- indent,- lines- ) {+ arr: unknown[],+ itemIndex: number,+ depth: number,+ currentPath: (string | number)[],+ indent: string,+ lines: string[]+ ): void {if (itemIndex > 0) {lines.push(`${indent} ...`);}@@ -295,11 +317,15 @@ class PathHighlightRenderer {/*** Renders all array items as truncated values.*- * @param {Array} arr - The array to render.- * @param {string} indent - Current indentation string.- * @param {Array<string>} lines - Output lines array.+ * @param arr - The array to render.+ * @param indent - Current indentation string.+ * @param lines - Output lines array.*/- #renderArrayAllTruncated(arr, indent, lines) {+ #renderArrayAllTruncated(+ arr: unknown[],+ indent: string,+ lines: string[]+ ): void {for (let i = 0; i < arr.length; i++) {const value = formatTruncatedValue(arr[i]);const comma = i < arr.length - 1 ? "," : "";@@ -310,10 +336,10 @@ class PathHighlightRenderer {/*** Checks if a path is the exact error location.*- * @param {Array<string|number>} path - Path to check.- * @returns {boolean} True if this is the exact error location.+ * @param path - Path to check.+ * @returns True if this is the exact error location.*/- #isExactErrorLocation(path) {+ #isExactErrorLocation(path: (string | number)[]): boolean {return (path.length === this.#errorSegments.length &&path.every((seg, j) => seg === this.#errorSegments[j])@@ -323,12 +349,16 @@ class PathHighlightRenderer {/*** Renders an object with path highlighting.*- * @param {Object} obj - The object to render.- * @param {number} depth - Current indentation depth.- * @param {Array<string|number>} currentPath - Path segments to current location.- * @returns {string} Rendered string.+ * @param obj - The object to render.+ * @param depth - Current indentation depth.+ * @param currentPath - Path segments to current location.+ * @returns Rendered string.*/- #renderObject(obj, depth, currentPath) {+ #renderObject(+ obj: Record<string, unknown>,+ depth: number,+ currentPath: (string | number)[]+ ): string {const indent = " ".repeat(depth);const keys = Object.keys(obj).filter((k) => !k.startsWith("_"));const isOnPath = this.#isOnErrorPath(currentPath);@@ -364,15 +394,23 @@ class PathHighlightRenderer {/*** Renders all keys of an object.*- * @param {Object} obj - The object being rendered.- * @param {Array<string>} keys - Keys to render.- * @param {number} depth - Current indentation depth.- * @param {Array<string|number>} currentPath - Current path segments.- * @param {boolean} isOnPath - Whether current location is on error path.- * @param {string} indent - Current indentation string.- * @param {Array<string>} lines - Output lines array.+ * @param obj - The object being rendered.+ * @param keys - Keys to render.+ * @param depth - Current indentation depth.+ * @param currentPath - Current path segments.+ * @param isOnPath - Whether current location is on error path.+ * @param indent - Current indentation string.+ * @param lines - Output lines array.*/- #renderObjectKeys(obj, keys, depth, currentPath, isOnPath, indent, lines) {+ #renderObjectKeys(+ obj: Record<string, unknown>,+ keys: string[],+ depth: number,+ currentPath: (string | number)[],+ isOnPath: boolean,+ indent: string,+ lines: string[]+ ): void {for (const key of keys) {const keyPath = [...currentPath, key];const isKeyOnPath = this.#isOnErrorPath(keyPath);@@ -394,13 +432,19 @@ class PathHighlightRenderer {/*** Appends a key-value line to the output, handling multiline values.*- * @param {string} key - The object key.- * @param {string} value - The rendered value.- * @param {string} errorMarker - Error marker string (or empty).- * @param {string} indent - Current indentation string.- * @param {Array<string>} lines - Output lines array.+ * @param key - The object key.+ * @param value - The rendered value.+ * @param errorMarker - Error marker string (or empty).+ * @param indent - Current indentation string.+ * @param lines - Output lines array.*/- #appendKeyValueLine(key, value, errorMarker, indent, lines) {+ #appendKeyValueLine(+ key: string,+ value: string,+ errorMarker: string,+ indent: string,+ lines: string[]+ ): void {if (value.includes("\n")) {const [firstLine, ...restLines] = value.split("\n");lines.push(`${indent} ${key}: ${firstLine}${errorMarker}`);@@ -413,11 +457,15 @@ class PathHighlightRenderer {/*** Renders a synthetic entry for missing keys on the error path.*- * @param {Array<string|number>} currentPath - Current path segments.- * @param {string} indent - Current indentation string.- * @param {Array<string>} lines - Output lines array.+ * @param currentPath - Current path segments.+ * @param indent - Current indentation string.+ * @param lines - Output lines array.*/- #renderSyntheticEntry(currentPath, indent, lines) {+ #renderSyntheticEntry(+ currentPath: (string | number)[],+ indent: string,+ lines: string[]+ ): void {const remainingPath = this.#errorSegments.slice(currentPath.length);const nextSegment = remainingPath[0];const isAtFinalKey = remainingPath.length === 1;@@ -439,13 +487,13 @@ class PathHighlightRenderer {/*** Renders the remaining path segments for a missing key.*- * @param {Array<string|number>} segments - Remaining path segments.- * @param {number} depth - Current indentation depth.- * @returns {Array<string>} Array of formatted lines.+ * @param segments - Remaining path segments.+ * @param depth - Current indentation depth.+ * @returns Array of formatted lines.*/- #renderMissingPath(segments, depth) {+ #renderMissingPath(segments: (string | number)[], depth: number): string[] {const indent = " ".repeat(depth);- const lines = [];+ const lines: string[] = [];if (segments.length === 0) {return lines;@@ -470,14 +518,16 @@ class PathHighlightRenderer {* Shows the structure with proper indentation and adds a comment marker* to indicate where the error occurred.*- * @param {Object|Array} entry - The block entry object to render.- * @param {string} errorPath - The path to the error (e.g., "conditions.any[0][0].queryParams").- * @param {Object} [options] - Formatting options.- * @param {string} [options.prefix] - Optional prefix to skip in the path (e.g., "conditions").- * @param {string} [options.label] - Label to show before the entry (e.g., "conditions:").- * @returns {string} Formatted string with the error location highlighted.+ * @param entry - The block entry object (or array) to render.+ * @param errorPath - The path to the error (e.g., "conditions.any[0][0].queryParams").+ * @param options - Formatting options.+ * @returns Formatted string with the error location highlighted.*/-export function formatEntryWithErrorPath(entry, errorPath, options = {}) {+export function formatEntryWithErrorPath(+ entry: unknown,+ errorPath: string,+ options: FormatEntryOptions = {}+): string {return new PathHighlightRenderer(errorPath, options).render(entry);}@@ -490,24 +540,24 @@ export function formatEntryWithErrorPath(entry, errorPath, options = {}) {** Handles special cases like block classes, children arrays, and circular references.*- * @param {*} obj - The object to truncate.- * @param {number} [maxDepth=2] - Maximum nesting depth before truncating.- * @param {number} [maxKeys=5] - Maximum number of keys to show per object.- * @param {WeakSet} [_seen=null] - Internal parameter for tracking circular references.- * @returns {*} Truncated representation of the object.+ * @param obj - The object to truncate.+ * @param maxDepth - Maximum nesting depth before truncating.+ * @param maxKeys - Maximum number of keys to show per object.+ * @param _seen - Internal parameter for tracking circular references.+ * @returns Truncated representation of the object.*/export function truncateForDisplay(- obj,+ obj: unknown,maxDepth = 2,maxKeys = 5,- _seen = null-) {+ _seen: WeakSet<object> | null = null+): unknown {if (obj === null || typeof obj !== "object") {return obj;}// Initialize seen set on first call to track circular references- const seen = _seen ?? new WeakSet();+ const seen = _seen ?? new WeakSet<object>();// Handle circular referencesif (seen.has(obj)) {@@ -520,30 +570,42 @@ export function truncateForDisplay(}if (Array.isArray(obj)) {- if (obj.length > maxKeys) {+ // `Array.isArray()` narrows to the (necessarily untyped) built-in `any[]`;+ // re-declare it as `unknown[]` so nothing downstream carries an `any`.+ const arr = obj as unknown[];+ if (arr.length > maxKeys) {return [- ...obj+ ...arr.slice(0, maxKeys).map((v) => truncateForDisplay(v, maxDepth - 1, maxKeys, seen)),"...",];}- return obj.map((v) => truncateForDisplay(v, maxDepth - 1, maxKeys, seen));+ return arr.map((v) => truncateForDisplay(v, maxDepth - 1, maxKeys, seen));}- // Filter out private keys (starting with _)- const keys = Object.keys(obj).filter((k) => !k.startsWith("_"));- const result = {};+ // Filter out private keys (starting with _). `obj` is a non-null,+ // non-array object at this point, so it's safe to treat as a record.+ const record = obj as Record<string, unknown>;+ const keys = Object.keys(record).filter((k) => !k.startsWith("_"));+ const result: Record<string, unknown> = {};const displayKeys = keys.slice(0, maxKeys);for (const key of displayKeys) {// Handle special keys that don't serialize well or are verboseif (key === "block") {- result[key] = `<${getBlockMetadata(obj[key])?.blockName || "Component"}>`;+ result[key] =+ `<${getBlockMetadata(record[key] as object)?.blockName || "Component"}>`;} else if (key === "children") {- result[key] = `[${obj[key]?.length || 0} children]`;+ const children = record[key] as unknown[] | undefined;+ result[key] = `[${children?.length || 0} children]`;} else {- result[key] = truncateForDisplay(obj[key], maxDepth - 1, maxKeys, seen);+ result[key] = truncateForDisplay(+ record[key],+ maxDepth - 1,+ maxKeys,+ seen+ );}}@@ -556,6 +618,18 @@ export function truncateForDisplay(/* Error Handling */+/**+ * The V8-specific `Error.captureStackTrace` static, absent from the standard+ * `ErrorConstructor` type declarations. A no-op in non-V8 environments.+ */+interface V8ErrorConstructor {+ captureStackTrace?: (+ targetObject: object,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ constructorOpt?: (...args: any[]) => void+ ) => void;+}+/*** Captures the current call site as an Error object, excluding internal frames.* Call this at the entry point (e.g., renderBlocks) to capture where@@ -565,19 +639,21 @@ export function truncateForDisplay(* and everything above it from the stack trace. This means the stack will* point directly to the user's code, not to internal block system functions.*- * @param {Function} callerFn - The function to exclude from the stack trace.+ * @param callerFn - The function to exclude from the stack trace.* Pass the function that calls `captureCallSite` (e.g., `_renderBlocks`).- * @returns {Error} An Error object with stack trace starting from callerFn's caller.+ * @returns An Error object with stack trace starting from callerFn's caller.*/-export function captureCallSite(callerFn) {+export function captureCallSite(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ callerFn: (...args: any[]) => void+): Error {const error = new Error();// V8-specific: exclude callerFn and everything above from the stack trace.// In non-V8 browsers, this is a no-op and the full stack is preserved.- // @ts-ignore - V8-specific API- if (Error.captureStackTrace) {- // @ts-ignore - V8-specific API- Error.captureStackTrace(error, callerFn);+ const v8Error: ErrorConstructor & V8ErrorConstructor = Error;+ if (v8Error.captureStackTrace) {+ v8Error.captureStackTrace(error, callerFn);}return error;@@ -587,20 +663,25 @@ export function captureCallSite(callerFn) {* Builds a tree-style breadcrumb showing the path from root to error.* Uses Unicode box-drawing characters for visual hierarchy.*- * @param {Array|Object} rootLayout - The root layout (usually an array of block entries).- * @param {string} errorPath - The path to the error (e.g., "[4].children[2].args.nme").- * @returns {string} Tree-style breadcrumb string.+ * @param rootLayout - The root layout (an array of block entries).+ * @param errorPath - The path to the error (e.g., "[4].children[2].args.nme").+ * @returns Tree-style breadcrumb string.** @example+ * ```* // Returns:* // └─ [4] BlockGroup (name: "callouts")* // └─ [2] ChildBlockName* // └─ args.nme ← error here+ * ```*/-function buildBreadcrumb(rootLayout, errorPath) {+function buildBreadcrumb(+ rootLayout: Array<Record<string, unknown>>,+ errorPath: string+): string {const segments = parseConditionPath(errorPath);- const lines = [];- let current = rootLayout;+ const lines: string[] = [];+ let current: unknown = rootLayout;let indent = "";for (let i = 0; i < segments.length; i++) {@@ -608,11 +689,14 @@ function buildBreadcrumb(rootLayout, errorPath) {if (typeof seg === "number" && Array.isArray(current)) {// Array index - show block info- const block = current[seg];+ const block = current[seg] as Record<string, unknown> | undefined;const blockClass = block?.block;const blockName =- getBlockMetadata(blockClass)?.blockName || blockClass?.name || "Block";- const nameArg = block?.args?.name ? ` (name: "${block.args.name}")` : "";+ getBlockMetadata(blockClass as object)?.blockName ||+ (blockClass as { name?: string } | undefined)?.name ||+ "Block";+ const args = block?.args as Record<string, unknown> | undefined;+ const nameArg = args?.name ? ` (name: "${args.name}")` : "";lines.push(`${indent}└─ [${seg}] ${blockName}${nameArg}`);current = block;indent += " ";@@ -624,7 +708,7 @@ function buildBreadcrumb(rootLayout, errorPath) {// Object key - check if this is a terminal segment or intermediateconst isLastSegment = i === segments.length - 1;const nextSeg = segments[i + 1];- const value = current[seg];+ const value = (current as Record<string, unknown>)[seg];if (seg === "children" && typeof nextSeg === "number") {// "children" followed by index - continue traversal@@ -652,10 +736,12 @@ function buildBreadcrumb(rootLayout, errorPath) {* When an `errorPath` is provided, uses the path-aware formatter to show* the error location within the entry with a comment marker.*- * @param {Object} context - The error context.- * @returns {string} Formatted context string, or empty string if no context.+ * @param context - The error context (see `ValidationContext`).+ * @returns Formatted context string, or empty string if no context.*/-function formatErrorContext(context) {+function formatErrorContext(+ context: Partial<ValidationContext> | null+): string {if (!context) {return "";}@@ -750,6 +836,19 @@ function formatErrorContext(context) {return parts.length > 0 ? `\n\n${parts.join("\n")}` : "";}+/**+ * Options accepted by `BlockError`'s constructor.+ */+export interface BlockErrorOptions {+ /** The underlying cause of this error, chained via the standard ES2022 `cause` option. */+ cause?: Error;+ /**+ * Path to the error within the layout (e.g., "[0].conditions.any[0].type"+ * or "[0].args.showIcon").+ */+ path?: string;+}+/*** Error thrown when block validation fails.* Used by block entry and condition validation to report@@ -760,21 +859,15 @@ function formatErrorContext(context) {* `callSiteError` directly (mutating its message and name) rather than* passing it as `cause`. This preserves the original stack trace pointing* to where `renderBlocks()` was called.- *- * @class BlockError- * @extends Error*/export class BlockError extends Error {+ path?: string;+/**- * Creates a new BlockError.- *- * @param {string} message - The error message.- * @param {Object} [options] - Error options.- * @param {Error} [options.cause] - The underlying cause of this error.- * @param {string} [options.path] - Path to the error within the layout- * (e.g., "[0].conditions.any[0].type" or "[0].args.showIcon").+ * @param message - The error message.+ * @param options - Error options.*/- constructor(message, options) {+ constructor(message: string, options?: BlockErrorOptions) {super(message, options);this.name = "BlockError";this.path = options?.path;@@ -792,20 +885,15 @@ export class BlockError extends Error {* `renderBlocks()` was called, which is more useful than pointing to this* function. Source maps are applied automatically by the browser.*- * @param {string} message - The error message.- * @param {Object} [context] - Optional error context for better error messages.- * @param {string} [context.outletName] - The outlet name where the block is registered.- * @param {string} [context.blockName] - The name of the block being validated.- * @param {string} [context.path] - Path within the layout to the error (e.g., "[2].conditions.params.categoryId").- * Used by validation code to indicate where errors occurred. Combined with `errorPath` for display.- * @param {Object} [context.entry] - The block entry being validated.- * @param {Object} [context.conditions] - The conditions being validated.- * @param {string} [context.errorPath] - Full path to the error for display (e.g., "[2].conditions.params.categoryId").- * @param {Array<Object>} [context.rootLayout] - The root outlet layout for tree display in errors.- * @param {Error | null} [context.callSiteError] - Error object capturing where renderBlocks() was called.- * @throws {BlockError} Always throws.+ * @param message - The error message.+ * @param context - Optional error context for better error messages (see+ * `ValidationContext`).+ * @throws Always throws a `BlockError`.*/-export function raiseBlockError(message, context = null) {+export function raiseBlockError(+ message: string,+ context: Partial<ValidationContext> | null = null+): never {// Warn in DEBUG mode when entry-related errors are missing rootLayout// This helps catch future validation code that forgets to pass rootLayoutif (DEBUG) {@@ -826,7 +914,7 @@ export function raiseBlockError(message, context = null) {const contextInfo = formatErrorContext(context);const fullMessage = `[Blocks] ${message}${contextInfo}`;- let error;+ let error: Error & { path?: string };// If we have a call site error, reuse it with updated message.// This preserves the stack trace pointing to where renderBlocks() was called,@@ -835,7 +923,6 @@ export function raiseBlockError(message, context = null) {error = context.callSiteError;error.name = "BlockError";error.message = fullMessage;- // @ts-ignore - Adding path property to Error for BlockError compatibilityerror.path = context.path;} else {error = new BlockError(fullMessage, { path: context?.path });diff --git a/frontend/discourse/app/lib/blocks/-internals/glimmer-manager.d.ts b/frontend/discourse/app/lib/blocks/-internals/glimmer-manager.d.tsnew file mode 100644index 00000000000..0ed996ce7ba--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/glimmer-manager.d.ts@@ -0,0 +1,13 @@+// Ambient shim for `@glimmer/manager`. The package ships its own types, but it+// is a transitive dependency with no resolvable entry point from the app, so+// `ember-tsc` cannot find the module (TS2307). Declare the two internal-manager+// helpers the block decorator relies on, typed just precisely enough to wrap the+// returned manager in a Proxy — the manager object itself is opaque here.+declare module "@glimmer/manager" {+ export function getInternalComponentManager(definition: object): object;++ export function setInternalComponentManager<T extends object>(+ manager: object,+ obj: T+ ): T;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.js b/frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.tssimilarity index 56%rename from frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.jsrename to frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.tsindex 07168ac6be3..1eeb39f51f4 100644--- a/frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.js+++ b/frontend/discourse/app/lib/blocks/-internals/matching/condition-evaluator.ts@@ -1,26 +1,38 @@-// @ts-check+import type { BlockCondition } from "discourse/blocks/conditions";import {DEBUG_CALLBACK,+ type DebugCallback,debugHooks,+ type DebugLoggerInterface,} from "discourse/lib/blocks/-internals/debug-hooks";+/**+ * Evaluation context passed through `evaluateConditions()` and its+ * combinator helpers.+ */+export interface ConditionEvaluationContext {+ /** Enable debug logging for this evaluation. */+ debug?: boolean;+ /** Internal: nesting depth for logging. */+ _depth?: number;+ /** Outlet arguments passed to conditions. */+ outletArgs?: Record<string, unknown>;+}+/*** Evaluates condition specs at render time.* Recursively evaluates nested conditions with AND/OR/NOT logic.*- * @param {Object|Array<Object>} conditionSpec - Condition spec(s) to evaluate.- * @param {Map<string, import("discourse/blocks/conditions").BlockCondition>} conditionTypes - Map of registered condition types.- * @param {Object} [context] - Evaluation context.- * @param {boolean} [context.debug] - Enable debug logging for this evaluation.- * @param {number} [context._depth] - Internal: nesting depth for logging.- * @param {Object} [context.outletArgs] - Outlet arguments passed to conditions.- * @returns {boolean} True if conditions pass, false otherwise.+ * @param conditionSpec - Condition spec(s) to evaluate.+ * @param conditionTypes - Map of registered condition types.+ * @param context - Evaluation context.+ * @returns True if conditions pass, false otherwise.*/export function evaluateConditions(- conditionSpec,- conditionTypes,- context = {}-) {+ conditionSpec: unknown,+ conditionTypes: Map<string, BlockCondition>,+ context: ConditionEvaluationContext = {}+): boolean {const isLoggingEnabled = context.debug ?? false;const depth = context._depth ?? 0;@@ -55,9 +67,9 @@ export function evaluateConditions(}// OR combinator (at least one must pass)- if (conditionSpec.any !== undefined) {+ if ((conditionSpec as { any?: unknown[] }).any !== undefined) {return evaluateOrCombinator(- conditionSpec,+ conditionSpec as { any: unknown[] },conditionTypes,context,isLoggingEnabled,@@ -68,9 +80,9 @@ export function evaluateConditions(}// NOT combinator (must fail)- if (conditionSpec.not !== undefined) {+ if ((conditionSpec as { not?: unknown }).not !== undefined) {return evaluateNotCombinator(- conditionSpec,+ conditionSpec as { not: unknown },conditionTypes,context,isLoggingEnabled,@@ -82,7 +94,7 @@ export function evaluateConditions(// Single condition with typereturn evaluateSingleCondition(- conditionSpec,+ conditionSpec as { type?: string } & Record<string, unknown>,conditionTypes,context,isLoggingEnabled,@@ -96,24 +108,24 @@ export function evaluateConditions(/*** Evaluates an array of conditions with AND logic (all must pass).*- * @param {Array<Object>} conditionSpec - Array of condition specs.- * @param {Map} conditionTypes - Map of registered condition types.- * @param {Object} context - Evaluation context.- * @param {boolean} isLoggingEnabled - Whether debug logging is enabled.- * @param {number} depth - Current nesting depth.- * @param {Function|null} conditionLog - Callback for logging conditions.- * @param {Function|null} combinatorLog - Callback for logging combinator results.- * @returns {boolean} True if all conditions pass.+ * @param conditionSpec - Array of condition specs.+ * @param conditionTypes - Map of registered condition types.+ * @param context - Evaluation context.+ * @param isLoggingEnabled - Whether debug logging is enabled.+ * @param depth - Current nesting depth.+ * @param conditionLog - Callback for logging conditions.+ * @param combinatorLog - Callback for logging combinator results.+ * @returns True if all conditions pass.*/function evaluateAndCombinator(- conditionSpec,- conditionTypes,- context,- isLoggingEnabled,- depth,- conditionLog,- combinatorLog-) {+ conditionSpec: unknown[],+ conditionTypes: Map<string, BlockCondition>,+ context: ConditionEvaluationContext,+ isLoggingEnabled: boolean,+ depth: number,+ conditionLog: DebugCallback | null | undefined,+ combinatorLog: DebugCallback | null | undefined+): boolean {// Empty array is vacuous truth - no conditions to failif (conditionSpec.length === 0) {return true;@@ -152,24 +164,24 @@ function evaluateAndCombinator(/*** Evaluates an OR combinator (at least one must pass).*- * @param {Object} conditionSpec - Condition spec containing "any" array.- * @param {Map} conditionTypes - Map of registered condition types.- * @param {Object} context - Evaluation context.- * @param {boolean} isLoggingEnabled - Whether debug logging is enabled.- * @param {number} depth - Current nesting depth.- * @param {Function|null} conditionLog - Callback for logging conditions.- * @param {Function|null} combinatorLog - Callback for logging combinator results.- * @returns {boolean} True if at least one condition passes.+ * @param conditionSpec - Condition spec containing "any" array.+ * @param conditionTypes - Map of registered condition types.+ * @param context - Evaluation context.+ * @param isLoggingEnabled - Whether debug logging is enabled.+ * @param depth - Current nesting depth.+ * @param conditionLog - Callback for logging conditions.+ * @param combinatorLog - Callback for logging combinator results.+ * @returns True if at least one condition passes.*/function evaluateOrCombinator(- conditionSpec,- conditionTypes,- context,- isLoggingEnabled,- depth,- conditionLog,- combinatorLog-) {+ conditionSpec: { any: unknown[] },+ conditionTypes: Map<string, BlockCondition>,+ context: ConditionEvaluationContext,+ isLoggingEnabled: boolean,+ depth: number,+ conditionLog: DebugCallback | null | undefined,+ combinatorLog: DebugCallback | null | undefined+): boolean {// Empty OR array means no conditions can passif (conditionSpec.any.length === 0) {return false;@@ -208,24 +220,24 @@ function evaluateOrCombinator(/*** Evaluates a NOT combinator (inner condition must fail).*- * @param {Object} conditionSpec - Condition spec containing "not" condition.- * @param {Map} conditionTypes - Map of registered condition types.- * @param {Object} context - Evaluation context.- * @param {boolean} isLoggingEnabled - Whether debug logging is enabled.- * @param {number} depth - Current nesting depth.- * @param {Function|null} conditionLog - Callback for logging conditions.- * @param {Function|null} combinatorLog - Callback for logging combinator results.- * @returns {boolean} True if inner condition fails.+ * @param conditionSpec - Condition spec containing "not" condition.+ * @param conditionTypes - Map of registered condition types.+ * @param context - Evaluation context.+ * @param isLoggingEnabled - Whether debug logging is enabled.+ * @param depth - Current nesting depth.+ * @param conditionLog - Callback for logging conditions.+ * @param combinatorLog - Callback for logging combinator results.+ * @returns True if inner condition fails.*/function evaluateNotCombinator(- conditionSpec,- conditionTypes,- context,- isLoggingEnabled,- depth,- conditionLog,- combinatorLog-) {+ conditionSpec: { not: unknown },+ conditionTypes: Map<string, BlockCondition>,+ context: ConditionEvaluationContext,+ isLoggingEnabled: boolean,+ depth: number,+ conditionLog: DebugCallback | null | undefined,+ combinatorLog: DebugCallback | null | undefined+): boolean {// Log combinator BEFORE children (result=null as placeholder)conditionLog?.({type: "NOT",@@ -250,28 +262,28 @@ function evaluateNotCombinator(/*** Evaluates a single condition with a type property.*- * @param {Object} conditionSpec - Single condition spec with type.- * @param {Map} conditionTypes - Map of registered condition types.- * @param {Object} context - Evaluation context.- * @param {boolean} isLoggingEnabled - Whether debug logging is enabled.- * @param {number} depth - Current nesting depth.- * @param {Function|null} conditionLog - Callback for logging conditions.- * @param {Function|null} conditionResultLog - Callback for logging condition results.- * @param {Object|null} logger - Logger interface for conditions.- * @returns {boolean} True if condition passes.+ * @param conditionSpec - Single condition spec with type.+ * @param conditionTypes - Map of registered condition types.+ * @param context - Evaluation context.+ * @param isLoggingEnabled - Whether debug logging is enabled.+ * @param depth - Current nesting depth.+ * @param conditionLog - Callback for logging conditions.+ * @param conditionResultLog - Callback for logging condition results.+ * @param logger - Logger interface for conditions.+ * @returns True if condition passes.*/function evaluateSingleCondition(- conditionSpec,- conditionTypes,- context,- isLoggingEnabled,- depth,- conditionLog,- conditionResultLog,- logger-) {+ conditionSpec: { type?: string } & Record<string, unknown>,+ conditionTypes: Map<string, BlockCondition>,+ context: ConditionEvaluationContext,+ isLoggingEnabled: boolean,+ depth: number,+ conditionLog: DebugCallback | null | undefined,+ conditionResultLog: DebugCallback | null | undefined,+ logger: DebugLoggerInterface | null+): boolean {const { type, ...args } = conditionSpec;- const conditionInstance = conditionTypes.get(type);+ const conditionInstance = conditionTypes.get(type as string);if (!conditionInstance) {conditionLog?.({diff --git a/frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.js b/frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.tssimilarity index 82%rename from frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.jsrename to frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.tsindex 2ff6b26ca72..b94d76222f5 100644--- a/frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.js+++ b/frontend/discourse/app/lib/blocks/-internals/matching/outlet-matcher.ts@@ -1,10 +1,27 @@-// @ts-checkimport { DEBUG } from "@glimmer/env";import picomatch from "picomatch";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import { getAllOutlets } from "discourse/lib/blocks/-internals/registry/outlet";import { isValidGlobPattern } from "discourse/lib/glob-utils";+/**+ * The result of `detectPatternConflicts()`.+ */+export type PatternConflictResult =+ | { conflict: false }+ | {+ conflict: true;+ details: { outlet: string; allowed: string; denied: string };+ };++/**+ * The result of `isBlockPermittedInOutlet()`.+ */+export interface OutletPermissionResult {+ permitted: boolean;+ reason?: string;+}+/*** Checks if a pattern targets a namespaced outlet.*@@ -13,16 +30,13 @@ import { isValidGlobPattern } from "discourse/lib/glob-utils";* These patterns bypass known-outlet validation since they reference outlets* that may not be in the core `BLOCK_OUTLETS` registry.*- * @param {string} pattern - The pattern to check.- * @returns {boolean} True if the pattern contains a namespace separator.- ** @example* isNamespacedPattern("my-plugin:dashboard"); // true* isNamespacedPattern("my-theme:hero-section"); // true* isNamespacedPattern("sidebar-blocks"); // false* isNamespacedPattern("sidebar-*"); // false*/-export function isNamespacedPattern(pattern) {+export function isNamespacedPattern(pattern: string): boolean {return pattern.includes(":");}@@ -37,32 +51,42 @@ export function isNamespacedPattern(pattern) {* - `{a,b}` matches any of the comma-separated patterns* - `!(pattern)` negative match (matches anything except pattern)*- * @param {string} outlet - The outlet name to test.- * @param {string} pattern - The glob pattern to match against.- * @returns {boolean} True if the outlet matches the pattern.+ * @param outlet - The outlet name to test.+ * @param pattern - The glob pattern to match against.+ * @returns True if the outlet matches the pattern.** @example+ * ```* // Exact match* matchOutletPattern("sidebar-blocks", "sidebar-blocks"); // true+ * ```** @example+ * ```* // Wildcard matching* matchOutletPattern("sidebar-left", "sidebar-*"); // true* matchOutletPattern("sidebar-left-top", "sidebar-*"); // true+ * ```** @example+ * ```* // Brace expansion* matchOutletPattern("sidebar-blocks", "{sidebar,footer}-*"); // true+ * ```** @example+ * ```* // Character class* matchOutletPattern("modal-1", "modal-[0-9]"); // true+ * ```** @example+ * ```* // Negation* matchOutletPattern("sidebar-blocks", "!(*-debug)"); // true+ * ```*/-export function matchOutletPattern(outlet, pattern) {+export function matchOutletPattern(outlet: string, pattern: string): boolean {// Use dot: true to match dots in outlet names (e.g., namespaced outlets)const isMatch = picomatch(pattern, { dot: true });return isMatch(outlet);@@ -77,15 +101,19 @@ export function matchOutletPattern(outlet, pattern) {* 2. Each pattern in the array is a string* 3. Each pattern can be compiled by picomatch*- * @param {*} patterns - The patterns to validate.- * @param {string} blockName - Block name for error messages.- * @param {string} propertyName - Property name ("allowedOutlets" or "deniedOutlets").+ * @param patterns - The patterns to validate.+ * @param blockName - Block name for error messages.+ * @param propertyName - Property name ("allowedOutlets" or "deniedOutlets").** @example* validateOutletPatterns(["sidebar-*", "homepage-blocks"], "my-block", "allowedOutlets");* validateOutletPatterns(null, "my-block", "allowedOutlets"); // null means no restrictions*/-export function validateOutletPatterns(patterns, blockName, propertyName) {+export function validateOutletPatterns(+ patterns: unknown,+ blockName: string,+ propertyName: string+): void {// null/undefined means "no restrictions" - this is validif (patterns == null) {return;@@ -133,22 +161,28 @@ export function validateOutletPatterns(patterns, blockName, propertyName) {* in patterns with concrete characters. This catches conflicts for outlets* that don't exist yet (e.g., plugin-defined outlets).*- * @param {string[]|null} allowedPatterns - Patterns for allowed outlets.- * @param {string[]|null} deniedPatterns - Patterns for denied outlets.- * @returns {{ conflict: boolean, details?: { outlet: string, allowed: string, denied: string } }}- * Returns conflict: true with details if a conflict is detected.+ * @param allowedPatterns - Patterns for allowed outlets.+ * @param deniedPatterns - Patterns for denied outlets.+ * @returns Conflict: true with details if a conflict is detected.** @example+ * ```* // No conflict* detectPatternConflicts(["sidebar-*"], ["homepage-*"]);* // { conflict: false }+ * ```** @example+ * ```* // Conflict detected* detectPatternConflicts(["*-blocks"], ["sidebar-*"]);* // { conflict: true, details: { outlet: "sidebar-blocks", allowed: "*-blocks", denied: "sidebar-*" } }+ * ```*/-export function detectPatternConflicts(allowedPatterns, deniedPatterns) {+export function detectPatternConflicts(+ allowedPatterns: string[] | null | undefined,+ deniedPatterns: string[] | null | undefined+): PatternConflictResult {// Early exit: No conflict possible if either list is empty/nullif (!allowedPatterns?.length || !deniedPatterns?.length) {return { conflict: false };@@ -175,7 +209,7 @@ export function detectPatternConflicts(allowedPatterns, deniedPatterns) {// Strategy 2: Generate synthetic test strings from patterns// This catches conflicts for outlets that don't exist yet (e.g., plugin outlets).// We derive test strings by replacing glob wildcards with concrete characters.- const testStrings = new Set();+ const testStrings = new Set<string>();[...allowedPatterns, ...deniedPatterns].forEach((pattern) => {// Replace all glob special chars with 'x' to get a literal string// e.g., "sidebar-*" -> "sidebar-x"@@ -219,41 +253,48 @@ export function detectPatternConflicts(allowedPatterns, deniedPatterns) {* Denial takes precedence over allowance. An empty `allowedOutlets` array means* "no outlets allowed" (strict whitelist).*- * @param {string} outlet - The outlet name to check.- * @param {string[]|null} allowedPatterns - Patterns for allowed outlets.- * @param {string[]|null} deniedPatterns - Patterns for denied outlets.- * @returns {{ permitted: boolean, reason?: string }}- * Returns permitted: true if allowed, or permitted: false with a reason if denied.+ * @param outlet - The outlet name to check.+ * @param allowedPatterns - Patterns for allowed outlets.+ * @param deniedPatterns - Patterns for denied outlets.+ * @returns Permitted: true if allowed, or permitted: false with a reason if denied.** @example+ * ```* // No restrictions* isBlockPermittedInOutlet("sidebar-blocks", null, null);* // { permitted: true }+ * ```** @example+ * ```* // Allowed by pattern* isBlockPermittedInOutlet("sidebar-blocks", ["sidebar-*"], null);* // { permitted: true }+ * ```** @example+ * ```* // Denied by pattern* isBlockPermittedInOutlet("sidebar-blocks", null, ["sidebar-*"]);* // { permitted: false, reason: 'outlet "sidebar-blocks" matches deniedOutlets pattern "sidebar-*"' }+ * ```** @example+ * ```* // Not in allowed list* isBlockPermittedInOutlet("homepage-blocks", ["sidebar-*"], null);* // { permitted: false, reason: 'outlet "homepage-blocks" does not match any allowedOutlets pattern' }+ * ```*/export function isBlockPermittedInOutlet(- outlet,- allowedPatterns,- deniedPatterns-) {+ outlet: string,+ allowedPatterns: string[] | null | undefined,+ deniedPatterns: string[] | null | undefined+): OutletPermissionResult {// Check denied list first (explicit deny always wins)// This ensures that even if a pattern appears in both lists (shouldn't happen// due to conflict detection), denial takes precedence for safety.- if (deniedPatterns?.length > 0) {+ if (deniedPatterns && deniedPatterns.length > 0) {const deniedMatch = deniedPatterns.find((p) =>matchOutletPattern(outlet, p));@@ -301,16 +342,20 @@ export function isBlockPermittedInOutlet(* Warnings are only printed in development builds (when DEBUG is true).* This prevents noise in production.*- * @param {string[]|null} patterns - The patterns to check.- * @param {string} blockName - Block name for warning messages.- * @param {string} propertyName - Property name ("allowedOutlets" or "deniedOutlets").+ * @param patterns - The patterns to check.+ * @param blockName - Block name for warning messages.+ * @param propertyName - Property name ("allowedOutlets" or "deniedOutlets").** @example* // Warns about typo* warnUnknownOutletPatterns(["sidbar-*"], "my-block", "allowedOutlets");* // Console: [Blocks] Block "my-block": allowedOutlets pattern "sidbar-*" does not match any known outlet...*/-export function warnUnknownOutletPatterns(patterns, blockName, propertyName) {+export function warnUnknownOutletPatterns(+ patterns: string[] | null | undefined,+ blockName: string,+ propertyName: string+): void {if (!patterns?.length) {return;}diff --git a/frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.js b/frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.tssimilarity index 71%rename from frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.jsrename to frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.tsindex 2bf25ffdae7..11f149dc145 100644--- a/frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.js+++ b/frontend/discourse/app/lib/blocks/-internals/matching/page-definitions.ts@@ -1,4 +1,3 @@-// @ts-checkimport { findClosestMatch } from "discourse/lib/string-similarity";/**@@ -6,26 +5,72 @@ import { findClosestMatch } from "discourse/lib/string-similarity";** This is a pure data structure that defines the available page types* and their parameters. The evaluation logic is in route.js.- *- * @typedef {Object} ParamDefinition- * @property {"string"|"number"} type - The expected type of the parameter.- * @property {string} description - A description of the parameter.- *- * @typedef {Object} PageDefinition- * @property {string} description - A description of the page type.- * @property {Object<string, ParamDefinition>} params - The parameters for this page type.*/+/**+ * Definition of a single parameter accepted by a page type.+ */+export interface ParamDefinition {+ /** The expected type of the parameter. */+ type: "string" | "number";+ /** A description of the parameter. */+ description: string;+}++/**+ * Definition of a page type: its description and the parameters it exposes.+ */+export interface PageDefinition {+ /** A description of the page type. */+ description: string;+ /** The parameters for this page type. */+ params: Record<string, ParamDefinition>;+}++/**+ * The router service shape used by `getPageContext()`/`getCurrentPageType()`+ * to read the current route. Callers pass Ember's injected `router` service,+ * which is untyped at the call sites today.+ */+export interface PageContextRouter {+ currentRouteName?: string | null;+ currentRoute?: { params?: Record<string, unknown> } | null;+}++/**+ * The discovery service shape used by `getPageContext()`/`getCurrentPageType()`+ * to read the current discovery route state. Callers pass Discourse's injected+ * `discovery` service, which is untyped at the call sites today.+ */+export interface PageContextDiscovery {+ category?: {+ id?: number;+ slug?: string;+ parent_category_id?: number;+ } | null;+ tag?: { name?: string } | null;+ custom?: boolean;+ onDiscoveryRoute?: boolean;+}++/**+ * Injected services needed to extract page context.+ */+export interface PageContextServices {+ /** The Ember router service. */+ router: PageContextRouter;+ /** The Discourse discovery service. */+ discovery: PageContextDiscovery;+}+/*** Definitions for all supported page types.** Each page type has:* - `description`: A human-readable description of what pages this matches.* - `params`: An object mapping parameter names to their definitions.- *- * @type {Object<string, PageDefinition>}*/-export const PAGE_DEFINITIONS = {+export const PAGE_DEFINITIONS: Record<string, PageDefinition> = {/*** Category listing pages (/c/slug, /c/parent/child).* Matches when discovery.category is set.@@ -166,28 +211,28 @@ export const PAGE_DEFINITIONS = {/*** Array of all valid page type names.- *- * @type {string[]}*/-export const VALID_PAGE_TYPES = Object.keys(PAGE_DEFINITIONS);+export const VALID_PAGE_TYPES: string[] = Object.keys(PAGE_DEFINITIONS);/*** Checks if a page type is valid.*- * @param {string} pageType - The page type to check.- * @returns {boolean} True if the page type is valid.+ * @param pageType - The page type to check.+ * @returns True if the page type is valid.*/-export function isValidPageType(pageType) {+export function isValidPageType(pageType: string): boolean {return pageType in PAGE_DEFINITIONS;}/*** Gets the parameter definitions for a page type.*- * @param {string} pageType - The page type.- * @returns {Object<string, ParamDefinition>|null} The parameter definitions, or null if invalid.+ * @param pageType - The page type.+ * @returns The parameter definitions, or null if invalid.*/-export function getParamsForPageType(pageType) {+export function getParamsForPageType(+ pageType: string+): Record<string, ParamDefinition> | null {const definition = PAGE_DEFINITIONS[pageType];return definition ? definition.params : null;}@@ -195,10 +240,10 @@ export function getParamsForPageType(pageType) {/*** Gets all valid parameter names for a page type.*- * @param {string} pageType - The page type.- * @returns {string[]} Array of valid parameter names.+ * @param pageType - The page type.+ * @returns Array of valid parameter names.*/-export function getValidParamNames(pageType) {+export function getValidParamNames(pageType: string): string[] {const params = getParamsForPageType(pageType);return params ? Object.keys(params) : [];}@@ -206,35 +251,39 @@ export function getValidParamNames(pageType) {/*** Suggests a page type for a potential typo using fuzzy matching.*- * @param {string} typo - The potentially misspelled page type.- * @returns {string|null} The suggested page type, or null if no good match found.+ * @param typo - The potentially misspelled page type.+ * @returns The suggested page type, or null if no good match found.*/-export function suggestPageType(typo) {+export function suggestPageType(typo: string): string | null {return findClosestMatch(typo, VALID_PAGE_TYPES);}/*** Validates that all provided params are valid for ALL listed page types.*- * @param {Object} params - The params object to validate.- * @param {string[]} pages - The array of page types.- * @returns {{valid: boolean, errors: string[]}} Validation result with any errors.+ * @param params - The params object to validate.+ * @param pages - The array of page types.+ * @returns Validation result with any errors.*/-export function validateParamsAgainstPages(params, pages) {- const errors = [];+export function validateParamsAgainstPages(+ params: unknown,+ pages: string[]+): { valid: boolean; errors: string[] } {+ const errors: string[] = [];if (!params || typeof params !== "object") {return { valid: true, errors: [] };}- const paramNames = Object.keys(params);+ const paramsRecord = params as Record<string, unknown>;+ const paramNames = Object.keys(paramsRecord);if (paramNames.length === 0) {return { valid: true, errors: [] };}for (const paramName of paramNames) {- const validFor = [];- const invalidFor = [];+ const validFor: string[] = [];+ const invalidFor: string[] = [];for (const pageType of pages) {const pageParams = getParamsForPageType(pageType);@@ -273,12 +322,16 @@ export function validateParamsAgainstPages(params, pages) {/*** Validates the type of a parameter value against its definition.*- * @param {string} paramName - The parameter name.- * @param {*} value - The value to validate.- * @param {string} pageType - The page type (for error messages).- * @returns {{valid: boolean, error: string|null}} Validation result.+ * @param paramName - The parameter name.+ * @param value - The value to validate.+ * @param pageType - The page type (for error messages).+ * @returns Validation result.*/-export function validateParamType(paramName, value, pageType) {+export function validateParamType(+ paramName: string,+ value: unknown,+ pageType: string+): { valid: boolean; error: string | null } {const params = getParamsForPageType(pageType);if (!params || !(paramName in params)) {return { valid: false, error: `Unknown parameter '${paramName}'` };@@ -293,7 +346,7 @@ export function validateParamType(paramName, value, pageType) {valid: false,error:`Parameter '${paramName}' must be a number, got ${actualType} '${value}'.\n` +- `Hint: Use numeric value: { params: { ${paramName}: ${parseInt(value, 10) || 123} } }`,+ `Hint: Use numeric value: { params: { ${paramName}: ${parseInt(String(value), 10) || 123} } }`,};}} else if (definition.type === "string") {@@ -314,18 +367,21 @@ export function validateParamType(paramName, value, pageType) {* Returns an object with the current values for all parameters defined for* this page type, or null if the page type doesn't match the current route.*- * @param {string} pageType - The page type (e.g., "CATEGORY_PAGES").- * @param {Object} services - Injected services for context extraction.- * @param {Object} services.router - The Ember router service.- * @param {Object} services.discovery - The Discourse discovery service.- * @returns {Object|null} The context object with param values, or null if page type doesn't match.+ * @param pageType - The page type (e.g., "CATEGORY_PAGES").+ * @param services - Injected services for context extraction.+ * @returns The context object with param values, or null if page type doesn't match.** @example+ * ```* const context = getPageContext("CATEGORY_PAGES", { router, discovery });* // Returns { categoryId: 5, categorySlug: "general", parentCategoryId: null }* // or null if not on a category page+ * ```*/-export function getPageContext(pageType, { router, discovery }) {+export function getPageContext(+ pageType: string,+ { router, discovery }: PageContextServices+): Record<string, unknown> | null {switch (pageType) {case "CATEGORY_PAGES": {const category = discovery.category;@@ -387,7 +443,7 @@ export function getPageContext(pageType, { router, discovery }) {}const routeParams = router.currentRoute?.params || {};return {- id: routeParams.id ? parseInt(routeParams.id, 10) : undefined,+ id: routeParams.id ? parseInt(String(routeParams.id), 10) : undefined,slug: routeParams.slug,};}@@ -422,16 +478,19 @@ export function getPageContext(pageType, { router, discovery }) {* Iterates through all valid page types and returns the first one that matches* the current route. Useful for debugging to show what page the user is on.*- * @param {Object} services - Injected services for context extraction.- * @param {Object} services.router - The Ember router service.- * @param {Object} services.discovery - The Discourse discovery service.- * @returns {string|null} The current page type, or null if no match.+ * @param services - Injected services for context extraction.+ * @returns The current page type, or null if no match.** @example+ * ```* const pageType = getCurrentPageType({ router, discovery });* // Returns "CATEGORY_PAGES", "TOPIC_PAGES", etc., or null+ * ```*/-export function getCurrentPageType({ router, discovery }) {+export function getCurrentPageType({+ router,+ discovery,+}: PageContextServices): string | null {for (const pageType of VALID_PAGE_TYPES) {if (getPageContext(pageType, { router, discovery }) !== null) {return pageType;diff --git a/frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.js b/frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.tssimilarity index 76%rename from frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.jsrename to frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.tsindex 292dd4c4c7e..29154c1a9c5 100644--- a/frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.js+++ b/frontend/discourse/app/lib/blocks/-internals/matching/url-matcher.ts@@ -1,4 +1,3 @@-// @ts-checkimport picomatch from "picomatch";import { withoutPrefix } from "discourse/lib/get-url";@@ -13,8 +12,8 @@ import { withoutPrefix } from "discourse/lib/get-url";* This ensures theme authors don't need to know about subfolder configurations* and can write patterns like `/c/**` that work universally.*- * @param {string} url - The URL to normalize (typically `router.currentURL`).- * @returns {string} The normalized path, ready for pattern matching.+ * @param url - The URL to normalize (typically `router.currentURL`).+ * @returns The normalized path, ready for pattern matching.** @example* // Subfolder stripping@@ -36,13 +35,13 @@ import { withoutPrefix } from "discourse/lib/get-url";* normalizePath(""); // "/"* normalizePath(null); // "/"*/-export function normalizePath(url) {+export function normalizePath(url: string | null | undefined): string {if (!url) {return "/";}// Strip subfolder prefix first (e.g., /forum -> "")- let path = withoutPrefix(url);+ let path: string = withoutPrefix(url) as string;// Strip query string and hash fragmentpath = path.split("?")[0].split("#")[0];@@ -65,24 +64,30 @@ export function normalizePath(url) {* - `[abc]` matches any character in the brackets* - `{a,b}` matches any of the comma-separated patterns*- * @param {string} path - The normalized URL path to test.- * @param {string} pattern - The glob pattern to match against.- * @returns {boolean} True if the path matches the pattern.+ * @param path - The normalized URL path to test.+ * @param pattern - The glob pattern to match against.+ * @returns True if the path matches the pattern.** @example+ * ```* // Single wildcard* matchUrlPattern("/c/general", "/c/*"); // true* matchUrlPattern("/c/general/sub", "/c/*"); // false+ * ```** @example+ * ```* // Double wildcard* matchUrlPattern("/c/general/sub", "/c/**"); // true+ * ```** @example+ * ```* // Brace expansion* matchUrlPattern("/latest", "/{latest,top}"); // true+ * ```*/-export function matchUrlPattern(path, pattern) {+export function matchUrlPattern(path: string, pattern: string): boolean {const isMatch = picomatch(pattern, { dot: true });return isMatch(path);}@@ -90,14 +95,16 @@ export function matchUrlPattern(path, pattern) {/*** Checks if any URL pattern in the array matches the given path.*- * @param {string} path - The normalized URL path to test.- * @param {string[]} patterns - Array of URL patterns.- * @returns {boolean} True if any pattern matches the path.+ * @param path - The normalized URL path to test.+ * @param patterns - Array of URL patterns.+ * @returns True if any pattern matches the path.** @example+ * ```* matchesAnyPattern("/c/general", ["/c/**", "/t/**"]); // true (matches /c/**)* matchesAnyPattern("/latest", ["/c/**", "/t/**"]); // false+ * ```*/-export function matchesAnyPattern(path, patterns) {+export function matchesAnyPattern(path: string, patterns: string[]): boolean {return patterns.some((pattern) => matchUrlPattern(path, pattern));}diff --git a/frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.js b/frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.tssimilarity index 69%rename from frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.jsrename to frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.tsindex dfb635ad794..8e03630fe19 100644--- a/frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.js+++ b/frontend/discourse/app/lib/blocks/-internals/matching/value-matcher.ts@@ -1,6 +1,33 @@-// @ts-check+import type { DebugLoggerInterface } from "discourse/lib/blocks/-internals/debug-hooks";import { findClosestMatch } from "discourse/lib/string-similarity";+/**+ * Evaluation context for `matchParams()`, carrying debug logging state through+ * recursive AND/OR/NOT evaluation.+ */+export interface MatchParamsContext {+ /** Enable debug logging. */+ debug?: boolean;+ /** Nesting depth for logging. */+ _depth?: number;+ /** Logger interface from dev-tools (optional). */+ logger?: DebugLoggerInterface | null;+}++/**+ * Options accepted by `matchParams()`.+ */+export interface MatchParamsOptions {+ /** Current params from router. */+ actualParams?: Record<string, unknown> | null;+ /** Expected params spec. */+ expectedParams?: unknown;+ /** Debug context. */+ context?: MatchParamsContext;+ /** Label for debug output (e.g., "params", "queryParams"). */+ label?: string;+}+/*** Evaluates a value matcher spec against an actual value.* Supports the same AND/OR/NOT logic as condition evaluation.@@ -13,12 +40,17 @@ import { findClosestMatch } from "discourse/lib/string-similarity";* - NOT: `{ not: value }` matches if actual does NOT match value* - ANY (OR): `{ any: [...] }` matches if actual matches any spec in array*- * @param {Object} options - Options object.- * @param {*} options.actual - The actual value to test.- * @param {*} options.expected - The expected value spec (exact, array, regex, or AND/OR/NOT spec).- * @returns {boolean} True if the actual value matches the expected spec.+ * @param actual - The actual value to test.+ * @param expected - The expected value spec (exact, array, regex, or AND/OR/NOT spec).+ * @returns True if the actual value matches the expected spec.*/-export function matchValue({ actual, expected }) {+export function matchValue({+ actual,+ expected,+}: {+ actual: unknown;+ expected: unknown;+}): boolean {// Handle arrays first (before checking for `any`/`not` properties)// because Ember prototype extensions add `any()` method to arraysif (Array.isArray(expected)) {@@ -31,13 +63,18 @@ export function matchValue({ actual, expected }) {}// OR logic: { any: [...] }- if (expected?.any !== undefined) {- return expected.any.some((exp) => matchValue({ actual, expected: exp }));+ if ((expected as { any?: unknown[] } | null | undefined)?.any !== undefined) {+ return (expected as { any: unknown[] }).any.some((exp) =>+ matchValue({ actual, expected: exp })+ );}// NOT logic: { not: ... }- if (expected?.not !== undefined) {- return !matchValue({ actual, expected: expected.not });+ if ((expected as { not?: unknown } | null | undefined)?.not !== undefined) {+ return !matchValue({+ actual,+ expected: (expected as { not: unknown }).not,+ });}// Simple value matching (leaf node)@@ -49,10 +86,10 @@ export function matchValue({ actual, expected }) {* array (for AND matching). Simple value arrays contain only primitives (strings,* numbers, booleans, null, undefined) or RegExp objects.*- * @param {Array} arr - The array to check.- * @returns {boolean} True if all items are primitives or RegExp.+ * @param arr - The array to check.+ * @returns True if all items are primitives or RegExp.*/-function isSimpleValueArray(arr) {+function isSimpleValueArray(arr: unknown[]): boolean {return arr.every((item) =>typeof item !== "object" || item === null || item instanceof RegExp@@ -66,11 +103,11 @@ function isSimpleValueArray(arr) {* testing. This means numeric values like `123` will match patterns like `/1/`* (because 123 is converted to "123").*- * @param {*} actual - The actual value.- * @param {*} expected - The expected value (primitive, array of primitives/RegExp, or RegExp).- * @returns {boolean} True if matches.+ * @param actual - The actual value.+ * @param expected - The expected value (primitive, array of primitives/RegExp, or RegExp).+ * @returns True if matches.*/-function matchSimpleValue(actual, expected) {+function matchSimpleValue(actual: unknown, expected: unknown): boolean {// RegExp pattern - coerce actual to string for testingif (expected instanceof RegExp) {return expected.test(String(actual));@@ -89,11 +126,11 @@ function matchSimpleValue(actual, expected) {* Checks if a failed match is due to a string/number type mismatch.* Used to provide helpful debug hints.*- * @param {*} actual - The actual value.- * @param {*} expected - The expected value.- * @returns {boolean} True if the values would match with type coercion.+ * @param actual - The actual value.+ * @param expected - The expected value.+ * @returns True if the values would match with type coercion.*/-export function isTypeMismatch(actual, expected) {+export function isTypeMismatch(actual: unknown, expected: unknown): boolean {// Already matches - not a mismatchif (actual === expected) {return false;@@ -113,8 +150,10 @@ export function isTypeMismatch(actual, expected) {}// Check { any: [...] } for type mismatches- if (expected?.any !== undefined) {- return expected.any.some((exp) => isTypeMismatch(actual, exp));+ if ((expected as { any?: unknown[] } | null | undefined)?.any !== undefined) {+ return (expected as { any: unknown[] }).any.some((exp) =>+ isTypeMismatch(actual, exp)+ );}return false;@@ -131,22 +170,14 @@ export function isTypeMismatch(actual, expected) {** Keys starting with backslash are escaped (e.g., `"\\any"` matches literal param `"any"`).*- * @param {Object} options - Options object.- * @param {Object} options.actualParams - Current params from router.- * @param {Object|Array} options.expectedParams - Expected params spec.- * @param {Object} [options.context] - Debug context.- * @param {boolean} [options.context.debug] - Enable debug logging.- * @param {number} [options.context._depth] - Nesting depth for logging.- * @param {Object} [options.context.logger] - Logger interface from dev-tools (optional).- * @param {string} [options.label] - Label for debug output (e.g., "params", "queryParams").- * @returns {boolean} True if params match.+ * @returns True if params match.*/export function matchParams({actualParams,expectedParams,context = {},label = "params",-}) {+}: MatchParamsOptions): boolean {const isLoggingEnabled = context.debug ?? false;const depth = context._depth ?? 0;const logger = context.logger;@@ -182,8 +213,8 @@ export function matchParams({}// OR logic: { any: [...] }- if (expectedParams.any !== undefined) {- const specs = expectedParams.any;+ if ((expectedParams as { any?: unknown[] }).any !== undefined) {+ const specs = (expectedParams as { any: unknown[] }).any;// Log combinator BEFORE children so it appears first in treelogger?.logCondition?.({@@ -210,7 +241,7 @@ export function matchParams({}// NOT logic: { not: {...} }- if (expectedParams.not !== undefined) {+ if ((expectedParams as { not?: unknown }).not !== undefined) {// Log combinator BEFORE children so it appears first in treelogger?.logCondition?.({type: "NOT",@@ -222,7 +253,7 @@ export function matchParams({const innerResult = matchParams({actualParams,- expectedParams: expectedParams.not,+ expectedParams: (expectedParams as { not: unknown }).not,context: { debug: isLoggingEnabled, _depth: depth + 1, logger },label,});@@ -235,18 +266,24 @@ export function matchParams({// Plain object with keys = AND logic across all keys// Note: keys starting with \ are escaped (e.g., "\\any" matches literal param "any")- const keys = Object.keys(expectedParams);+ const expectedParamsRecord = expectedParams as Record<string, unknown>;+ const keys = Object.keys(expectedParamsRecord);if (keys.length === 0) {return true;}// Collect match results for debug logging- const matches = [];+ const matches: Array<{+ key: string;+ expected: unknown;+ actual: unknown;+ result: boolean;+ }> = [];for (const key of keys) {// Strip leading backslash for escaped keys (e.g., "\\any" -> "any")const actualKey = key.startsWith("\\") ? key.slice(1) : key;- const expected = expectedParams[key];+ const expected = expectedParamsRecord[key];const actual = actualParams?.[actualKey];const result = matchValue({ actual, expected });matches.push({ key: actualKey, expected, actual, result });@@ -269,7 +306,7 @@ export function matchParams({* Valid operator keys for param/queryParam specs.* These are the only keys with special meaning in param matching.*/-const VALID_OPERATOR_KEYS = Object.freeze(["any", "not"]);+const VALID_OPERATOR_KEYS: readonly string[] = Object.freeze(["any", "not"]);/*** Validates a param spec for typos in operator keys.@@ -277,11 +314,15 @@ const VALID_OPERATOR_KEYS = Object.freeze(["any", "not"]);* Recursively checks that any object key that looks like an operator typo* (e.g., "an" instead of "any", "nto" instead of "not") is flagged.*- * @param {*} spec - The param spec to validate.- * @param {string} path - Current path for error messages.- * @param {Function} raiseError - Function to call with error message.+ * @param spec - The param spec to validate.+ * @param path - Current path for error messages.+ * @param raiseError - Function to call with error message.*/-export function validateParamSpec(spec, path, raiseError) {+export function validateParamSpec(+ spec: unknown,+ path: string,+ raiseError: (message: string) => void+): void {if (spec === null || spec === undefined) {return;}@@ -300,7 +341,8 @@ export function validateParamSpec(spec, path, raiseError) {}// Objects: check keys for operator typos- const keys = Object.keys(spec);+ const specRecord = spec as Record<string, unknown>;+ const keys = Object.keys(specRecord);for (const key of keys) {// Check if this key looks like a typo of a valid operator@@ -318,6 +360,6 @@ export function validateParamSpec(spec, path, raiseError) {}// Recursively validate the value- validateParamSpec(spec[key], `${path}.${key}`, raiseError);+ validateParamSpec(specRecord[key], `${path}.${key}`, raiseError);}}diff --git a/frontend/discourse/app/lib/blocks/-internals/patterns.js b/frontend/discourse/app/lib/blocks/-internals/patterns.tssimilarity index 76%rename from frontend/discourse/app/lib/blocks/-internals/patterns.jsrename to frontend/discourse/app/lib/blocks/-internals/patterns.tsindex 55cbad78ccd..49f8cbedd6f 100644--- a/frontend/discourse/app/lib/blocks/-internals/patterns.js+++ b/frontend/discourse/app/lib/blocks/-internals/patterns.ts@@ -1,8 +1,5 @@-// @ts-check/*** Pattern constants for block name validation.- *- * @module discourse/lib/blocks/-internals/patterns*//**@@ -14,8 +11,6 @@** A depth of 20 is generous for real-world use cases while protecting against* malicious or buggy configurations that could cause infinite recursion.- *- * @type {number}*/export const MAX_LAYOUT_DEPTH = 20;@@ -27,8 +22,6 @@ export const MAX_LAYOUT_DEPTH = 20;* protecting against malicious or buggy configurations.** This applies to the full namespaced name (e.g., "theme:my-theme:my-block").- *- * @type {number}*/export const MAX_BLOCK_NAME_LENGTH = 100;@@ -39,8 +32,6 @@ export const MAX_BLOCK_NAME_LENGTH = 100;** Used in layout validation and block registration to identify optional* blocks that aren't registered and should be skipped during validation and rendering.- *- * @type {symbol}*/export const OPTIONAL_MISSING = Symbol("optional-missing");@@ -64,14 +55,31 @@ export const FAILURE_TYPE = Object.freeze({OPTIONAL_MISSING: "optional-missing",});+/**+ * A resolved-block marker indicating an optional block reference (`name?`)+ * that isn't registered. Returned by resolution functions such as+ * `tryResolveBlock()` in place of a block class.+ */+export interface OptionalMissingMarker {+ optionalMissing: typeof OPTIONAL_MISSING;+ name: string;+}+/*** Checks if a resolved block is an optional missing block marker.*- * @param {*} resolvedBlock - The result from tryResolveBlock.- * @returns {boolean} True if the block is an optional missing marker.+ * @param resolvedBlock - The result from tryResolveBlock.+ * @returns True if the block is an optional missing marker.*/-export function isOptionalMissing(resolvedBlock) {- return resolvedBlock?.optionalMissing === OPTIONAL_MISSING;+export function isOptionalMissing(+ resolvedBlock: unknown+): resolvedBlock is OptionalMissingMarker {+ return (+ typeof resolvedBlock === "object" &&+ resolvedBlock !== null &&+ "optionalMissing" in resolvedBlock &&+ resolvedBlock.optionalMissing === OPTIONAL_MISSING+ );}/**@@ -102,6 +110,7 @@ export const VALID_BLOCK_ID_PATTERN = VALID_BLOCK_NAME_PATTERN;* numbers, and hyphens.** @example+ * ```* // Valid patterns:* "group" // Core block* "chat:message-widget" // Plugin block@@ -111,28 +120,28 @@ export const VALID_BLOCK_ID_PATTERN = VALID_BLOCK_NAME_PATTERN;* "Theme:Name:block" // Uppercase not allowed* "theme:block" // Theme requires namespace segment* "my_block" // Underscores not allowed+ * ```*/export const VALID_NAMESPACED_BLOCK_PATTERN =/^(?:theme:[a-z][a-z0-9-]*:[a-z][a-z0-9-]*|(?!theme:)[a-z][a-z0-9-]*:[a-z][a-z0-9-]*|[a-z][a-z0-9-]*)$/;/*** The parsed components of a block name.- *- * @typedef {{- * type: "core"|"plugin"|"theme",- * namespace: string|null,- * name: string- * }} ParsedBlockName*/+export interface ParsedBlockName {+ type: "core" | "plugin" | "theme";+ namespace: string | null;+ name: string;+}/*** Parses a full block name into its components.*- * @param {string} fullName - The full block name.- * @returns {ParsedBlockName|null}- * An object with the parsed components, or `null` if the name is invalid.+ * @param fullName - The full block name.+ * @returns An object with the parsed components, or `null` if the name is invalid.** @example+ * ```* parseBlockName("group")* // => { type: "core", namespace: null, name: "group" }*@@ -144,8 +153,9 @@ export const VALID_NAMESPACED_BLOCK_PATTERN =** parseBlockName("Invalid_Name")* // => null+ * ```*/-export function parseBlockName(fullName) {+export function parseBlockName(fullName: string): ParsedBlockName | null {// Theme: theme:namespace:nameconst themeMatch = fullName.match(/^theme:([a-z][a-z0-9-]*):([a-z][a-z0-9-]*)$/@@ -173,6 +183,14 @@ export function parseBlockName(fullName) {return null;}+/**+ * The result of parsing a block reference string.+ */+export interface ParsedBlockReference<Name = string | object> {+ name: Name;+ optional: boolean;+}+/*** Parses a block reference string to extract the block name and optional flag.*@@ -185,20 +203,30 @@ export function parseBlockName(fullName) {* - Plugin: `"plugin:block"` or `"plugin:block?"`* - Theme: `"theme:namespace:block"` or `"theme:namespace:block?"`*- * @param {string|Object} blockRef - The block reference. If a string, may have an- * optional `?` suffix. Non-string references (e.g., component classes) are- * returned as-is in the `name` property with `optional: false`.- * @returns {{ name: string|Object, optional: boolean }} Parsed result with the clean- * block name (or original reference) and whether it's optional.+ * @param blockRef - The block reference. If a string, may have an optional `?`+ * suffix. Non-string references (e.g., component classes) are returned as-is+ * in the `name` property with `optional: false`.+ * @returns Parsed result with the clean block name (or original reference) and+ * whether it's optional.** @example+ * ```* parseBlockReference("chat:widget?")* // => { name: "chat:widget", optional: true }** parseBlockReference("hero-banner")* // => { name: "hero-banner", optional: false }+ * ```*/-export function parseBlockReference(blockRef) {+export function parseBlockReference(+ blockRef: string+): ParsedBlockReference<string>;+export function parseBlockReference<T extends object>(+ blockRef: T+): ParsedBlockReference<T>;+export function parseBlockReference(+ blockRef: string | object+): ParsedBlockReference {if (typeof blockRef === "string" && blockRef.endsWith("?")) {return { name: blockRef.slice(0, -1), optional: true };}diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/block.js b/frontend/discourse/app/lib/blocks/-internals/registry/block.tssimilarity index 63%rename from frontend/discourse/app/lib/blocks/-internals/registry/block.jsrename to frontend/discourse/app/lib/blocks/-internals/registry/block.tsindex 54014bea169..64d371d3976 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/block.js+++ b/frontend/discourse/app/lib/blocks/-internals/registry/block.ts@@ -1,12 +1,18 @@-// @ts-checkimport { DEBUG } from "@glimmer/env";import { trackedMap } from "@ember/reactive/collections";+import type { BlockMetadata } from "discourse/blocks/types";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import {OPTIONAL_MISSING,+ type OptionalMissingMarker,parseBlockReference,} from "discourse/lib/blocks/-internals/patterns";+import type {+ BlockClass,+ BlockFactory,+ BlockRegistryEntry,+} from "discourse/lib/blocks/-internals/types";import { isTesting } from "discourse/lib/environment";import {assertNotDuplicate,@@ -16,48 +22,6 @@ import {validateSourceNamespace,} from "./helpers";-/**- * A block class decorated with `@block`.- *- * Block metadata is stored in an internal WeakMap and accessed via the- * `getBlockMetadata()` function from the decorator module.- *- * @typedef {typeof import("@glimmer/component").default} BlockClass- */--/**- * Metadata object containing block configuration set by the `@block` decorator.- * Includes args schema, container settings, validation, and outlet restrictions.- *- * @typedef {{- * blockName: string,- * shortName: string,- * namespace: string|null,- * namespaceType: "core"|"plugin"|"theme",- * description: string,- * isContainer: boolean,- * decoratorClassNames: string|Array<string>|Function|null,- * args: Object|null,- * childArgs: Object|null,- * constraints: Object|null,- * validate: Function|null,- * allowedOutlets: ReadonlyArray<string>|null,- * deniedOutlets: ReadonlyArray<string>|null- * }} BlockMetadata- */--/**- * A factory function that returns a Promise resolving to a BlockClass or module with default export.- *- * @typedef {() => Promise<BlockClass | { default: BlockClass }>} BlockFactory- */--/**- * Registry entry: either a resolved BlockClass or a factory function for lazy loading.- *- * @typedef {BlockClass | BlockFactory} BlockRegistryEntry- */-/** Registry State*/@@ -65,10 +29,8 @@ import {/*** Registry of block components registered via `api.registerBlock()`.* Maps block names to their component classes or factory functions.- *- * @type {Map<string, BlockRegistryEntry>}*/-const blockRegistry = new Map();+const blockRegistry = new Map<string, BlockRegistryEntry>();/*** Cache for resolved factory functions.@@ -78,46 +40,27 @@ const blockRegistry = new Map();* automatically re-render when a factory they depend on finishes resolving.* The tracked map tracks per-key, so only components waiting on specific blocks* are invalidated.- *- * @type {Map<string, BlockClass>}*/-const resolvedFactoryCache = trackedMap();+const resolvedFactoryCache = trackedMap<string, BlockClass>();-/**- * Tracks in-flight resolution promises to prevent duplicate concurrent attempts.- *- * @type {Map<string, Promise<BlockClass|undefined>>}- */-const pendingResolutions = new Map();+/** Tracks in-flight resolution promises to prevent duplicate concurrent attempts. */+const pendingResolutions = new Map<string, Promise<BlockClass | undefined>>();-/**- * Caches failed resolution attempts to prevent infinite retry loops.- *- * @type {Set<string>}- */-const failedResolutions = new Set();+/** Caches failed resolution attempts to prevent infinite retry loops. */+const failedResolutions = new Set<string>();-/**- * Whether the block registry is frozen (no new registrations allowed).- */+/** Whether the block registry is frozen (no new registrations allowed). */let registryFrozen = false;-/**- * Stores the initial frozen state to allow correct reset after tests.- * @type {boolean | null}- */-let testRegistryFrozenState = null;+/** Stores the initial frozen state to allow correct reset after tests. */+let testRegistryFrozenState: boolean | null = null;/** Public Functions*/-/**- * Returns whether the block registry is frozen.- *- * @returns {boolean}- */-export function isBlockRegistryFrozen() {+/** Returns whether the block registry is frozen. */+export function isBlockRegistryFrozen(): boolean {return registryFrozen;}@@ -127,24 +70,25 @@ export function isBlockRegistryFrozen() {* This is a synchronous check that does not resolve factory functions.* Use this to verify a block exists before attempting resolution.*- * @param {string | BlockClass} nameOrClass - Block name string or BlockClass.- * @returns {boolean} True if the block is registered.+ * @param nameOrClass - Block name string or BlockClass.+ * @returns True if the block is registered.*/-export function hasBlock(nameOrClass) {+export function hasBlock(nameOrClass: string | BlockClass) {if (typeof nameOrClass === "string") {return blockRegistry.has(nameOrClass);}- const blockName = getBlockMetadata(nameOrClass)?.blockName;+ const metadata: BlockMetadata | null = getBlockMetadata(nameOrClass);+ const blockName = metadata?.blockName;return blockName && blockRegistry.has(blockName);}/*** Returns the registry entry for a block (class or factory).*- * @param {string} name - The block name.- * @returns {BlockRegistryEntry | undefined} The registry entry, or undefined if not found.+ * @param name - The block name.+ * @returns The registry entry, or undefined if not found.*/-export function getBlockEntry(name) {+export function getBlockEntry(name: string): BlockRegistryEntry | undefined {return blockRegistry.get(name);}@@ -152,19 +96,19 @@ export function getBlockEntry(name) {* Returns all block entries with their names as [name, entry] pairs.* Used by Blocks service for listing and introspection.*- * @returns {Array<[string, BlockRegistryEntry]>} Array of [name, entry] pairs.+ * @returns Array of [name, entry] pairs.*/-export function getAllBlockEntries() {+export function getAllBlockEntries(): Array<[string, BlockRegistryEntry]> {return Array.from(blockRegistry.entries());}/*** Checks if a block is registered and fully resolved (not a pending factory).*- * @param {string} name - The block name to check.- * @returns {boolean} True if registered and resolved.+ * @param name - The block name to check.+ * @returns True if registered and resolved.*/-export function isBlockResolved(name) {+export function isBlockResolved(name: string): boolean {if (!blockRegistry.has(name)) {return false;}@@ -178,10 +122,12 @@ export function isBlockResolved(name) {* Factory functions are plain functions not registered in the block metadata WeakMap.* BlockClasses are tracked by the `@block` decorator.*- * @param {BlockRegistryEntry} entry - The registry entry to check.- * @returns {entry is BlockFactory} True if the entry is a factory function.+ * @param entry - The registry entry to check.+ * @returns True if the entry is a factory function.*/-export function isBlockFactory(entry) {+export function isBlockFactory(+ entry: BlockRegistryEntry | undefined+): entry is BlockFactory {return typeof entry === "function" && !getBlockMetadata(entry);}@@ -192,9 +138,9 @@ export function isBlockFactory(entry) {* - If given a string, looks up in registry and resolves factory if needed.* - Caches resolved factories to avoid re-resolving.*- * @param {string | BlockClass} nameOrClass - Block name string or BlockClass.- * @returns {Promise<BlockClass|undefined>} The resolved block class, or undefined if resolution previously failed.- * @throws {Error} If block not registered or factory resolution fails on first attempt.+ * @param nameOrClass - Block name string or BlockClass.+ * @returns The resolved block class, or undefined if resolution previously failed.+ * @throws If block not registered or factory resolution fails on first attempt.** @example* ```javascript@@ -202,7 +148,9 @@ export function isBlockFactory(entry) {* const BlockClass = await resolveBlock(HeroBanner); // Returns directly* ```*/-export async function resolveBlock(nameOrClass) {+export async function resolveBlock(+ nameOrClass: string | BlockClass+): Promise<BlockClass | undefined> {if (typeof nameOrClass !== "string") {if (!getBlockMetadata(nameOrClass)) {raiseBlockError(@@ -234,7 +182,8 @@ export async function resolveBlock(nameOrClass) {);}- const entry = blockRegistry.get(name);+ // Guaranteed to be set by the `.has()` check above.+ const entry = blockRegistry.get(name)!;if (!isBlockFactory(entry)) {return entry;@@ -253,14 +202,15 @@ export async function resolveBlock(nameOrClass) {* and returns null. The calling component will automatically re-render when the* factory resolves.*- * @param {string | BlockClass} blockRef - Block reference (string name or class).- * String names may include a trailing "?" to mark the block as optional.- * @returns {BlockClass | { optionalMissing: symbol, name: string } | null}- * - The BlockClass if found and resolved- * - An object with `optionalMissing` marker if the block is optional and not registered- * - null if the block is not registered (non-optional) or is a factory awaiting resolution+ * @param blockRef - Block reference (string name or class). String names may+ * include a trailing "?" to mark the block as optional.+ * @returns The BlockClass if found and resolved; an optional-missing marker if+ * the block is optional and not registered; or `null` if the block is not+ * registered (non-optional) or is a factory awaiting resolution.*/-export function tryResolveBlock(blockRef) {+export function tryResolveBlock(+ blockRef: string | BlockClass+): BlockClass | OptionalMissingMarker | null {if (typeof blockRef !== "string") {return blockRef;}@@ -284,7 +234,8 @@ export function tryResolveBlock(blockRef) {return null;}- const entry = blockRegistry.get(blockName);+ // Guaranteed to be set by the `.has()` check above.+ const entry = blockRegistry.get(blockName)!;if (!isBlockFactory(entry)) {return entry;@@ -292,7 +243,7 @@ export function tryResolveBlock(blockRef) {// Trigger async resolution. Returns null for this render cycle - the component// will re-render automatically when the factory resolves (tracked via TrackedMap).- resolveBlock(blockName).catch((error) => {+ resolveBlock(blockName).catch((error: unknown) => {// TODO (blocks-api) Consider returning an error marker and rendering an error// placeholder component for admin visibility, rather than silently returning null.document.dispatchEvent(@@ -315,7 +266,7 @@ export function tryResolveBlock(blockRef) {** @internal*/-export function _freezeBlockRegistry() {+export function _freezeBlockRegistry(): void {registryFrozen = true;}@@ -327,8 +278,11 @@ export function _freezeBlockRegistry() {* (including `blockName`) is stored in an internal WeakMap and accessed* via `getBlockMetadata()`.*- * @param {BlockClass} BlockClass - The block component class- * @throws {Error} If called after registry is locked, or if block is invalid+ * @param klass - The block component class. Typed nullable because untyped+ * 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.+ * @throws If called after registry is locked, or if block is invalid** @example* ```javascript@@ -345,23 +299,24 @@ export function _freezeBlockRegistry() {* };* ```*/-export function _registerBlock(BlockClass) {- const blockName = getBlockMetadata(BlockClass)?.blockName;+export function _registerBlock(klass: BlockClass | null | undefined): void {+ const metadata: BlockMetadata | null = getBlockMetadata(klass);+ const blockName = metadata?.blockName;if (!assertRegistryNotFrozen({frozen: registryFrozen,apiMethod: "api.registerBlock()",entityType: "Block",- entityName: blockName || BlockClass?.name,+ entityName: blockName || klass?.name,})) {return;}- if (!blockName) {+ if (!klass || !blockName) {raiseBlockError(- `Block class "${BlockClass?.name}" must be decorated with @block to be registered.`+ `Block class "${klass?.name}" must be decorated with @block to be registered.`);return;}@@ -378,7 +333,7 @@ export function _registerBlock(BlockClass) {return;}- blockRegistry.set(blockName, BlockClass);+ blockRegistry.set(blockName, klass);}/**@@ -387,9 +342,9 @@ export function _registerBlock(BlockClass) {* The factory will be called when the block is first needed. It must return* a Promise that resolves to a BlockClass (or a module with a default export).*- * @param {string} name - The name to register the block under.- * @param {BlockFactory} factory - Factory function returning Promise<BlockClass>.- * @throws {Error} If registry is locked, name is invalid, or factory is not a function.+ * @param name - The name to register the block under.+ * @param factory - Factory function returning Promise<BlockClass>.+ * @throws If registry is locked, name is invalid, or factory is not a function.** @example* ```javascript@@ -398,7 +353,10 @@ export function _registerBlock(BlockClass) {** @internal*/-export function _registerBlockFactory(name, factory) {+export function _registerBlockFactory(+ name: string,+ factory: BlockFactory+): void {if (!assertRegistryNotFrozen({frozen: registryFrozen,@@ -435,17 +393,24 @@ export function _registerBlockFactory(name, factory) {/*** Resolves a factory function and caches the result.*- * @param {string} name - The block name.- * @param {BlockFactory} factory - The factory function to resolve.- * @returns {Promise<BlockClass>} The resolved block class.- * @throws {BlockError} If the factory returns an invalid class or the resolved name doesn't match.+ * @param name - The block name.+ * @param factory - The factory function to resolve.+ * @returns The resolved block class.+ * @throws If the factory returns an invalid class or the resolved name doesn't match.*/-async function resolveFactory(name, factory) {+async function resolveFactory(+ name: string,+ factory: BlockFactory+): Promise<BlockClass | undefined> {try {const result = await factory();- // @ts-ignore - result may be a module with .default or direct BlockClass- const BlockClass = result?.default ?? result;- const resolvedBlockName = getBlockMetadata(BlockClass)?.blockName;++ // A factory resolves to the class itself or to a module namespace, and to+ // nothing at all when an author forgets to return. Unwrap without assuming+ // a value is present so an absent result reaches the error below.+ const resolvedClass = ((result as { default?: BlockClass } | null)+ ?.default ?? result) as BlockClass;+ const resolvedBlockName = getBlockMetadata(resolvedClass)?.blockName;if (!resolvedBlockName) {raiseBlockError(@@ -461,18 +426,23 @@ async function resolveFactory(name, factory) {);}- resolvedFactoryCache.set(name, BlockClass);- blockRegistry.set(name, BlockClass);+ resolvedFactoryCache.set(name, resolvedClass);+ blockRegistry.set(name, resolvedClass);- return BlockClass;- } catch (error) {+ return resolvedClass;+ } catch (error: unknown) {failedResolutions.add(name);- if (error.name === "BlockError") {- throw error;+ // Thrown errors are always `Error`-like: either a rethrown `BlockError` or+ // a factory/import failure. Cast to read `.name`/`.message` without+ // widening the catch signature to `any`.+ const err = error as Error;++ if (err.name === "BlockError") {+ throw err;}raiseBlockError(- `Failed to resolve block factory for "${name}": ${error.message}`+ `Failed to resolve block factory for "${name}": ${err.message}`);return undefined;} finally {@@ -488,8 +458,6 @@ async function resolveFactory(name, factory) {* Temporarily unfreezes the block registry for testing.** USE ONLY FOR TESTING PURPOSES.- *- * @param {Function} callback - Function to execute with unfrozen registry.*/export const withTestBlockRegistration = createTestRegistrationWrapper({getFrozen: () => registryFrozen,@@ -510,7 +478,7 @@ export const withTestBlockRegistration = createTestRegistrationWrapper({** @internal Called by `resetBlockRegistryForTesting`, not meant for direct use.*/-export function _resetBlockRegistryState() {+export function _resetBlockRegistryState(): void {// allows tree-shaking in production buildsif (!DEBUG) {return;diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/condition.js b/frontend/discourse/app/lib/blocks/-internals/registry/condition.tssimilarity index 77%rename from frontend/discourse/app/lib/blocks/-internals/registry/condition.jsrename to frontend/discourse/app/lib/blocks/-internals/registry/condition.tsindex 83f6cf5e83f..09a1591d72b 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/condition.js+++ b/frontend/discourse/app/lib/blocks/-internals/registry/condition.ts@@ -1,5 +1,5 @@-// @ts-checkimport { 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 { isTesting } from "discourse/lib/environment";@@ -21,52 +21,42 @@ import {* Unlike blocks which store component classes, conditions are stored as classes* and instantiated by the Blocks service when first needed. This allows the* service to set the owner for dependency injection.- *- * @type {Map<string, typeof import("discourse/blocks/conditions").BlockCondition>}*/-const conditionTypeRegistry = new Map();+const conditionTypeRegistry = new Map<string, typeof BlockCondition>();-/**- * Whether the condition type registry is frozen (no new registrations allowed).- */+/** Whether the condition type registry is frozen (no new registrations allowed). */let conditionTypeRegistryFrozen = false;/*** Stores the initial frozen state for condition registry to allow correct reset after tests.- * @type {boolean | null}*/-let testConditionRegistryFrozenState = null;+let testConditionRegistryFrozenState: boolean | null = null;/** Public Functions*/-/**- * Returns whether the condition type registry is frozen.- *- * @returns {boolean}- */-export function isConditionTypeRegistryFrozen() {+/** Returns whether the condition type registry is frozen. */+export function isConditionTypeRegistryFrozen(): boolean {return conditionTypeRegistryFrozen;}/*** Checks if a condition type is registered.*- * @param {string} type - The condition type name.- * @returns {boolean}+ * @param type - The condition type name.*/-export function hasConditionType(type) {+export function hasConditionType(type: string): boolean {return conditionTypeRegistry.has(type);}/*** Returns all condition type entries as [type, ConditionClass] pairs.* Used by Blocks service for lazy initialization.- *- * @returns {Array<[string, typeof import("discourse/blocks/conditions").BlockCondition]>}*/-export function getAllConditionTypeEntries() {+export function getAllConditionTypeEntries(): Array<+ [string, typeof BlockCondition]+> {return Array.from(conditionTypeRegistry.entries());}@@ -80,7 +70,7 @@ export function getAllConditionTypeEntries() {** @internal*/-export function _freezeConditionTypeRegistry() {+export function _freezeConditionTypeRegistry(): void {conditionTypeRegistryFrozen = true;}@@ -90,7 +80,10 @@ export function _freezeConditionTypeRegistry() {** The condition class must be decorated with `@blockCondition`*- * @param {typeof import("discourse/blocks/conditions").BlockCondition} ConditionClass - The condition class to register.+ * @param ConditionClass - The condition class to register. Typed nullable+ * because untyped callers can hand `api.registerBlockConditionType()` a bad+ * import; that call must report the decorator error, not a property-read+ * failure.** @example* ```javascript@@ -108,7 +101,9 @@ export function _freezeConditionTypeRegistry() {** @internal*/-export function _registerConditionType(ConditionClass) {+export function _registerConditionType(+ ConditionClass: typeof BlockCondition | null | undefined+): void {if (!assertRegistryNotFrozen({frozen: conditionTypeRegistryFrozen,@@ -121,9 +116,9 @@ export function _registerConditionType(ConditionClass) {}// Ensure the class was created by the @blockCondition decorator- if (!isDecoratedCondition(ConditionClass)) {+ if (!ConditionClass || !isDecoratedCondition(ConditionClass)) {raiseBlockError(- `${ConditionClass.name} must use the @blockCondition decorator. ` ++ `${ConditionClass?.name} must use the @blockCondition decorator. ` +`Manual inheritance from BlockCondition is not allowed.`);return;@@ -159,8 +154,6 @@ export function _registerConditionType(ConditionClass) {** USE ONLY FOR TESTING PURPOSES.*- * @param {Function} callback - Function to execute with unfrozen registry.- ** @example* ```javascript* withTestConditionRegistration(() => {@@ -187,7 +180,7 @@ export const withTestConditionRegistration = createTestRegistrationWrapper({** @internal Called by `resetBlockRegistryForTesting`, not meant for direct use.*/-export function _resetConditionRegistryState() {+export function _resetConditionRegistryState(): void {// allows tree-shaking in production buildsif (!DEBUG) {return;diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/helpers.js b/frontend/discourse/app/lib/blocks/-internals/registry/helpers.tssimilarity index 69%rename from frontend/discourse/app/lib/blocks/-internals/registry/helpers.jsrename to frontend/discourse/app/lib/blocks/-internals/registry/helpers.tsindex 5f1d4f00354..8ad08ec2ced 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/helpers.js+++ b/frontend/discourse/app/lib/blocks/-internals/registry/helpers.ts@@ -1,4 +1,3 @@-// @ts-checkimport { DEBUG } from "@glimmer/env";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import {@@ -15,37 +14,42 @@ import identifySource from "discourse/lib/source-identifier";** Key: source identifier (e.g., "theme:Tactile Theme" or "plugin:chat")* Value: the namespace prefix used (e.g., "theme:tactile" or "chat")- *- * @type {Map<string, string|null>}*/-const sourceNamespaceMap = new Map();+const sourceNamespaceMap = new Map<string, string | null>();-/**- * Override for source identifier in tests.- * @type {string|null|undefined}- */-let testSourceIdentifier;+/** Override for source identifier in tests. */+let testSourceIdentifier: string | null | undefined;/** Public Functions*/+/** Options for {@link assertRegistryNotFrozen}. */+interface AssertRegistryNotFrozenOptions {+ /** Whether the registry is frozen. */+ frozen: boolean;++ /** The API method name for the error message. */+ apiMethod: string;++ /** Type of entity (e.g., "Block", "Outlet", "Condition"). */+ entityType: string;++ /** Name of the entity being registered. */+ entityName: string;+}+/*** Asserts that a registry is not frozen before registration.*- * @param {Object} options - Validation options.- * @param {boolean} options.frozen - Whether the registry is frozen.- * @param {string} options.apiMethod - The API method name for the error message.- * @param {string} options.entityType - Type of entity (e.g., "Block", "Outlet", "Condition").- * @param {string} options.entityName - Name of the entity being registered.- * @returns {boolean} True if not frozen, false if frozen (error was raised).+ * @returns True if not frozen, false if frozen (error was raised).*/export function assertRegistryNotFrozen({frozen,apiMethod,entityType,entityName,-}) {+}: AssertRegistryNotFrozenOptions): boolean {if (frozen) {raiseBlockError(`${apiMethod} was called after the ${entityType.toLowerCase()} registry was frozen. ` +@@ -63,11 +67,11 @@ export function assertRegistryNotFrozen({* Checks both the pattern format and maximum length to prevent memory and* performance issues from extremely long names.*- * @param {string} name - The name to validate.- * @param {string} entityType - Type of entity for error messages (e.g., "Block", "Outlet").- * @returns {boolean} True if valid, false if invalid (error was raised).+ * @param name - The name to validate.+ * @param entityType - Type of entity for error messages (e.g., "Block", "Outlet").+ * @returns True if valid, false if invalid (error was raised).*/-export function validateNamePattern(name, entityType) {+export function validateNamePattern(name: string, entityType: string): boolean {// Check length first to avoid regex issues with extremely long strings.if (name.length > MAX_BLOCK_NAME_LENGTH) {raiseBlockError(@@ -92,12 +96,16 @@ export function validateNamePattern(name, entityType) {/*** Asserts that an entry is not already registered.*- * @param {Map} registry - The registry to check.- * @param {string} name - The name to check.- * @param {string} entityType - Type of entity for error messages.- * @returns {boolean} True if not duplicate, false if duplicate (error was raised).+ * @param registry - The registry to check.+ * @param name - The name to check.+ * @param entityType - Type of entity for error messages.+ * @returns True if not duplicate, false if duplicate (error was raised).*/-export function assertNotDuplicate(registry, name, entityType) {+export function assertNotDuplicate<V>(+ registry: Map<string, V>,+ name: string,+ entityType: string+): boolean {if (registry.has(name)) {raiseBlockError(`${entityType} "${name}" is already registered.`);return false;@@ -105,6 +113,18 @@ export function assertNotDuplicate(registry, name, entityType) {return true;}+/** Options for {@link validateSourceNamespace}. */+interface ValidateSourceNamespaceOptions {+ /** The name being registered. */+ name: string;++ /** Type of entity for error messages. */+ entityType: "block" | "outlet" | "condition";++ /** Whether to enforce single namespace per source. Defaults to `true`. */+ enforceConsistency?: boolean;+}+/*** Validates that a block or outlet name follows namespace requirements for themes and plugins.*@@ -113,17 +133,13 @@ export function assertNotDuplicate(registry, name, entityType) {* - Plugins must use `namespace:name` format* - Optionally enforces that each source uses a consistent namespace across all registrations*- * @param {Object} options - Validation options.- * @param {string} options.name - The name being registered.- * @param {"block"|"outlet"|"condition"} options.entityType - Type of entity for error messages.- * @param {boolean} [options.enforceConsistency=true] - Whether to enforce single namespace per source.- * @returns {boolean} True if validation passes, false if it failed (error was raised).+ * @returns True if validation passes, false if it failed (error was raised).*/export function validateSourceNamespace({name,entityType,enforceConsistency = true,-}) {+}: ValidateSourceNamespaceOptions): boolean {const sourceId = getSourceIdentifier();if (!sourceId) {return true;@@ -180,18 +196,30 @@ export function validateSourceNamespace({return true;}+/** Options for {@link createTestRegistrationWrapper}. */+interface TestRegistrationWrapperOptions {+ /** Function to get frozen state. */+ getFrozen: () => boolean;++ /** Function to set frozen state. */+ setFrozen: (value: boolean) => void;++ /** Function to get saved test state. */+ getSavedState: () => boolean | null;++ /** Function to set saved test state. */+ setSavedState: (value: boolean | null) => void;++ /** Name for error message. */+ name: string;+}+/*** Creates a test registration wrapper function for temporarily unfreezing a registry.** USE ONLY FOR TESTING PURPOSES.*- * @param {Object} options - Options object.- * @param {() => boolean} options.getFrozen - Function to get frozen state.- * @param {(value: boolean) => void} options.setFrozen - Function to set frozen state.- * @param {() => boolean|null} options.getSavedState - Function to get saved test state.- * @param {(value: boolean|null) => void} options.setSavedState - Function to set saved test state.- * @param {string} options.name - Name for error message.- * @returns {((callback: Function) => void)|undefined} The wrapper function.+ * @returns The wrapper function, or `undefined` outside of `DEBUG` builds.*/export function createTestRegistrationWrapper({getFrozen,@@ -199,12 +227,14 @@ export function createTestRegistrationWrapper({getSavedState,setSavedState,name,-}) {+}: TestRegistrationWrapperOptions):+ | ((callback: () => void) => void)+ | undefined {// allows tree-shaking in production buildsif (!DEBUG) {return; // this won't be called in production builds}- return function (callback) {+ return function (callback: () => void): void {if (!isTesting()) {throw new Error(`Use \`${name}\` only in tests.`);}@@ -217,7 +247,9 @@ export function createTestRegistrationWrapper({try {callback();} finally {- setFrozen(getSavedState());+ // Invariant: the check above guarantees a saved (non-null) state by+ // the time this runs.+ setFrozen(getSavedState() as boolean);}};}@@ -230,9 +262,9 @@ 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).*- * @returns {string|null} Source identifier like "theme:Tactile" or "plugin:chat"+ * @returns Source identifier like "theme:Tactile" or "plugin:chat"*/-function getSourceIdentifier() {+function getSourceIdentifier(): string | null {if (DEBUG && testSourceIdentifier !== undefined) {return testSourceIdentifier;}@@ -253,15 +285,17 @@ function getSourceIdentifier() {/*** Extracts the namespace prefix from a block name.*- * @param {string} blockName - The full block name.- * @returns {string|null} The namespace prefix, or null for core blocks.+ * @param blockName - The full block name.+ * @returns The namespace prefix, or null for core blocks.** @example+ * ```* getNamespacePrefix("theme:tactile:banner") // => "theme:tactile"* getNamespacePrefix("chat:widget") // => "chat"* getNamespacePrefix("group") // => null (core)+ * ```*/-function getNamespacePrefix(blockName) {+function getNamespacePrefix(blockName: string): string | null {const parsed = parseBlockName(blockName);if (!parsed) {return null;@@ -280,10 +314,12 @@ function getNamespacePrefix(blockName) {** USE ONLY FOR TESTING PURPOSES.*- * @param {string|null} sourceId - Source identifier to use, or null to clear.+ * @param sourceId - Source identifier to use, or null to clear.* @internal Called by `setTestSourceIdentifier` in block-testing.js.*/-export function _setTestSourceIdentifierInternal(sourceId) {+export function _setTestSourceIdentifierInternal(+ sourceId: string | null+): void {// allows tree-shaking in production buildsif (!DEBUG) {return;@@ -298,7 +334,7 @@ export function _setTestSourceIdentifierInternal(sourceId) {** @internal Called by `resetBlockRegistryForTesting`, not meant for direct use.*/-export function _resetSourceNamespaceState() {+export function _resetSourceNamespaceState(): void {// allows tree-shaking in production buildsif (!DEBUG) {return;diff --git a/frontend/discourse/app/lib/blocks/-internals/registry/outlet.js b/frontend/discourse/app/lib/blocks/-internals/registry/outlet.tssimilarity index 69%rename from frontend/discourse/app/lib/blocks/-internals/registry/outlet.jsrename to frontend/discourse/app/lib/blocks/-internals/registry/outlet.tsindex f29bb212bc9..0f21eaf7df9 100644--- a/frontend/discourse/app/lib/blocks/-internals/registry/outlet.js+++ b/frontend/discourse/app/lib/blocks/-internals/registry/outlet.ts@@ -1,4 +1,3 @@-// @ts-checkimport { DEBUG } from "@glimmer/env";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import { isTesting } from "discourse/lib/environment";@@ -9,6 +8,15 @@ import {validateSourceNamespace,} from "./helpers";+/** Metadata recorded for a custom block outlet. */+interface CustomOutletMetadata {+ /** The outlet name. */+ name: string;++ /** Human-readable description. */+ description?: string;+}+/** Registry State*/@@ -16,55 +24,49 @@ import {/*** Registry of custom block outlets registered by plugins and themes.* Maps outlet names to their metadata.- *- * @type {Map<string, { name: string, description?: string }>}*/-const customOutletRegistry = new Map();+const customOutletRegistry = new Map<string, CustomOutletMetadata>();-/**- * Whether the outlet registry is frozen (no new registrations allowed).- */+/** Whether the outlet registry is frozen (no new registrations allowed). */let outletRegistryFrozen = false;/** Public Functions*/-/**- * Returns whether the outlet registry is frozen.- *- * @returns {boolean}- */-export function isOutletRegistryFrozen() {+/** Returns whether the outlet registry is frozen. */+export function isOutletRegistryFrozen(): boolean {return outletRegistryFrozen;}/*** Returns all valid outlet names (both core and custom).*- * @returns {string[]} Array of all outlet names.+ * @returns Array of all outlet names.*/-export function getAllOutlets() {+export function getAllOutlets(): string[] {return [...BLOCK_OUTLETS, ...customOutletRegistry.keys()];}/*** Checks if an outlet name is valid (registered as core or custom).*- * @param {string} name - The outlet name to check.- * @returns {boolean} True if the outlet is registered.+ * @param name - The outlet name to check.+ * @returns True if the outlet is registered.*/-export function isValidOutlet(name) {+export function isValidOutlet(name: string): boolean {return BLOCK_OUTLETS.includes(name) || customOutletRegistry.has(name);}/*** Gets metadata for a custom outlet.*- * @param {string} name - The outlet name.- * @returns {{ name: string, description?: string } | undefined} Outlet metadata or undefined.+ * @param name - The outlet name.+ * @returns Outlet metadata or undefined.*/-export function getCustomOutlet(name) {+export function getCustomOutlet(+ name: string+): CustomOutletMetadata | undefined {return customOutletRegistry.get(name);}@@ -78,10 +80,16 @@ export function getCustomOutlet(name) {** @internal*/-export function _freezeOutletRegistry() {+export function _freezeOutletRegistry(): void {outletRegistryFrozen = true;}+/** Options for {@link _registerOutlet}. */+interface RegisterOutletOptions {+ /** Human-readable description. */+ description?: string;+}+/*** Registers a custom block outlet.*@@ -90,13 +98,15 @@ export function _freezeOutletRegistry() {* - Plugin outlets: `namespace:outlet-name`* - Theme outlets: `theme:namespace:outlet-name`*- * @param {string} outletName - The outlet name (must follow naming conventions).- * @param {Object} [options] - Outlet options.- * @param {string} [options.description] - Human-readable description.+ * @param outletName - The outlet name (must follow naming conventions).+ * @param options - Outlet options.** @internal*/-export function _registerOutlet(outletName, options = {}) {+export function _registerOutlet(+ outletName: string,+ options: RegisterOutletOptions = {}+): void {if (!assertRegistryNotFrozen({frozen: outletRegistryFrozen,@@ -153,7 +163,7 @@ export function _registerOutlet(outletName, options = {}) {** @internal Called by `resetBlockRegistryForTesting`, not meant for direct use.*/-export function _resetOutletRegistryState() {+export function _resetOutletRegistryState(): void {// allows tree-shaking in production buildsif (!DEBUG) {return;diff --git a/frontend/discourse/app/lib/blocks/-internals/types.ts b/frontend/discourse/app/lib/blocks/-internals/types.tsnew file mode 100644index 00000000000..202f59b85e1--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/types.ts@@ -0,0 +1,72 @@+import type { ComponentLike } from "@glint/template";++/**+ * A block component class decorated with `@block`. Block metadata is stored in+ * an internal WeakMap and read via `getBlockMetadata()`.+ *+ * Glimmer's `Component` is generic and invariant over its `Signature`, so+ * neither `typeof Component` nor `Component<unknown>` accepts a concrete+ * subclass like `class Foo extends Component<FooSignature>`. Since a block class+ * is only ever stored, compared, and curried as an opaque token here — its+ * component-ness is enforced at runtime by the `@block` decorator's+ * `instanceof Component` check — a permissive construct signature is the+ * idiomatic way to accept "any block component class".+ */+export type BlockClass = abstract new (...args: unknown[]) => object;++/**+ * A factory that lazily resolves to a block class (or a module whose default+ * export is one), used for code-split block registration.+ */+export type BlockFactory = () => Promise<BlockClass | { default: BlockClass }>;++/** A registry entry: either a resolved block class or a lazy factory. */+export type BlockRegistryEntry = BlockClass | BlockFactory;++/**+ * A curried, render-ready block component. Curried components carry no+ * statically known args, so this is intentionally a permissive `ComponentLike`.+ */+export type BlockComponent = ComponentLike;++/**+ * A block entry after preprocessing, carrying the visibility/keying metadata+ * the render pipeline assigns (the `__`-prefixed fields).+ */+export interface BlockEntry {+ block: string | BlockClass;+ args?: Record<string, unknown>;+ containerArgs?: Record<string, unknown>;+ children?: BlockEntry[];+ conditions?: object | object[];+ classNames?: string;+ id?: string;++ // Whether the block passed condition evaluation.+ __visible: boolean;++ // Stable key assigned at registration time, preserved across renders.+ __stableKey: number;++ // Failure metadata, populated in debug mode only.+ __failureType?: string;+ __failureReason?: string;+}++/**+ * A renderable child produced by the block pipeline: the curried component, any+ * `containerArgs` destined for the parent's `childArgs` schema, and a stable key+ * for list rendering.+ */+export interface ChildBlockResult {+ Component: BlockComponent;+ containerArgs?: Record<string, unknown>;+ key: string;++ // True for a ghost placeholder rendered in debug mode.+ isGhost?: boolean;++ // Returns a ghost version of this child with the given reason (debug mode),+ // or null when debug mode is disabled. Ghost children return themselves.+ asGhost: (reason: string) => ChildBlockResult | null;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/utils.js b/frontend/discourse/app/lib/blocks/-internals/utils.jsdeleted file mode 100644index 7826d36fad8..00000000000--- a/frontend/discourse/app/lib/blocks/-internals/utils.js+++ /dev/null@@ -1,170 +0,0 @@-// @ts-check-/**- * Utility functions for the block system.- *- * @module discourse/lib/blocks/-internals/utils- */-import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";--/**- * @typedef {Object} ValidationContext- * @property {string} outletName - The name of the outlet being validated.- * @property {string|null} [blockName=null] - The name of the block, if resolved.- * @property {string} path - The hierarchical path to this entry (e.g., "layout[0].children[1]").- * @property {Object|null} [entry=null] - The block entry object being validated.- * @property {Error|null} [callSiteError=null] - Error captured at the call site for stack traces.- * @property {Array|null} [rootLayout=null] - The root layout array for error display.- *- * The following properties are added by validation code after initial context creation:- * @property {string} [errorPath] - Full path to the error (e.g., "layout[0].conditions.params.categoryId").- * @property {string} [conditionsPath] - Path within conditions (e.g., "params.categoryId").- * @property {Object} [conditions] - The conditions object for error display.- */--/**- * Creates a validation context object for error reporting.- * Centralizes context creation to ensure consistent structure across- * all validation functions.- *- * @param {Object} params - Context parameters.- * @param {string} params.outletName - The name of the outlet being validated.- * @param {string|null} [params.blockName=null] - The name of the block, if resolved.- * @param {string} params.path - The hierarchical path to this entry.- * @param {Object|null} [params.entry=null] - The block entry object being validated.- * @param {Error|null} [params.callSiteError=null] - Error captured at the call site.- * @param {Array|null} [params.rootLayout=null] - The root layout array for error display.- * @returns {ValidationContext} A validation context object.- */-export function createValidationContext({- outletName,- blockName = null,- path,- entry = null,- callSiteError = null,- rootLayout = null,-}) {- return { outletName, blockName, path, entry, callSiteError, rootLayout };-}--/**- * Builds a hierarchical error path by joining path segments.- * Used to construct full paths for error messages (e.g., "layout[0].args.title").- *- * @param {string} basePath - The base path (e.g., "layout[0]").- * @param {string} segment - The segment to append (e.g., "args.title").- * @returns {string} Combined path with dot separator, or the non-empty path if one is missing.- *- * @example- * buildErrorPath("layout[0]", "args.title")- * // => "layout[0].args.title"- *- * buildErrorPath("", "args")- * // => "args"- */-export function buildErrorPath(basePath, segment) {- if (!basePath) {- return segment;- }- if (!segment) {- return basePath;- }- return `${basePath}.${segment}`;-}--/**- * Applies default values from block metadata to provided args.- *- * When a block is configured with args, this function merges the provided- * args with default values from the block's metadata schema. Default values- * are only applied when the arg is undefined in the provided args.- *- * @param {import("discourse/lib/blocks/-internals/registry/block").BlockClass} ComponentClass - The block component class.- * @param {Object} providedArgs - The args provided in the layout entry.- * @returns {Readonly<Object>} A new object with defaults applied for missing args.- *- * @example- * ```javascript- * // Block metadata: { args: { title: { default: "Hello" }, count: { default: 0 } } }- * applyArgDefaults(MyBlock, { title: "Custom" });- * // => { title: "Custom", count: 0 }- * ```- */-export function applyArgDefaults(ComponentClass, providedArgs) {- const schema = getBlockMetadata(ComponentClass)?.args;-- const result = { ...providedArgs };-- // apply default values- if (schema) {- for (const [argName, argDef] of Object.entries(schema)) {- if (result[argName] === undefined && argDef.default !== undefined) {- result[argName] = argDef.default;- }- }- }-- return Object.freeze(result);-}--/**- * Performs a shallow comparison of two args objects.- *- * Compares top-level values using strict equality (===). Does not perform- * deep comparison of nested objects. Used to determine if cached curried- * components can be reused.- *- * @param {Object|null|undefined} a - First args object.- * @param {Object|null|undefined} b - Second args object.- * @returns {boolean} True if the args are shallowly equal, false otherwise.- */-export function shallowArgsEqual(a, b) {- if (a === b) {- return true;- }- if (a == null || b == null) {- return false;- }- const keysA = Object.keys(a);- const keysB = Object.keys(b);- if (keysA.length !== keysB.length) {- return false;- }- return keysA.every((key) => a[key] === b[key]);-}--/**- * Retrieves a value from a nested object using dot-notation path.- *- * This utility safely navigates through nested object properties using a- * dot-separated path string. It handles null/undefined values gracefully- * at any level of the path.- *- * @param {Object} obj - The object to get the value from.- * @param {string} path - Dot-notation path (e.g., "user.trust_level").- * @returns {*} The value at the path, or undefined if not found or if any- * intermediate value is null/undefined.- *- * @example- * const user = { profile: { name: "Alice", settings: { theme: "dark" } } };- * getByPath(user, "profile.name"); // "Alice"- * getByPath(user, "profile.settings.theme"); // "dark"- * getByPath(user, "profile.missing"); // undefined- * getByPath(user, "profile.settings.missing.deep"); // undefined (safe)- */-export function getByPath(obj, path) {- if (!obj || !path) {- return undefined;- }-- const parts = path.split(".");- let current = obj;-- for (const part of parts) {- if (current === null || current === undefined) {- return undefined;- }- current = current[part];- }-- return current;-}diff --git a/frontend/discourse/app/lib/blocks/-internals/utils.ts b/frontend/discourse/app/lib/blocks/-internals/utils.tsnew file mode 100644index 00000000000..1e6dc1246d0--- /dev/null+++ b/frontend/discourse/app/lib/blocks/-internals/utils.ts@@ -0,0 +1,198 @@+/**+ * Utility functions for the block system.+ */+import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";+import type { BlockClass } from "discourse/lib/blocks/-internals/types";++/**+ * Parameters accepted by `createValidationContext()`.+ */+export interface CreateValidationContextParams {+ /** The name of the outlet being validated. */+ outletName: string;+ /** The name of the block, if resolved. */+ blockName?: string | null;+ /** The hierarchical path to this entry (e.g., "layout[0].children[1]"). */+ path: string;+ /** The block entry object being validated. */+ entry?: Record<string, unknown> | null;+ /** Error captured at the call site for stack traces. */+ callSiteError?: Error | null;+ /** The root layout array for error display. */+ rootLayout?: Array<Record<string, unknown>> | null;+}++/**+ * Validation context passed through the layout validation pipeline for error+ * reporting. Created via `createValidationContext()` to ensure consistent+ * structure across all validation functions; the members beyond the creation+ * params are added by validation code after initial context creation.+ */+export interface ValidationContext extends CreateValidationContextParams {+ /** Full path to the error (e.g., "layout[0].conditions.params.categoryId"). */+ errorPath?: string;+ /** Path within conditions (e.g., "params.categoryId"). */+ conditionsPath?: string;+ /** The conditions object for error display. */+ conditions?: unknown;+}++/**+ * Creates a validation context object for error reporting.+ * Centralizes context creation to ensure consistent structure across+ * all validation functions.+ */+export function createValidationContext({+ outletName,+ blockName = null,+ path,+ entry = null,+ callSiteError = null,+ rootLayout = null,+}: CreateValidationContextParams): ValidationContext {+ return { outletName, blockName, path, entry, callSiteError, rootLayout };+}++/**+ * Builds a hierarchical error path by joining path segments.+ * Used to construct full paths for error messages (e.g., "layout[0].args.title").+ *+ * @param basePath - The base path (e.g., "layout[0]").+ * @param segment - The segment to append (e.g., "args.title").+ * @returns Combined path with dot separator, or the non-empty path if one is missing.+ *+ * @example+ * ```+ * buildErrorPath("layout[0]", "args.title")+ * // => "layout[0].args.title"+ *+ * buildErrorPath("", "args")+ * // => "args"+ * ```+ */+export function buildErrorPath(basePath: string, segment: string): string {+ if (!basePath) {+ return segment;+ }+ if (!segment) {+ return basePath;+ }+ return `${basePath}.${segment}`;+}++/**+ * The `default` metadata for a single block argument, as read from the+ * `@block` decorator's args schema.+ */+export interface BlockArgSchemaEntry {+ default?: unknown;+}++/**+ * Applies default values from block metadata to provided args.+ *+ * When a block is configured with args, this function merges the provided+ * args with default values from the block's metadata schema. Default values+ * are only applied when the arg is undefined in the provided args.+ *+ * @param ComponentClass - The block component class.+ * @param providedArgs - The args provided in the layout entry.+ * @returns A new object with defaults applied for missing args.+ *+ * @example+ * ```javascript+ * // Block metadata: { args: { title: { default: "Hello" }, count: { default: 0 } } }+ * applyArgDefaults(MyBlock, { title: "Custom" });+ * // => { title: "Custom", count: 0 }+ * ```+ */+export function applyArgDefaults(+ ComponentClass: BlockClass,+ providedArgs: Record<string, unknown>+): Readonly<Record<string, unknown>> {+ const schema = getBlockMetadata(ComponentClass)?.args as+ | Record<string, BlockArgSchemaEntry>+ | null+ | undefined;++ const result: Record<string, unknown> = { ...providedArgs };++ // apply default values+ if (schema) {+ for (const [argName, argDef] of Object.entries(schema)) {+ if (result[argName] === undefined && argDef.default !== undefined) {+ result[argName] = argDef.default;+ }+ }+ }++ return Object.freeze(result);+}++/**+ * Performs a shallow comparison of two args objects.+ *+ * Compares top-level values using strict equality (===). Does not perform+ * deep comparison of nested objects. Used to determine if cached curried+ * components can be reused.+ *+ * @param a - First args object.+ * @param b - Second args object.+ * @returns True if the args are shallowly equal, false otherwise.+ */+export function shallowArgsEqual(+ a: Record<string, unknown> | null | undefined,+ b: Record<string, unknown> | null | undefined+): boolean {+ if (a === b) {+ return true;+ }+ if (a == null || b == null) {+ return false;+ }+ const keysA = Object.keys(a);+ const keysB = Object.keys(b);+ if (keysA.length !== keysB.length) {+ return false;+ }+ return keysA.every((key) => a[key] === b[key]);+}++/**+ * Retrieves a value from a nested object using dot-notation path.+ *+ * This utility safely navigates through nested object properties using a+ * dot-separated path string. It handles null/undefined values gracefully+ * at any level of the path.+ *+ * @param obj - The object to get the value from.+ * @param path - Dot-notation path (e.g., "user.trust_level").+ * @returns The value at the path, or undefined if not found or if any+ * intermediate value is null/undefined.+ *+ * @example+ * ```+ * const user = { profile: { name: "Alice", settings: { theme: "dark" } } };+ * getByPath(user, "profile.name"); // "Alice"+ * getByPath(user, "profile.settings.theme"); // "dark"+ * getByPath(user, "profile.missing"); // undefined+ * getByPath(user, "profile.settings.missing.deep"); // undefined (safe)+ * ```+ */+export function getByPath(obj: unknown, path: string): unknown {+ if (!obj || !path) {+ return undefined;+ }++ const parts = path.split(".");+ let current: unknown = obj;++ for (const part of parts) {+ if (current === null || current === undefined) {+ return undefined;+ }+ current = (current as Record<string, unknown>)[part];+ }++ return current;+}diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/args.js b/frontend/discourse/app/lib/blocks/-internals/validation/args.tssimilarity index 74%rename from frontend/discourse/app/lib/blocks/-internals/validation/args.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/args.tsindex 2255e184c3b..919c799553d 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/args.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/args.ts@@ -1,16 +1,13 @@-// @ts-check/*** Shared arg validation utilities.** This module provides generic validation functions for argument schemas* used by both blocks and conditions. Entity-specific validation logic* lives in separate modules:- * - block-args.js - block-specific validation- * - condition-args.js - condition-specific validation- *- * @module discourse/lib/blocks/-internals/validation/args+ * - block-args.ts - block-specific validation+ * - condition-args.ts - condition-specific validation*/-+import type { ArgSchema, ArgType } from "discourse/blocks/types";import {BlockError,raiseBlockError,@@ -21,11 +18,40 @@ import RestModel from "discourse/models/rest";/*** A validation error result containing the error message and the path* to the argument that failed validation.- *- * @typedef {Object} ValidationError- * @property {string} message - The formatted error message.- * @property {string} path - The path to the invalid argument (e.g., "test.name").*/+export interface ValidationError {+ /** The formatted error message. */+ message: string;+ /** The path to the invalid argument (e.g., "test.name"). */+ path: string;+}++/**+ * Error-message context shared by the arg-value validation functions below.+ */+export interface ArgErrorContext {+ /** Optional entity name for context (e.g., block name). */+ contextName?: string | null;+ /** The entity type for the prefix (e.g., "Block", "Condition"). */+ contextType?: string;+}++/**+ * The minimal owner surface `validateArgValue` needs to resolve a `"model:*"`+ * `instanceOf` reference to its registered class. Modeled as a narrow local+ * shape rather than the full `@ember/owner` `Owner` — whose `factoryFor()` is+ * generic over literal `"type:name"` strings — because the model name here is+ * only known at runtime.+ */+interface ModelRegistryOwner {+ factoryFor?: (fullName: string) => { class?: unknown } | undefined;+}++/** Options accepted by `validateArgValue` and `validateArgsAgainstSchema`. */+export interface ValidateArgValueOptions extends ArgErrorContext {+ /** Ember owner for registry lookups (used for `"model:*"` `instanceOf`). */+ owner?: ModelRegistryOwner | null;+}/*** Valid arg name pattern: must be a valid JavaScript identifier.@@ -39,7 +65,7 @@ export const VALID_ARG_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;* These are used internally by the block system and would conflict with* user-provided args. Names starting with underscore are also reserved.*/-export const RESERVED_ARG_NAMES = Object.freeze([+export const RESERVED_ARG_NAMES: readonly string[] = Object.freeze(["args","block","classNames",@@ -58,17 +84,17 @@ export const RESERVED_ARG_NAMES = Object.freeze([* Reserved names include explicit names in RESERVED_ARG_NAMES and* any name starting with underscore (private by convention).*- * @param {string} argName - The argument name to check- * @returns {boolean} True if the name is reserved+ * @param argName - The argument name to check+ * @returns True if the name is reserved*/-export function isReservedArgName(argName) {+export function isReservedArgName(argName: string): boolean {return RESERVED_ARG_NAMES.includes(argName) || argName.startsWith("_");}/*** Valid arg types for schema definitions.*/-export const VALID_ARG_TYPES = Object.freeze([+export const VALID_ARG_TYPES: readonly ArgType[] = Object.freeze(["string","number","boolean",@@ -77,15 +103,22 @@ export const VALID_ARG_TYPES = Object.freeze(["any",]);+/** Valid item types for array args. */+type ArgItemType = NonNullable<ArgSchema["itemType"]>;+/*** Valid item types for array args.*/-export const VALID_ITEM_TYPES = Object.freeze(["string", "number", "boolean"]);+export const VALID_ITEM_TYPES: readonly ArgItemType[] = Object.freeze([+ "string",+ "number",+ "boolean",+]);/*** Valid properties for arg schema definitions.*/-export const VALID_ARG_SCHEMA_PROPERTIES = Object.freeze([+export const VALID_ARG_SCHEMA_PROPERTIES: readonly string[] = Object.freeze(["type","required","default",@@ -103,6 +136,22 @@ export const VALID_ARG_SCHEMA_PROPERTIES = Object.freeze(["instanceOfName",]);+/**+ * A schema property validation rule, describing which arg types the+ * property is valid for and how to validate its value.+ */+interface SchemaPropertyRule {+ /** Arg types that can use this property. */+ allowedTypes: ArgType[];+ /** Validates the property's value. Omitted when checked elsewhere (e.g. via+ * `formatWithSuggestion` or recursive schema validation). */+ valueCheck?: (value: unknown) => boolean;+ /** Error message if `valueCheck` fails. */+ valueError?: string;+ /** Text to append for type restriction errors (e.g., "string or array"). */+ typeErrorSuffix: string;+}+/*** Schema property rules for declarative validation.* Each rule defines:@@ -111,7 +160,9 @@ export const VALID_ARG_SCHEMA_PROPERTIES = Object.freeze([* - valueError: error message if value check fails* - typeErrorSuffix: text to append for type restriction errors (e.g., "string or array")*/-export const SCHEMA_PROPERTY_RULES = Object.freeze({+export const SCHEMA_PROPERTY_RULES: Readonly<+ Record<string, SchemaPropertyRule>+> = Object.freeze({min: {allowedTypes: ["number"],valueCheck: (v) => typeof v === "number",@@ -132,13 +183,13 @@ export const SCHEMA_PROPERTY_RULES = Object.freeze({},minLength: {allowedTypes: ["string", "array"],- valueCheck: (v) => Number.isInteger(v) && v >= 0,+ valueCheck: (v) => Number.isInteger(v) && (v as number) >= 0,valueError: "Must be a non-negative integer.",typeErrorSuffix: "string or array",},maxLength: {allowedTypes: ["string", "array"],- valueCheck: (v) => Number.isInteger(v) && v >= 0,+ valueCheck: (v) => Number.isInteger(v) && (v as number) >= 0,valueError: "Must be a non-negative integer.",typeErrorSuffix: "string or array",},@@ -175,17 +226,28 @@ export const SCHEMA_PROPERTY_RULES = Object.freeze({},});+/** Options accepted by the schema-property validation helpers below. */+interface EntityErrorOptions {+ /** The entity name for error messages. */+ entityName?: string | null;+ /** The entity type for error messages. */+ entityType?: string;+}+/*** Validates a schema property against its rule.*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name.- * @param {string} prop - The property name.- * @param {Object} [options] - Optional configuration.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type for error messages.+ * @param argDef - The argument definition.+ * @param argName - The argument name.+ * @param prop - The property name.+ * @param options - Optional configuration.*/-export function validateSchemaProperty(argDef, argName, prop, options = {}) {+export function validateSchemaProperty(+ argDef: ArgSchema,+ argName: string,+ prop: keyof ArgSchema,+ options: EntityErrorOptions = {}+): void {const { entityName, entityType = "Block" } = options;const rule = SCHEMA_PROPERTY_RULES[prop];@@ -212,21 +274,22 @@ export function validateSchemaProperty(argDef, argName, prop, options = {}) {/*** Validates that at most one of the specified schema properties is defined (mutually exclusive).*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name for error messages.- * @param {string[]} properties - Array of property names that are mutually exclusive.- * @param {Object} [options] - Optional configuration.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type (e.g., "Block", "Condition").- * @param {string} [options.argLabel="arg"] - Label for the argument (e.g., "arg", "childArgs arg").- * @param {string} [options.reason] - Custom reason message.+ * @param argDef - The argument definition.+ * @param argName - The argument name for error messages.+ * @param properties - Array of property names that are mutually exclusive.+ * @param options - Optional configuration.*/export function validateMutuallyExclusive(- argDef,- argName,- properties,- options = {}-) {+ argDef: ArgSchema,+ argName: string,+ properties: readonly (keyof ArgSchema)[],+ options: EntityErrorOptions & {+ /** Label for the argument (e.g., "arg", "childArgs arg"). */+ argLabel?: string;+ /** Custom reason message. */+ reason?: string;+ } = {}+): void {const {entityName,entityType = "Block",@@ -249,24 +312,25 @@ export function validateMutuallyExclusive(}}+/** The names of `ArgSchema`'s numeric range-pair properties. */+type NumericRangeProperty = "min" | "max" | "minLength" | "maxLength";+/*** Validates a min/max range pair in the schema.*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name.- * @param {string} minProp - The min property name.- * @param {string} maxProp - The max property name.- * @param {Object} [options] - Optional configuration.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type for error messages.+ * @param argDef - The argument definition.+ * @param argName - The argument name.+ * @param minProp - The min property name.+ * @param maxProp - The max property name.+ * @param options - Optional configuration.*/export function validateRangePair(- argDef,- argName,- minProp,- maxProp,- options = {}-) {+ argDef: ArgSchema,+ argName: string,+ minProp: NumericRangeProperty,+ maxProp: NumericRangeProperty,+ options: EntityErrorOptions = {}+): void {const { entityName, entityType = "Block" } = options;if (@@ -280,17 +344,23 @@ export function validateRangePair(}}+/** Options accepted by `validateEnumArray`. */+interface ValidateEnumArrayOptions extends EntityErrorOptions {+ /** The enum array value to validate. */+ enumValue: unknown;+ /** Property name ("enum" or "itemEnum"). */+ propName: string;+ /** Expected type for values, or undefined to skip type check. */+ expectedType?: string;+ /** The argument name for error messages. */+ argName: string;+}+/*** Validates an enum-like array property (enum or itemEnum).* Checks that the value is a non-empty array and all items match the expected type.*- * @param {Object} options - Validation options.- * @param {*} options.enumValue - The enum array value to validate.- * @param {string} options.propName - Property name ("enum" or "itemEnum").- * @param {string|undefined} options.expectedType - Expected type for values, or undefined to skip type check.- * @param {string} options.argName - The argument name for error messages.- * @param {string} options.entityName - The entity name for error messages.- * @param {string} options.entityType - The entity type.+ * @param options - Validation options.*/function validateEnumArray({enumValue,@@ -299,7 +369,7 @@ function validateEnumArray({argName,entityName,entityType,-}) {+}: ValidateEnumArrayOptions): void {if (!Array.isArray(enumValue) || enumValue.length === 0) {raiseBlockError(`${entityType} "${entityName}": arg "${argName}" has invalid "${propName}" value. Must be an array with at least one element.`@@ -327,18 +397,24 @@ function validateEnumArray({* - "default" validation - blocks validate default values, conditions reject the property entirely* - "required + default contradiction" - only relevant for blocks*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name.- * @param {Object} [options] - Optional configuration.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type for error messages.+ * @param argDef - The argument definition.+ * @param argName - The argument name.+ * @param options - Optional configuration.*/-export function validateCommonSchemaProperties(argDef, argName, options = {}) {+export function validateCommonSchemaProperties(+ argDef: ArgSchema,+ argName: string,+ options: EntityErrorOptions = {}+): void {const { entityName, entityType = "Block" } = options;const context = { entityName, entityType };// Validate schema properties using declarative rules (type restrictions + value checks)- for (const prop of Object.keys(SCHEMA_PROPERTY_RULES)) {+ // `Object.keys()` widens to `string[]`; every key of `SCHEMA_PROPERTY_RULES`+ // is a valid `ArgSchema` property name.+ for (const prop of Object.keys(+ SCHEMA_PROPERTY_RULES+ ) as (keyof ArgSchema)[]) {validateSchemaProperty(argDef, argName, prop, context);}@@ -471,17 +547,23 @@ export function validateCommonSchemaProperties(argDef, argName, options = {}) {/* Arg Schema Entry Validation Helpers */+/** Options accepted by `validateArgName`. */+interface ValidateArgNameOptions extends EntityErrorOptions {+ /** Label for error messages (e.g., "childArgs arg"). */+ argLabel?: string;+}+/*** Validates an argument name format.*- * @param {string} argName - The argument name to validate.- * @param {Object} [options] - Optional configuration.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type for error messages.- * @param {string} [options.argLabel="arg"] - Label for error messages (e.g., "childArgs arg").- * @returns {boolean} True if valid, false if invalid (and error raised).+ * @param argName - The argument name to validate.+ * @param options - Optional configuration.+ * @returns True if valid, false if invalid (and error raised).*/-export function validateArgName(argName, options = {}) {+export function validateArgName(+ argName: string,+ options: ValidateArgNameOptions = {}+): boolean {const { entityName, entityType = "Block", argLabel = "arg" } = options;if (!VALID_ARG_NAME_PATTERN.test(argName)) {@@ -504,24 +586,34 @@ export function validateArgName(argName, options = {}) {return true;}+/** Options accepted by `validateArgSchemaEntry`. */+export interface ValidateArgSchemaEntryOptions extends EntityErrorOptions {+ /** List of valid schema properties. */+ validProperties: readonly string[];+ /** Map of property names to their specific error messages. Properties in+ * this map trigger a "disallowed" error instead of "unknown". */+ disallowedProperties?: Record<string, string>;+ /** If true, allow type: "any" (for conditions only). */+ allowAnyType?: boolean;+ /** Label for error messages (e.g., "childArgs arg"). */+ argLabel?: string;+}+/*** Validates a single arg schema entry (argDef).* Shared logic between block args, childArgs, and condition args validation.*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name.- * @param {Object} options - Configuration options.- * @param {string} [options.entityName] - The entity name for error messages.- * @param {string} [options.entityType="Block"] - The entity type for error messages.- * @param {readonly string[]} options.validProperties - List of valid schema properties.- * @param {Object<string, string>} [options.disallowedProperties={}] - Map of property names to their- * specific error messages. Properties in this map trigger a "disallowed" error instead of "unknown".- * @param {boolean} [options.allowAnyType=false] - If true, allow type: "any" (for conditions only).- * @param {string} [options.argLabel="arg"] - Label for error messages (e.g., "childArgs arg").- * @returns {boolean} True if validation should continue with caller-specific logic, false if+ * @param argDef - The argument definition.+ * @param argName - The argument name.+ * @param options - Configuration options.+ * @returns True if validation should continue with caller-specific logic, false if* validation should stop (e.g., missing type, type: "any" with allowAnyType).*/-export function validateArgSchemaEntry(argDef, argName, options) {+export function validateArgSchemaEntry(+ argDef: ArgSchema,+ argName: string,+ options: ValidateArgSchemaEntryOptions+): boolean {const {entityName,entityType = "Block",@@ -549,7 +641,7 @@ export function validateArgSchemaEntry(argDef, argName, options) {disallowedPropNames.includes(p));if (disallowed.length > 0) {- const prop = disallowed[0];+ const prop = disallowed[0]!;raiseBlockError(`${entityType} "${entityName}": ${argLabel} "${argName}" has disallowed property "${prop}". ` +disallowedProperties[prop]@@ -606,14 +698,16 @@ export function validateArgSchemaEntry(argDef, argName, options) {* - Schema validation (at decoration time): includes entity context* - Runtime validation (in renderBlocks): no context prefix*- * @param {string} argName - The argument name (used as the path).- * @param {string} message - The error message (without arg prefix).- * @param {Object} [options] - Optional configuration.- * @param {string|null} [options.contextName] - Optional entity name for context (e.g., block name).- * @param {string} [options.contextType] - The entity type for the prefix (e.g., "Block", "Condition").- * @returns {ValidationError} The validation error object with message and path.+ * @param argName - The argument name (used as the path).+ * @param message - The error message (without arg prefix).+ * @param options - Optional configuration.+ * @returns The validation error object with message and path.*/-function argValidationError(argName, message, options = {}) {+function argValidationError(+ argName: string,+ message: string,+ options: ArgErrorContext = {}+): ValidationError {const { contextName, contextType } = options;const formattedMessage = contextName? `${contextType} "${contextName}": arg "${argName}" ${message}`@@ -624,16 +718,18 @@ function argValidationError(argName, message, options = {}) {/*** Validates a single argument value against its schema definition.*- * @param {*} value - The argument value.- * @param {Object} argSchema - The schema definition for this arg.- * @param {string} argName - The argument name for error messages.- * @param {Object} [options] - Optional configuration.- * @param {string|null} [options.contextName] - Optional entity name for context.- * @param {string} [options.contextType] - The entity type for error prefix (e.g., "Block", "Condition").- * @param {Object} [options.owner] - Ember owner for registry lookups (used for "model:*" instanceOf).- * @returns {ValidationError|null} Validation error if validation fails, null otherwise.+ * @param value - The argument value.+ * @param argSchema - The schema definition for this arg.+ * @param argName - The argument name for error messages.+ * @param options - Optional configuration.+ * @returns Validation error if validation fails, null otherwise.*/-export function validateArgValue(value, argSchema, argName, options = {}) {+export function validateArgValue(+ value: unknown,+ argSchema: ArgSchema,+ argName: string,+ options: ValidateArgValueOptions = {}+): ValidationError | null {const { owner } = options;const {@@ -686,7 +782,7 @@ export function validateArgValue(value, argSchema, argName, options = {}) {);}if (enumValues !== undefined && !enumValues.includes(value)) {- const suggestion = formatWithSuggestion(value, enumValues);+ const suggestion = formatWithSuggestion(value, enumValues as string[]);return argValidationError(argName,`must be one of: ${enumValues.map((v) => `"${v}"`).join(", ")}. Got ${suggestion}.`,@@ -767,7 +863,7 @@ export function validateArgValue(value, argSchema, argName, options = {}) {}if (itemType) {for (let i = 0; i < value.length; i++) {- const item = value[i];+ const item: unknown = value[i];const itemError = validateArrayItemType(item,itemType,@@ -782,7 +878,7 @@ export function validateArgValue(value, argSchema, argName, options = {}) {}if (itemEnum !== undefined) {for (let i = 0; i < value.length; i++) {- const item = value[i];+ const item: unknown = value[i];if (!itemEnum.includes(item)) {const suggestion = formatWithSuggestion(String(item),@@ -853,7 +949,7 @@ export function validateArgValue(value, argSchema, argName, options = {}) {const klass = owner?.factoryFor?.(`model:${modelType}`)?.class;if (klass && klass !== RestModel) {// Specific model class exists, use instanceof- if (!(value instanceof klass)) {+ if (!(value instanceof (klass as abstract new () => object))) {return argValidationError(argName,`must be an instance of ${modelType} model.`,@@ -861,10 +957,14 @@ export function validateArgValue(value, argSchema, argName, options = {}) {);}} else {- // No specific class or RestModel fallback, check RestModel + __type+ // No specific class or RestModel fallback, check RestModel + __type.+ // `value instanceof RestModel` narrows `value` to `RestModel`,+ // which (like `LayoutEntry`) has no index signature — the+ // two-step cast reads its dynamic `__type` field regardless.if (!(value instanceof RestModel) ||- value["__type"] !== modelType+ (value as unknown as Record<string, unknown>)["__type"] !==+ modelType) {return argValidationError(argName,@@ -881,7 +981,7 @@ export function validateArgValue(value, argSchema, argName, options = {}) {for (const [propName, propDef] of Object.entries(argSchema.properties)) {- const propValue = value[propName];+ const propValue = (value as Record<string, unknown>)[propName];// Check required propertiesif (propDef.required && propValue === undefined) {@@ -917,22 +1017,20 @@ export function validateArgValue(value, argSchema, argName, options = {}) {/*** Validates an array item against the specified item type.*- * @param {*} item - The array item.- * @param {string} itemType - The expected type ("string", "number", "boolean").- * @param {string} argName - The argument name for error messages.- * @param {number} index - The array index for error messages.- * @param {Object} [options] - Optional configuration.- * @param {string|null} [options.contextName] - Optional entity name for context.- * @param {string} [options.contextType] - The entity type for error prefix (e.g., "Block", "Condition").- * @returns {ValidationError|null} Validation error if validation fails, null otherwise.+ * @param item - The array item.+ * @param itemType - The expected type ("string", "number", "boolean").+ * @param argName - The argument name for error messages.+ * @param index - The array index for error messages.+ * @param options - Optional configuration.+ * @returns Validation error if validation fails, null otherwise.*/export function validateArrayItemType(- item,- itemType,- argName,- index,- options = {}-) {+ item: unknown,+ itemType: ArgItemType,+ argName: string,+ index: number,+ options: ArgErrorContext = {}+): ValidationError | null {const indexedArgName = `${argName}[${index}]`;switch (itemType) {@@ -982,19 +1080,18 @@ export function validateArrayItemType(* The unknown args check is done FIRST so that typos like "nam" produce* "unknown arg 'nam' (did you mean 'name'?)" instead of "missing required arg 'name'".*- * @param {Object} providedArgs - The arguments to validate.- * @param {Object} schema - The schema to validate against.- * @param {string} pathPrefix - Prefix for error paths (e.g., "args" or "containerArgs").- * @param {Object} [options={}] - Optional configuration.- * @param {Object} [options.owner] - Ember owner for registry lookups (used for "model:*" instanceOf).- * @throws {BlockError} If validation fails.+ * @param providedArgs - The arguments to validate.+ * @param schema - The schema to validate against.+ * @param pathPrefix - Prefix for error paths (e.g., "args" or "containerArgs").+ * @param options - Optional configuration.+ * @throws BlockError if validation fails.*/export function validateArgsAgainstSchema(- providedArgs,- schema,- pathPrefix,- options = {}-) {+ providedArgs: Record<string, unknown>,+ schema: Record<string, ArgSchema>,+ pathPrefix: string,+ options: ValidateArgValueOptions = {}+): void {// 1. Check for unknown args FIRST (catches typos before missing required)const declaredArgs = Object.keys(schema);for (const argName of Object.keys(providedArgs)) {diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/block-args.js b/frontend/discourse/app/lib/blocks/-internals/validation/block-args.tssimilarity index 74%rename from frontend/discourse/app/lib/blocks/-internals/validation/block-args.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/block-args.tsindex 19f0ee3fb2c..abe97614ae2 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/block-args.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/block-args.ts@@ -1,54 +1,55 @@-// @ts-check/*** Block-specific arg validation.*- * This module adapts the shared arg validation utilities from args.js+ * This module adapts the shared arg validation utilities from args.ts* for use with blocks. Key differences from condition arg validation:* - Supports "default" values (conditions don't use defaults)* - Validates "required + default" contradiction* - Supports childArgs with "unique" property- *- * @module discourse/lib/blocks/-internals/validation/block-args*/-+import type {+ ArgSchema,+ ChildArgSchema,+ LayoutEntry,+} from "discourse/blocks/types";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";import {BlockError,raiseBlockError,} from "discourse/lib/blocks/-internals/error";+import type { BlockClass } from "discourse/lib/blocks/-internals/types";import {VALID_ARG_SCHEMA_PROPERTIES,validateArgName,validateArgsAgainstSchema,validateArgSchemaEntry,validateArgValue,+ type ValidateArgValueOptions,} from "discourse/lib/blocks/-internals/validation/args";/*** Valid properties for childArgs schema definitions.* Includes all standard arg properties plus "unique" for sibling uniqueness validation.*/-export const VALID_CHILD_ARG_SCHEMA_PROPERTIES = Object.freeze([- ...VALID_ARG_SCHEMA_PROPERTIES,- "unique",-]);+export const VALID_CHILD_ARG_SCHEMA_PROPERTIES: readonly string[] =+ Object.freeze([...VALID_ARG_SCHEMA_PROPERTIES, "unique"]);/*** Validates block-specific default value rules:* - "required + default" is contradictory (an arg with a default is never missing)* - Default value must match the arg's type schema*- * @param {Object} argDef - The argument definition.- * @param {string} argName - The argument name.- * @param {string} blockName - Block name for error messages.- * @param {string} [argLabel="arg"] - Label for error messages (e.g., "childArgs arg").+ * @param argDef - The argument definition.+ * @param argName - The argument name.+ * @param blockName - Block name for error messages.+ * @param argLabel - Label for error messages (e.g., "childArgs arg").*/function validateBlockDefaultValue(- argDef,- argName,- blockName,+ argDef: ArgSchema,+ argName: string,+ blockName: string,argLabel = "arg"-) {+): void {// Check for required + default contradiction (value-based, not presence-based)// An arg with required: false + default is valid, so we check required === trueif (argDef.required === true && argDef.default !== undefined) {@@ -72,14 +73,17 @@ function validateBlockDefaultValue(}/**- * Validates the arg schema definition passed to the @block decorator.+ * Validates the arg schema definition passed to the `@block` decorator.* Enforces strict schema format - unknown properties are not allowed.*- * @param {Object} argsSchema - The args schema object from decorator options.- * @param {string} blockName - Block name for error messages.- * @throws {Error} If schema is invalid.+ * @param argsSchema - The args schema object from decorator options.+ * @param blockName - Block name for error messages.+ * @throws Error if schema is invalid.*/-export function validateArgsSchema(argsSchema, blockName) {+export function validateArgsSchema(+ argsSchema: Record<string, ArgSchema> | null | undefined,+ blockName: string+): void {if (!argsSchema || typeof argsSchema !== "object") {return;}@@ -109,13 +113,16 @@ export function validateArgsSchema(argsSchema, blockName) {* Validates block arguments against the block's metadata arg schema.* Checks for required args and validates types.*- * @param {Object} entry - The block entry.- * @param {Object} blockClass - The resolved block class (must be a class, not a string reference).- * @param {Object} [options={}] - Optional configuration.- * @param {Object} [options.owner] - Ember owner for registry lookups (used for "model:*" instanceOf).- * @throws {BlockError} If args are invalid.+ * @param entry - The block entry.+ * @param blockClass - The resolved block class (must be a class, not a string reference).+ * @param options - Optional configuration.+ * @throws BlockError if args are invalid.*/-export function validateBlockArgs(entry, blockClass, options = {}) {+export function validateBlockArgs(+ entry: Pick<LayoutEntry, "args">,+ blockClass: BlockClass,+ options: ValidateArgValueOptions = {}+): void {const metadata = getBlockMetadata(blockClass);const providedArgs = entry.args || {};const hasProvidedArgs = Object.keys(providedArgs).length > 0;@@ -140,15 +147,18 @@ export function validateBlockArgs(entry, blockClass, options = {}) {}/**- * Validates the childArgs schema definition passed to the @block decorator.+ * Validates the childArgs schema definition passed to the `@block` decorator.* Similar to validateArgsSchema but supports the additional "unique" property* for enforcing uniqueness across sibling children.*- * @param {Object} childArgsSchema - The childArgs schema object from decorator options.- * @param {string} blockName - Block name for error messages.- * @throws {Error} If schema is invalid.+ * @param childArgsSchema - The childArgs schema object from decorator options.+ * @param blockName - Block name for error messages.+ * @throws Error if schema is invalid.*/-export function validateChildArgsSchema(childArgsSchema, blockName) {+export function validateChildArgsSchema(+ childArgsSchema: Record<string, ChildArgSchema> | null | undefined,+ blockName: string+): void {if (!childArgsSchema || typeof childArgsSchema !== "object") {return;}diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.js b/frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.tssimilarity index 76%rename from frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.tsindex a9c33a5f8a5..689143044c5 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/block-decorator.ts@@ -1,9 +1,10 @@/*** Block Decorator Validation*- * This module contains validation functions used by the @block decorator.+ * This module contains validation functions used by the `@block` decorator.* These validations run at decoration time (not render time) for fail-fast behavior.*/+import type { BlockOptions } from "discourse/blocks/types";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import {detectPatternConflicts,@@ -12,16 +13,15 @@ import {} from "discourse/lib/blocks/-internals/matching/outlet-matcher";import {parseBlockName,+ type ParsedBlockName,VALID_NAMESPACED_BLOCK_PATTERN,} from "discourse/lib/blocks/-internals/patterns";import { formatWithSuggestion } from "discourse/lib/string-similarity";/**- * Valid keys for the @block decorator options (block schema).- *- * @constant {ReadonlyArray<string>}+ * Valid keys for the `@block` decorator options (block schema).*/-export const VALID_BLOCK_OPTIONS = Object.freeze([+export const VALID_BLOCK_OPTIONS: readonly string[] = Object.freeze(["container","classNames","description",@@ -34,13 +34,16 @@ export const VALID_BLOCK_OPTIONS = Object.freeze([]);/**- * Validates the options object passed to the @block decorator.+ * Validates the options object passed to the `@block` decorator.* Checks for unknown keys and provides suggestions for typos.*- * @param {string} name - The block name (for error messages).- * @param {Object} options - The options object to validate.+ * @param name - The block name (for error messages).+ * @param options - The options object to validate.*/-export function validateBlockOptions(name, options) {+export function validateBlockOptions(+ name: string,+ options: BlockOptions+): void {if (options && typeof options === "object") {const unknownKeys = Object.keys(options).filter((key) => !VALID_BLOCK_OPTIONS.includes(key)@@ -61,10 +64,10 @@ export function validateBlockOptions(name, options) {* Validates and parses the block name.* Ensures the name follows the required format for core, plugin, or theme blocks.*- * @param {string} name - The block name to validate.- * @returns {import("discourse/lib/blocks/-internals/patterns").ParsedBlockName} Parsed name components.+ * @param name - The block name to validate.+ * @returns Parsed name components.*/-export function validateAndParseBlockName(name) {+export function validateAndParseBlockName(name: string): ParsedBlockName {if (!VALID_NAMESPACED_BLOCK_PATTERN.test(name)) {raiseBlockError(`Block name "${name}" is invalid. ` +@@ -86,15 +89,15 @@ export function validateAndParseBlockName(name) {* Validates outlet restriction patterns (allowedOutlets and deniedOutlets).* Checks for valid picomatch syntax and detects conflicts between patterns.*- * @param {string} name - The block name (for error messages).- * @param {string[]|null} allowedOutlets - Allowed outlet patterns.- * @param {string[]|null} deniedOutlets - Denied outlet patterns.+ * @param name - The block name (for error messages).+ * @param allowedOutlets - Allowed outlet patterns.+ * @param deniedOutlets - Denied outlet patterns.*/export function validateOutletRestrictions(- name,- allowedOutlets,- deniedOutlets-) {+ name: string,+ allowedOutlets: string[] | null | undefined,+ deniedOutlets: string[] | null | undefined+): void {// Validate outlet patterns are valid picomatch syntax (arrays of strings)validateOutletPatterns(allowedOutlets, name, "allowedOutlets");validateOutletPatterns(deniedOutlets, name, "deniedOutlets");diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/condition-args.js b/frontend/discourse/app/lib/blocks/-internals/validation/condition-args.tssimilarity index 69%rename from frontend/discourse/app/lib/blocks/-internals/validation/condition-args.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/condition-args.tsindex f238eafe33f..05d2497b1ad 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/condition-args.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/condition-args.ts@@ -1,16 +1,13 @@-// @ts-check/*** Condition-specific arg validation.*- * This module adapts the shared arg validation utilities from args.js+ * This module adapts the shared arg validation utilities from args.ts* for use with block conditions. Key differences from block arg validation:* - Error messages use "Condition" instead of "Block"* - The "default" property is not allowed (conditions don't use defaults)* - Type validation happens at registration time- *- * @module discourse/lib/blocks/-internals/validation/condition-args*/-+import type { ArgSchema } from "discourse/blocks/types";import { BlockError } from "discourse/lib/blocks/-internals/error";import {VALID_ARG_SCHEMA_PROPERTIES,@@ -25,30 +22,34 @@ import {* The "default" property is disallowed because conditions don't apply defaults -* they check explicitly for undefined values to determine what was provided.*/-const DISALLOWED_CONDITION_PROPERTIES = Object.freeze({- default: "Conditions do not support default values.",-});+const DISALLOWED_CONDITION_PROPERTIES: Readonly<Record<string, string>> =+ Object.freeze({+ default: "Conditions do not support default values.",+ });/*** Valid properties for condition arg schemas.* Includes all standard arg properties except those in DISALLOWED_CONDITION_PROPERTIES.*/-export const VALID_CONDITION_ARG_PROPERTIES = Object.freeze(+export const VALID_CONDITION_ARG_PROPERTIES: readonly string[] = Object.freeze(VALID_ARG_SCHEMA_PROPERTIES.filter((p) => !Object.hasOwn(DISALLOWED_CONDITION_PROPERTIES, p)));/**- * Validates the arg schema definition passed to the @blockCondition decorator.+ * Validates the arg schema definition passed to the `@blockCondition` decorator.* Enforces strict schema format - unknown properties are not allowed.* Called at decoration time to catch schema errors early.*- * @param {Object} argsSchema - The args schema object from decorator options.- * @param {string} conditionType - Condition type name for error messages.- * @throws {Error} If schema is invalid.+ * @param argsSchema - The args schema object from decorator options.+ * @param conditionType - Condition type name for error messages.+ * @throws Error if schema is invalid.*/-export function validateConditionArgsSchema(argsSchema, conditionType) {+export function validateConditionArgsSchema(+ argsSchema: Record<string, ArgSchema> | null | undefined,+ conditionType: string+): void {if (!argsSchema || typeof argsSchema !== "object") {return;}@@ -77,12 +78,16 @@ export function validateConditionArgsSchema(argsSchema, conditionType) {/*** Formats an error message for condition arg validation.*- * @param {string} argName - The argument name.- * @param {string} message - The error message.- * @param {string} conditionType - The condition type name.- * @returns {string} Formatted error message.+ * @param argName - The argument name.+ * @param message - The error message.+ * @param conditionType - The condition type name.+ * @returns Formatted error message.*/-function formatConditionArgError(argName, message, conditionType) {+function formatConditionArgError(+ argName: string,+ message: string,+ conditionType: string+): string {return `Condition "${conditionType}": arg "${argName}" ${message}`;}@@ -90,18 +95,18 @@ function formatConditionArgError(argName, message, conditionType) {* Validates provided arg values against the condition's schema.* Called at block registration time to catch invalid values early.*- * @param {Object} args - The arguments provided to the condition.- * @param {Object} argsSchema - The condition's args schema.- * @param {string} conditionType - The condition type for error messages.- * @param {string} path - The path to this condition in the block tree.- * @throws {BlockError} If validation fails.+ * @param args - The arguments provided to the condition.+ * @param argsSchema - The condition's args schema.+ * @param conditionType - The condition type for error messages.+ * @param path - The path to this condition in the block tree.+ * @throws BlockError if validation fails.*/export function validateConditionArgValues(- args,- argsSchema,- conditionType,- path-) {+ args: Record<string, unknown>,+ argsSchema: Record<string, ArgSchema>,+ conditionType: string,+ path: string+): void {for (const [argName, argDef] of Object.entries(argsSchema)) {const value = args[argName];diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/conditions.js b/frontend/discourse/app/lib/blocks/-internals/validation/conditions.tssimilarity index 66%rename from frontend/discourse/app/lib/blocks/-internals/validation/conditions.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/conditions.tsindex 419843c0798..88650a8ad2f 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/conditions.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/conditions.ts@@ -1,4 +1,4 @@-// @ts-check+import type { BlockCondition } from "discourse/blocks/conditions";import { BlockError } from "discourse/lib/blocks/-internals/error";import { validateConditionArgValues } from "discourse/lib/blocks/-internals/validation/condition-args";import {@@ -13,6 +13,14 @@ import { formatWithSuggestion } from "discourse/lib/string-similarity";*/const OUTLET_ARGS_SOURCE_PATTERN = /^@outletArgs\.[\w.]+$/;+/** The result of `validateConditionSource()`: error info, or `null` if valid. */+export interface ConditionSourceError {+ /** The error message. */+ message: string;+ /** The path to the invalid `source` parameter. */+ path?: string;+}+/*** Validates the `source` parameter based on the condition's `sourceType`.*@@ -20,11 +28,14 @@ const OUTLET_ARGS_SOURCE_PATTERN = /^@outletArgs\.[\w.]+$/;* - `sourceType: "outletArgs"`: Validates format is `@outletArgs.propertyPath`* - `sourceType: "object"`: Validates `source` is an object if provided*- * @param {"none"|"outletArgs"|"object"} sourceType - The condition's source type.- * @param {Object} args - The condition arguments from the layout entry.- * @returns {{ message: string, path?: string } | null} Error info or null if valid.+ * @param sourceType - The condition's source type.+ * @param args - The condition arguments from the layout entry.+ * @returns Error info or null if valid.*/-export function validateConditionSource(sourceType, args) {+export function validateConditionSource(+ sourceType: "none" | "outletArgs" | "object",+ args: Record<string, unknown>+): ConditionSourceError | null {const { source } = args;if (source === undefined) {@@ -70,17 +81,26 @@ export function validateConditionSource(sourceType, args) {* Validates that all provided args are recognized by a condition.* Suggests corrections for typos using fuzzy string matching.*- * @param {import("discourse/blocks/conditions").BlockCondition} instance - The condition instance.- * @param {string} type - The condition type name.- * @param {Object} args - The args provided to the condition.- * @param {string} path - The path to this condition in the block tree.- * @throws {BlockError} If an unrecognized arg key is found.+ * @param instance - The condition instance.+ * @param type - The condition type name.+ * @param args - The args provided to the condition.+ * @param path - The path to this condition in the block tree.+ * @throws BlockError if an unrecognized arg key is found.*/-export function validateConditionArgKeys(instance, type, args, path) {+export function validateConditionArgKeys(+ instance: BlockCondition,+ type: string,+ args: Record<string, unknown>,+ path: string+): void {+ // `instance.constructor` is typed as the generic `Function` by default; the+ // `@blockCondition` decorator always defines `validArgKeys` (and the other+ // statics read throughout this module) on every concrete `BlockCondition`+ // subclass, so this cast reads it safely.// validArgKeys already includes "source" when sourceType !== "none"// (computed by the @blockCondition decorator)- // @ts-ignore - Static property defined on condition classes- const validKeys = instance.constructor.validArgKeys;+ const validKeys = (instance.constructor as typeof BlockCondition)+ .validArgKeys;for (const key of Object.keys(args)) {if (!validKeys.includes(key)) {@@ -108,13 +128,17 @@ export function validateConditionArgKeys(instance, type, args, path) {* This is acceptable since condition keys come from theme/plugin layouts* where unusual characters are rare.*- * @param {Object|Array<Object>} conditionSpec - Condition spec(s) to validate.- * @param {Map<string, import("discourse/blocks/conditions").BlockCondition>} conditionTypes - Map of registered condition types.- * @param {string} [path=""] - The path to this condition relative to conditions root+ * @param conditionSpec - Condition spec(s) to validate.+ * @param conditionTypes - Map of registered condition types.+ * @param path - The path to this condition relative to conditions root* (e.g., "", "[0]", "any[1]", "params.categoryId").- * @throws {BlockError} If validation fails.+ * @throws BlockError if validation fails.*/-export function validateConditions(conditionSpec, conditionTypes, path = "") {+export function validateConditions(+ conditionSpec: unknown,+ conditionTypes: Map<string, BlockCondition>,+ path = ""+): void {if (!conditionSpec) {return;}@@ -128,30 +152,46 @@ export function validateConditions(conditionSpec, conditionTypes, path = "") {}// OR combinator- if (conditionSpec.any !== undefined) {- validateAnyCombinator(conditionSpec, conditionTypes, path);+ if ((conditionSpec as { any?: unknown[] }).any !== undefined) {+ validateAnyCombinator(+ conditionSpec as { any: unknown[] },+ conditionTypes,+ path+ );return;}// NOT combinator- if (conditionSpec.not !== undefined) {- validateNotCombinator(conditionSpec, conditionTypes, path);+ if ((conditionSpec as { not?: unknown }).not !== undefined) {+ validateNotCombinator(+ conditionSpec as { not: unknown },+ conditionTypes,+ path+ );return;}// Single condition with type- validateSingleCondition(conditionSpec, conditionTypes, path);+ validateSingleCondition(+ conditionSpec as { type?: string } & Record<string, unknown>,+ conditionTypes,+ path+ );}/*** Validates an "any" (OR) combinator.*- * @param {Object} conditionSpec - The condition spec containing "any".- * @param {Map<string, import("discourse/blocks/conditions").BlockCondition>} conditionTypes - Map of registered condition types.- * @param {string} path - The path to this condition in the block tree.- * @throws {BlockError} If validation fails.+ * @param conditionSpec - The condition spec containing "any".+ * @param conditionTypes - Map of registered condition types.+ * @param path - The path to this condition in the block tree.+ * @throws BlockError if validation fails.*/-function validateAnyCombinator(conditionSpec, conditionTypes, path) {+function validateAnyCombinator(+ conditionSpec: { any: unknown[] },+ conditionTypes: Map<string, BlockCondition>,+ path: string+): void {// Validate no extra keys alongside "any"const extraKeys = Object.keys(conditionSpec).filter((k) => k !== "any");if (extraKeys.length > 0) {@@ -180,12 +220,16 @@ function validateAnyCombinator(conditionSpec, conditionTypes, path) {/*** Validates a "not" (NOT) combinator.*- * @param {Object} conditionSpec - The condition spec containing "not".- * @param {Map<string, import("discourse/blocks/conditions").BlockCondition>} conditionTypes - Map of registered condition types.- * @param {string} path - The path to this condition in the block tree.- * @throws {BlockError} If validation fails.+ * @param conditionSpec - The condition spec containing "not".+ * @param conditionTypes - Map of registered condition types.+ * @param path - The path to this condition in the block tree.+ * @throws BlockError if validation fails.*/-function validateNotCombinator(conditionSpec, conditionTypes, path) {+function validateNotCombinator(+ conditionSpec: { not: unknown },+ conditionTypes: Map<string, BlockCondition>,+ path: string+): void {// Validate no extra keys alongside "not"const extraKeys = Object.keys(conditionSpec).filter((k) => k !== "not");if (extraKeys.length > 0) {@@ -219,12 +263,16 @@ function validateNotCombinator(conditionSpec, conditionTypes, path) {* 4. Validate source parameter (based on sourceType)* 5. Run custom validate function from decorator config*- * @param {Object} conditionSpec - The condition spec with a type property.- * @param {Map<string, import("discourse/blocks/conditions").BlockCondition>} conditionTypes - Map of registered condition types.- * @param {string} path - The path to this condition in the block tree.- * @throws {BlockError} If validation fails.+ * @param conditionSpec - The condition spec with a type property.+ * @param conditionTypes - Map of registered condition types.+ * @param path - The path to this condition in the block tree.+ * @throws BlockError if validation fails.*/-function validateSingleCondition(conditionSpec, conditionTypes, path) {+function validateSingleCondition(+ conditionSpec: { type?: string } & Record<string, unknown>,+ conditionTypes: Map<string, BlockCondition>,+ path: string+): void {const { type, ...args } = conditionSpec;if (!type) {@@ -245,12 +293,11 @@ function validateSingleCondition(conditionSpec, conditionTypes, path) {);}- // @ts-ignore - Static properties defined on condition classes- const argsSchema = conditionInstance.constructor.argsSchema;- // @ts-ignore - Static properties defined on condition classes- const constraints = conditionInstance.constructor.constraints;- // @ts-ignore - Static properties defined on condition classes- const validateFn = conditionInstance.constructor.validateFn;+ // `conditionInstance.constructor` is typed as the generic `Function` by+ // default; the `@blockCondition` decorator always defines these statics on+ // every concrete `BlockCondition` subclass, so this cast reads them safely.+ const ConditionClass = conditionInstance.constructor as typeof BlockCondition;+ const { argsSchema, constraints, validateFn, sourceType } = ConditionClass;// 1. Validate unknown args (catches typos like "nam" instead of "name")// This is checked FIRST so typos produce helpful suggestions rather than@@ -278,8 +325,6 @@ function validateSingleCondition(conditionSpec, conditionTypes, path) {}// 4. Validate source parameter (based on sourceType)- // @ts-ignore - Static property defined on condition classes- const sourceType = conditionInstance.constructor.sourceType;const sourceError = validateConditionSource(sourceType, args);if (sourceError) {throw new BlockError(sourceError.message, {@@ -290,7 +335,7 @@ function validateSingleCondition(conditionSpec, conditionTypes, path) {// 5. Run custom validate function from decorator configif (validateFn) {const customErrors = runCustomValidation(validateFn, args);- if (customErrors?.length > 0) {+ if (customErrors && customErrors.length > 0) {throw new BlockError(`Condition "${type}": ${customErrors.join("; ")}`, {path,});diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/constraints.js b/frontend/discourse/app/lib/blocks/-internals/validation/constraints.tssimilarity index 71%rename from frontend/discourse/app/lib/blocks/-internals/validation/constraints.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/constraints.tsindex 3b619ea1cbc..f115e47a42a 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/constraints.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/constraints.ts@@ -1,4 +1,3 @@-// @ts-check/*** Cross-arg constraint validation for blocks.*@@ -11,17 +10,19 @@* - allOrNone: Either all or none of the specified args must be provided* - atMostOne: At most one of the specified args may be provided (0 or 1)* - requires: If a dependent arg is provided, its required arg must also be provided- *- * @module discourse/lib/blocks/-internals/validation/constraints*/-+import type {+ ArgSchema,+ BlockConstraints,+ BlockValidateFn,+} from "discourse/blocks/types";import { raiseBlockError } from "discourse/lib/blocks/-internals/error";import { formatWithSuggestion } from "discourse/lib/string-similarity";/*** Valid constraint types for cross-arg validation.*/-export const VALID_CONSTRAINT_TYPES = Object.freeze([+export const VALID_CONSTRAINT_TYPES: readonly string[] = Object.freeze(["atLeastOne","exactlyOne","allOrNone",@@ -32,10 +33,10 @@ export const VALID_CONSTRAINT_TYPES = Object.freeze([/*** Formats an array of arg names as a quoted, comma-separated list.*- * @param {string[]} argNames - Array of argument names.- * @returns {string} Formatted string like `"a", "b", "c"`.+ * @param argNames - Array of argument names.+ * @returns Formatted string like `"a", "b", "c"`.*/-function formatArgList(argNames) {+function formatArgList(argNames: string[]): string {return argNames.map((n) => `"${n}"`).join(", ");}@@ -48,19 +49,23 @@ function formatArgList(argNames) {* - Incompatible constraints (exactlyOne + allOrNone, exactlyOne + atLeastOne)* - Vacuous constraints (constraints rendered always true/false by defaults)*- * @param {Object} constraints - The constraints object from decorator options.- * @param {Object} argsSchema - The args schema object from decorator options.- * @param {string} blockName - Block name for error messages.+ * @param constraints - The constraints object from decorator options.+ * @param argsSchema - The args schema object from decorator options.+ * @param blockName - Block name for error messages.*/-export function validateConstraintsSchema(constraints, argsSchema, blockName) {+export function validateConstraintsSchema(+ constraints: BlockConstraints | null | undefined,+ argsSchema: Record<string, ArgSchema> | null | undefined,+ blockName: string+): void {if (!constraints || typeof constraints !== "object") {return;}const declaredArgs = argsSchema ? Object.keys(argsSchema) : [];- const constraintsByArgs = new Map();+ const constraintsByArgs = new Map<string, string[]>();- for (const [constraintType, argNames] of Object.entries(constraints)) {+ for (const [constraintType, argNamesValue] of Object.entries(constraints)) {// Check for unknown constraint types with fuzzy matchingif (!VALID_CONSTRAINT_TYPES.includes(constraintType)) {const suggestion = formatWithSuggestion(@@ -77,9 +82,9 @@ export function validateConstraintsSchema(constraints, argsSchema, blockName) {// Handle requires constraint (object format instead of array)if (constraintType === "requires") {if (- typeof argNames !== "object" ||- Array.isArray(argNames) ||- argNames == null+ typeof argNamesValue !== "object" ||+ Array.isArray(argNamesValue) ||+ argNamesValue == null) {raiseBlockError(`Block "${blockName}": constraint "requires" must be an object mapping dependent args to required args.`@@ -87,7 +92,7 @@ export function validateConstraintsSchema(constraints, argsSchema, blockName) {continue;}- for (const [dependentArg, requiredArg] of Object.entries(argNames)) {+ for (const [dependentArg, requiredArg] of Object.entries(argNamesValue)) {// Validate dependent arg existsif (!declaredArgs.includes(dependentArg)) {const suggestion = formatWithSuggestion(dependentArg, declaredArgs);@@ -114,13 +119,18 @@ export function validateConstraintsSchema(constraints, argsSchema, blockName) {}// Constraint value must be an array- if (!Array.isArray(argNames)) {+ if (!Array.isArray(argNamesValue)) {raiseBlockError(`Block "${blockName}": constraint "${constraintType}" must be an array of arg names.`);continue;}+ // The schema authoring contract is an array of arg-name strings; the+ // per-element check just below is defensive against non-TypeScript+ // (plugin/theme) callers passing a malformed array at runtime.+ const argNames = argNamesValue as string[];+// Constraint array must have at least 2 elementsif (argNames.length < 2) {raiseBlockError(@@ -151,7 +161,8 @@ export function validateConstraintsSchema(constraints, argsSchema, blockName) {if (!constraintsByArgs.has(sortedArgs)) {constraintsByArgs.set(sortedArgs, []);}- constraintsByArgs.get(sortedArgs).push(constraintType);+ // Guaranteed to be set by the `.has()`/`.set()` pair above.+ constraintsByArgs.get(sortedArgs)!.push(constraintType);// Check for vacuous constraints (always true or always false due to defaults)if (argsSchema) {@@ -170,17 +181,17 @@ export function validateConstraintsSchema(constraints, argsSchema, blockName) {/*** Checks if a constraint is vacuous (always true or always false) due to default values.*- * @param {string} constraintType - The constraint type.- * @param {string[]} argNames - The arg names in the constraint.- * @param {Object} argsSchema - The args schema.- * @param {string} blockName - Block name for error messages.+ * @param constraintType - The constraint type.+ * @param argNames - The arg names in the constraint.+ * @param argsSchema - The args schema.+ * @param blockName - Block name for error messages.*/function checkVacuousConstraint(- constraintType,- argNames,- argsSchema,- blockName-) {+ constraintType: string,+ argNames: string[],+ argsSchema: Record<string, ArgSchema>,+ blockName: string+): void {const argsWithDefaults = argNames.filter((name) => argsSchema[name]?.default !== undefined);@@ -240,11 +251,15 @@ function checkVacuousConstraint(/*** Checks for incompatible constraint types on the same arg set.*- * @param {string[]} constraintTypes - The constraint types applied to the same args.- * @param {string} argSet - The sorted arg names (for error message).- * @param {string} blockName - Block name for error messages.+ * @param constraintTypes - The constraint types applied to the same args.+ * @param argSet - The sorted arg names (for error message).+ * @param blockName - Block name for error messages.*/-function checkIncompatibleConstraints(constraintTypes, argSet, blockName) {+function checkIncompatibleConstraints(+ constraintTypes: string[],+ argSet: string,+ blockName: string+): void {const argList = argSet.split(",").map((n) => `"${n}"`)@@ -299,26 +314,35 @@ function checkIncompatibleConstraints(constraintTypes, argSet, blockName) {* Validates constraints against the provided args at runtime.* Called after defaults are applied.*- * @param {Object} constraints - The constraints from block metadata.- * @param {Object} args - The resolved args (with defaults applied).- * @param {string} blockName - Block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param constraints - The constraints from block metadata.+ * @param args - The resolved args (with defaults applied).+ * @param blockName - Block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-export function validateConstraints(constraints, args, blockName) {+export function validateConstraints(+ constraints: BlockConstraints | null | undefined,+ args: Record<string, unknown>,+ blockName: string+): string | null {if (!constraints || typeof constraints !== "object") {return null;}- for (const [constraintType, argNames] of Object.entries(constraints)) {- let error = null;+ for (const [constraintType, argNamesValue] of Object.entries(constraints)) {+ let error: string | null = null;// Handle requires constraint (object format)if (constraintType === "requires") {- if (typeof argNames === "object" && !Array.isArray(argNames)) {- error = validateRequires(argNames, args, blockName);+ if (typeof argNamesValue === "object" && !Array.isArray(argNamesValue)) {+ error = validateRequires(+ argNamesValue as Record<string, string>,+ args,+ blockName+ );}- } else if (Array.isArray(argNames)) {+ } else if (Array.isArray(argNamesValue)) {// Handle array-based constraints+ const argNames = argNamesValue as string[];switch (constraintType) {case "atLeastOne":error = validateAtLeastOne(argNames, args, blockName);@@ -346,12 +370,16 @@ export function validateConstraints(constraints, args, blockName) {/*** Validates that at least one of the specified args is provided.*- * @param {string[]} argNames - The arg names to check.- * @param {Object} args - The resolved args.- * @param {string} blockName - The block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param argNames - The arg names to check.+ * @param args - The resolved args.+ * @param blockName - The block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-function validateAtLeastOne(argNames, args, blockName) {+function validateAtLeastOne(+ argNames: string[],+ args: Record<string, unknown>,+ blockName: string+): string | null {const providedCount = argNames.filter((name) => args[name] !== undefined).length;@@ -367,12 +395,16 @@ function validateAtLeastOne(argNames, args, blockName) {/*** Validates that exactly one of the specified args is provided.*- * @param {string[]} argNames - The arg names to check.- * @param {Object} args - The resolved args.- * @param {string} blockName - The block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param argNames - The arg names to check.+ * @param args - The resolved args.+ * @param blockName - The block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-function validateExactlyOne(argNames, args, blockName) {+function validateExactlyOne(+ argNames: string[],+ args: Record<string, unknown>,+ blockName: string+): string | null {const providedArgs = argNames.filter((name) => args[name] !== undefined);const argList = formatArgList(argNames);@@ -391,12 +423,16 @@ function validateExactlyOne(argNames, args, blockName) {/*** Validates that either all or none of the specified args are provided.*- * @param {string[]} argNames - The arg names to check.- * @param {Object} args - The resolved args.- * @param {string} blockName - The block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param argNames - The arg names to check.+ * @param args - The resolved args.+ * @param blockName - The block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-function validateAllOrNone(argNames, args, blockName) {+function validateAllOrNone(+ argNames: string[],+ args: Record<string, unknown>,+ blockName: string+): string | null {const providedCount = argNames.filter((name) => args[name] !== undefined).length;@@ -420,12 +456,16 @@ function validateAllOrNone(argNames, args, blockName) {/*** Validates that at most one of the specified args is provided (0 or 1).*- * @param {string[]} argNames - The arg names to check.- * @param {Object} args - The resolved args.- * @param {string} blockName - The block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param argNames - The arg names to check.+ * @param args - The resolved args.+ * @param blockName - The block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-function validateAtMostOne(argNames, args, blockName) {+function validateAtMostOne(+ argNames: string[],+ args: Record<string, unknown>,+ blockName: string+): string | null {const providedArgs = argNames.filter((name) => args[name] !== undefined);if (providedArgs.length > 1) {@@ -440,12 +480,16 @@ function validateAtMostOne(argNames, args, blockName) {/*** Validates that if a dependent arg is provided, its required arg must also be provided.*- * @param {Object} requiresMap - Object mapping dependent args to required args.- * @param {Object} args - The resolved args.- * @param {string} blockName - The block name for error messages.- * @returns {string|null} Error message if validation fails, null otherwise.+ * @param requiresMap - Object mapping dependent args to required args.+ * @param args - The resolved args.+ * @param blockName - The block name for error messages.+ * @returns Error message if validation fails, null otherwise.*/-function validateRequires(requiresMap, args, blockName) {+function validateRequires(+ requiresMap: Record<string, string>,+ args: Record<string, unknown>,+ blockName: string+): string | null {for (const [dependentArg, requiredArg] of Object.entries(requiresMap)) {if (args[dependentArg] !== undefined && args[requiredArg] === undefined) {return `Block "${blockName}": "${dependentArg}" requires "${requiredArg}" to be specified.`;@@ -457,11 +501,14 @@ function validateRequires(requiresMap, args, blockName) {/*** Runs a custom validation function if provided.*- * @param {Function} validateFn - The custom validate function.- * @param {Object} args - The resolved args (with defaults applied).- * @returns {string[]|null} Array of error messages if validation fails, null otherwise.+ * @param validateFn - The custom validate function.+ * @param args - The resolved args (with defaults applied).+ * @returns Array of error messages if validation fails, null otherwise.*/-export function runCustomValidation(validateFn, args) {+export function runCustomValidation(+ validateFn: BlockValidateFn | null | undefined,+ args: Record<string, unknown>+): string[] | null {if (typeof validateFn !== "function") {return null;}@@ -478,8 +525,13 @@ export function runCustomValidation(validateFn, args) {}if (Array.isArray(result)) {+ // `Array.isArray()` narrows to the (necessarily untyped) built-in `any[]`;+ // re-declare it as `unknown[]` so nothing downstream carries an `any`.+ const resultArray = result as unknown[];// Filter out non-string values and empty strings- const errors = result.filter((e) => typeof e === "string" && e.length > 0);+ const errors = resultArray.filter(+ (e): e is string => typeof e === "string" && e.length > 0+ );return errors.length > 0 ? errors : null;}diff --git a/frontend/discourse/app/lib/blocks/-internals/validation/layout.js b/frontend/discourse/app/lib/blocks/-internals/validation/layout.tssimilarity index 61%rename from frontend/discourse/app/lib/blocks/-internals/validation/layout.jsrename to frontend/discourse/app/lib/blocks/-internals/validation/layout.tsindex 978fcb586e7..51dbee21881 100644--- a/frontend/discourse/app/lib/blocks/-internals/validation/layout.js+++ b/frontend/discourse/app/lib/blocks/-internals/validation/layout.ts@@ -1,4 +1,3 @@-// @ts-check/*** Outlet layout validation utilities.*@@ -9,12 +8,14 @@* Terminology:* - **Block Entry**: An object in a layout that specifies how to use a block.* - **Outlet Layout**: An array of block entries defining which blocks appear in an outlet.- *- * @module discourse/lib/blocks/-internals/validation/layout*/-import { DEBUG } from "@glimmer/env";import { getOwner } from "@ember/owner";+import type {+ BlockMetadata,+ ChildArgSchema,+ LayoutEntry,+} from "discourse/blocks/types";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";import {BlockError,@@ -36,10 +37,12 @@ import {getAllOutlets,isValidOutlet,} from "discourse/lib/blocks/-internals/registry/outlet";+import type { BlockClass } from "discourse/lib/blocks/-internals/types";import {applyArgDefaults,buildErrorPath,createValidationContext,+ type ValidationContext,} from "discourse/lib/blocks/-internals/utils";import { validateArgsAgainstSchema } from "discourse/lib/blocks/-internals/validation/args";import { validateBlockArgs } from "discourse/lib/blocks/-internals/validation/block-args";@@ -48,24 +51,52 @@ import {validateConstraints,} from "discourse/lib/blocks/-internals/validation/constraints";import { formatWithSuggestion } from "discourse/lib/string-similarity";+import type Blocks from "discourse/services/blocks";++/**+ * Widens a `LayoutEntry` to the generic record shape `ValidationContext`+ * expects for error-message rendering. `LayoutEntry` has no index signature,+ * so it isn't directly assignable to `Record<string, unknown>` even though+ * every field it declares is a valid record entry — hence the two-step cast.+ */+function asContextEntry(+ entry: LayoutEntry | null | undefined+): Record<string, unknown> | null {+ return entry ? (entry as unknown as Record<string, unknown>) : null;+}++/** Same widening as {@link asContextEntry}, for a full layout array. */+function asContextLayout(+ layout: LayoutEntry[] | null | undefined+): Array<Record<string, unknown>> | null {+ return layout ? (layout as unknown as Array<Record<string, unknown>>) : null;+}/*** Wraps a validation function call with BlockError handling.* Catches errors with a `path` property and re-raises with full context.*- * @param {Function} validationFn - The validation function to call.- * @param {string} errorPrefix - Prefix for the error message.- * @param {Object} context - Error context including outletName, blockName, path, etc.+ * @param validationFn - The validation function to call.+ * @param errorPrefix - Prefix for the error message.+ * @param context - Error context including outletName, blockName, path, etc.*/-function wrapValidationError(validationFn, errorPrefix, context) {+function wrapValidationError(+ validationFn: () => void,+ errorPrefix: string,+ context: ValidationContext+): void {try {validationFn();- } catch (error) {+ } catch (error: unknown) {+ // Errors raised by the schema/entry validators below are always+ // `BlockError`-shaped (or a plain `Error` with a `path` property attached+ // manually), never an arbitrary throw.+ const err = error as Error & { path?: string };// Errors with path property need context enrichment- if (error.path) {- raiseBlockError(`${errorPrefix}: ${error.message}`, {+ if (err.path) {+ raiseBlockError(`${errorPrefix}: ${err.message}`, {...context,- errorPath: buildErrorPath(context.path, error.path),+ errorPath: buildErrorPath(context.path, err.path),});}throw error;@@ -76,21 +107,29 @@ function wrapValidationError(validationFn, errorPrefix, context) {* Validates that a block is permitted in the specified outlet.* Checks allowedOutlets and deniedOutlets metadata if present.*- * @param {Object} metadata - Block metadata with outlet restrictions.- * @param {string} outletName - The outlet being validated.- * @param {string} blockName - The block name for error messages.- * @param {Object} context - Error context for raiseBlockError.- * @returns {boolean} True if validation passed, false if error was raised.+ * @param metadata - Block metadata with outlet restrictions.+ * @param outletName - The outlet being validated.+ * @param blockName - The block name for error messages.+ * @param context - Error context for raiseBlockError.+ * @returns True if validation passed, false if error was raised.*/-function validateOutletPermission(metadata, outletName, blockName, context) {+function validateOutletPermission(+ metadata: BlockMetadata | null | undefined,+ outletName: string,+ blockName: string,+ context: ValidationContext+): boolean {if (!metadata?.allowedOutlets && !metadata?.deniedOutlets) {return true;}const permission = isBlockPermittedInOutlet(outletName,- metadata.allowedOutlets,- metadata.deniedOutlets+ // `BlockMetadata`'s outlet lists are `readonly` (the decorator freezes+ // them); `isBlockPermittedInOutlet` only reads them, so it's safe to+ // widen back to a mutable array here.+ metadata.allowedOutlets as string[] | null,+ metadata.deniedOutlets as string[] | null);if (!permission.permitted) {@@ -107,21 +146,21 @@ function validateOutletPermission(metadata, outletName, blockName, context) {* Validates container/children relationship.* Containers must have children, non-containers cannot have children.*- * @param {Object} entry - The block entry.- * @param {boolean} isContainer - Whether the block is a container.- * @param {string} blockName - The block name for error messages.- * @param {string} outletName - The outlet name for error messages.- * @param {Object} context - Error context for raiseBlockError.- * @returns {boolean} True if validation passed, false if error was raised.+ * @param entry - The block entry.+ * @param isContainer - Whether the block is a container.+ * @param blockName - The block name for error messages.+ * @param outletName - The outlet name for error messages.+ * @param context - Error context for raiseBlockError.+ * @returns True if validation passed, false if error was raised.*/function validateContainerChildren(- entry,- isContainer,- blockName,- outletName,- context-) {- const hasChildren = entry.children?.length > 0;+ entry: LayoutEntry,+ isContainer: boolean,+ blockName: string,+ outletName: string,+ context: ValidationContext+): boolean {+ const hasChildren = !!entry.children?.length;if (hasChildren && !isContainer) {raiseBlockError(@@ -145,19 +184,19 @@ function validateContainerChildren(* Validates block constraints and custom validation functions.* Applies arg defaults before validation.*- * @param {Object} metadata - Block metadata with constraints/validate.- * @param {Object} resolvedBlock - The resolved block class.- * @param {Object} entry - The block entry.- * @param {string} blockName - The block name for error messages.- * @param {Object} context - Error context for raiseBlockError.+ * @param metadata - Block metadata with constraints/validate.+ * @param resolvedBlock - The resolved block class.+ * @param entry - The block entry.+ * @param blockName - The block name for error messages.+ * @param context - Error context for raiseBlockError.*/function validateBlockConstraints(- metadata,- resolvedBlock,- entry,- blockName,- context-) {+ metadata: BlockMetadata | null | undefined,+ resolvedBlock: BlockClass,+ entry: LayoutEntry,+ blockName: string,+ context: ValidationContext+): void {if (!metadata?.constraints && !metadata?.validate) {return;}@@ -185,7 +224,7 @@ function validateBlockConstraints(metadata.validate,argsWithDefaults);- if (customErrors?.length > 0) {+ if (customErrors && customErrors.length > 0) {const errorMessage =customErrors.length === 1? customErrors[0]@@ -202,17 +241,17 @@ function validateBlockConstraints(* Validates a child block's containerArgs against the parent container's childArgs schema.* Reuses the shared validateArgsAgainstSchema function for core validation logic.*- * @param {Object} childEntry - The child block entry.- * @param {Object} parentChildArgsSchema - The parent's childArgs schema.- * @param {string} parentName - Parent block name for error messages.- * @param {Object} context - Error context.+ * @param childEntry - The child block entry.+ * @param parentChildArgsSchema - The parent's childArgs schema.+ * @param parentName - Parent block name for error messages.+ * @param context - Error context.*/function validateContainerArgs(- childEntry,- parentChildArgsSchema,- parentName,- context-) {+ childEntry: LayoutEntry,+ parentChildArgsSchema: Record<string, ChildArgSchema>,+ parentName: string | null,+ context: ValidationContext+): void {const providedArgs = childEntry.containerArgs || {};try {@@ -221,13 +260,14 @@ function validateContainerArgs(parentChildArgsSchema,"containerArgs");- } catch (error) {+ } catch (error: unknown) {// Enhance error message with parent context+ const err = error as BlockError;raiseBlockError(- `Child block at ${context.path} ${error.message} (required by parent "${parentName}").`,+ `Child block at ${context.path} ${err.message} (required by parent "${parentName}").`,{...context,- errorPath: buildErrorPath(context.path, error.path),+ errorPath: buildErrorPath(context.path, err.path ?? ""),});}@@ -236,26 +276,26 @@ function validateContainerArgs(/*** Validates uniqueness constraints for containerArgs across all sibling children.*- * @param {Array<Object>} childEntries - Array of child block entries.- * @param {Object} childArgsSchema - The parent's childArgs schema.- * @param {string} parentName - Parent block name for error messages.- * @param {string} parentPath - Path to parent for error context.- * @param {Object} context - Error context.+ * @param childEntries - Array of child block entries.+ * @param childArgsSchema - The parent's childArgs schema.+ * @param parentName - Parent block name for error messages.+ * @param parentPath - Path to parent for error context.+ * @param context - Error context.*/function validateContainerArgsUniqueness(- childEntries,- childArgsSchema,- parentName,- parentPath,- context-) {+ childEntries: LayoutEntry[],+ childArgsSchema: Record<string, ChildArgSchema>,+ parentName: string | null,+ parentPath: string,+ context: ValidationContext+): void {// Find args with unique: trueconst uniqueArgs = Object.entries(childArgsSchema).filter(([, schema]) => schema.unique).map(([name]) => name);for (const argName of uniqueArgs) {- const seenValues = new Map(); // value -> index of first occurrence+ const seenValues = new Map<unknown, number>(); // value -> index of first occurrencefor (let i = 0; i < childEntries.length; i++) {const childEntry = childEntries[i];@@ -290,10 +330,10 @@ function validateContainerArgsUniqueness(* IDs must start with a lowercase letter and contain only lowercase letters,* numbers, and hyphens (same format as block names).*- * @param {Object} entry - The block entry.- * @throws {BlockError} If the id format is invalid.+ * @param entry - The block entry.+ * @throws BlockError if the id format is invalid.*/-export function validateEntryIdFormat(entry) {+export function validateEntryIdFormat(entry: LayoutEntry): void {if (!entry.id) {return;}@@ -311,11 +351,15 @@ export function validateEntryIdFormat(entry) {* Validates that containerArgs is not provided when parent has no childArgs.* Follows the pattern: error in dev/test, warn in production.*- * @param {Object} entry - The block entry.- * @param {Object} parentChildArgsSchema - The parent's childArgs schema (null if none).- * @param {Object} context - Error context.+ * @param entry - The block entry.+ * @param parentChildArgsSchema - The parent's childArgs schema (null if none).+ * @param context - Error context.*/-function validateOrphanContainerArgs(entry, parentChildArgsSchema, context) {+function validateOrphanContainerArgs(+ entry: LayoutEntry,+ parentChildArgsSchema: Record<string, ChildArgSchema> | null,+ context: ValidationContext+): void {if (entry.containerArgs && !parentChildArgsSchema) {const message =`Block at ${context.path} has "containerArgs" but parent container does not declare "childArgs". ` +@@ -333,61 +377,82 @@ function validateOrphanContainerArgs(entry, parentChildArgsSchema, context) {/*** Validates block conditions and raises errors with proper context.*- * @param {Object} blocksService - The blocks service with validate method.- * @param {Object} entry - The block entry containing conditions.- * @param {string} outletName - The outlet name for error messages.- * @param {string} blockName - The block name for error messages.- * @param {string} path - The path in the layout tree for error messages.- * @param {Error | null} [callSiteError] - Error object capturing where renderBlocks() was called.- * @param {Array<Object>} [rootLayout] - The root blocks array for error context display.+ * @param blocksService - The blocks service with validate method.+ * @param entry - The block entry containing conditions.+ * @param outletName - The outlet name for error messages.+ * @param blockName - The block name for error messages.+ * @param path - The path in the layout tree for error messages.+ * @param callSiteError - Error object capturing where renderBlocks() was called.+ * @param rootLayout - The root blocks array for error context display.*/function validateBlockConditions(- blocksService,- entry,- outletName,- blockName,- path,- callSiteError = null,- rootLayout = null-) {+ blocksService: Blocks | undefined,+ entry: LayoutEntry,+ outletName: string,+ blockName: string,+ path: string,+ callSiteError: Error | null = null,+ rootLayout: LayoutEntry[] | null = null+): void {if (!entry.conditions || !blocksService) {return;}try {blocksService.validate(entry.conditions);- } catch (error) {+ } catch (error: unknown) {// Build context for error message - include rootLayout for tree display- const context = {+ const context: ValidationContext = {...createValidationContext({outletName,blockName,path,- entry,+ entry: asContextEntry(entry),callSiteError,- rootLayout,+ rootLayout: asContextLayout(rootLayout),}),conditions: entry.conditions,};// If error has a path property, build the full errorPath and conditionsPath// error.path is relative to conditions (e.g., "params.categoryId")- if (error.path) {+ const err = error as BlockError;+ if (err.path) {context.errorPath = buildErrorPath(path,- buildErrorPath("conditions", error.path)+ buildErrorPath("conditions", err.path));// conditionsPath is relative to the conditions object (for formatter)- context.conditionsPath = error.path;+ context.conditionsPath = err.path;}raiseBlockError(- `Invalid conditions for block "${blockName}" in outlet "${outletName}": ${error.message}`,+ `Invalid conditions for block "${blockName}" in outlet "${outletName}": ${err.message}`,context);}}+/** Context accepted by `resolveBlockForValidation`. */+interface ResolveBlockForValidationContext {+ /** Path to this entry in the block tree. */+ path?: string;+ /** The block entry object. */+ entry?: LayoutEntry | null;+ /** Error capturing call site location. */+ callSiteError?: Error | null;+ /** Root layout array for error display. */+ rootLayout?: LayoutEntry[] | null;+}++/**+ * Marker returned by `resolveBlockForValidation()` for an optional block+ * reference (`name?`) that isn't registered, keyed by the `OPTIONAL_MISSING`+ * symbol (distinct from the `registry/block.ts` `OptionalMissingMarker` shape,+ * which is keyed by the plain `"optionalMissing"` property).+ */+type ResolveOptionalMissingMarker = { [OPTIONAL_MISSING]: true; name: string };+/*** Resolves a block reference (string or class) to a BlockClass for validation.*@@ -406,22 +471,19 @@ function validateBlockConditions(* is returned instead of throwing an error. The calling code should check for this* marker and skip validation/rendering for the block.*- * @param {string | Object} blockRef - Block name string (possibly with `?` suffix) or BlockClass.- * @param {string} outletName - Outlet name for error messages.- * @param {Object} [context] - Context for error messages.- * @param {string} [context.path] - Path to this entry in the block tree.- * @param {Object} [context.entry] - The block entry object.- * @param {Error} [context.callSiteError] - Error capturing call site location.- * @param {Array} [context.rootLayout] - Root layout array for error display.- * @returns {Promise<Object | string | { [OPTIONAL_MISSING]: true, name: string }>}- * Resolved BlockClass, string name if deferred, or optional missing marker object.- * @throws {Error} If required block is not registered.+ * @param blockRef - Block name string (possibly with `?` suffix) or BlockClass.+ * @param outletName - Outlet name for error messages.+ * @param context - Context for error messages.+ * @returns Resolved BlockClass, string name if deferred, or optional missing marker object.+ * @throws Error if required block is not registered.*/export async function resolveBlockForValidation(- blockRef,- outletName,- context = {}-) {+ blockRef: string | BlockClass,+ outletName: string,+ context: ResolveBlockForValidationContext = {}+): Promise<+ BlockClass | string | ResolveOptionalMissingMarker | null | undefined+> {// Class reference - return as-is (classes always exist)if (typeof blockRef !== "string") {return blockRef;@@ -442,10 +504,10 @@ export async function resolveBlockForValidation(createValidationContext({outletName,blockName: name,- path: context.path,- entry: context.entry,+ path: context.path ?? "",+ entry: asContextEntry(context.entry),callSiteError: context.callSiteError,- rootLayout: context.rootLayout,+ rootLayout: asContextLayout(context.rootLayout),}));return null;@@ -470,7 +532,7 @@ export async function resolveBlockForValidation(* Any key not in this list will trigger a validation error, helping catch* common typos like `condition` instead of `conditions`.*/-export const VALID_ENTRY_KEYS = Object.freeze([+export const VALID_ENTRY_KEYS: readonly string[] = Object.freeze(["block", // Block class or name (required)"conditions", // Conditions for rendering"args", // Arguments to pass to the block@@ -480,17 +542,25 @@ export const VALID_ENTRY_KEYS = Object.freeze(["id", // Unique identifier for targeting and BEM styling]);+/**+ * A declarative type-validation rule for one block entry field, used by+ * `ENTRY_TYPE_RULES`.+ */+interface EntryTypeRule {+ /** Checks whether the field's value is valid. */+ validate: (value: unknown) => boolean;+ /** The expected type, for the error message. */+ expected: string;+ /** Describes the actual (invalid) value's type, for the error message.+ * Falls back to `typeof value` when omitted. */+ actual?: (value: unknown) => string;+}+/*** Declarative type validation rules for block entry fields.* Each rule specifies how to validate a field's type and generate error messages.- *- * @type {Object<string, {- * validate: (value: any) => boolean,- * expected: string,- * actual?: (value: any) => string- * }>}*/-const ENTRY_TYPE_RULES = {+const ENTRY_TYPE_RULES: Record<string, EntryTypeRule> = {args: {validate: (v) => typeof v === "object" && !Array.isArray(v),expected: "an object",@@ -534,10 +604,10 @@ const ENTRY_TYPE_RULES = {* Internal keys (starting with `__`) are skipped as they are added by the* system during preprocessing (e.g., `__visible`, `__failureReason`).*- * @param {Object} entry - The block entry object.- * @throws {BlockError} If unknown keys are found.+ * @param entry - The block entry object.+ * @throws BlockError if unknown keys are found.*/-export function validateEntryKeys(entry) {+export function validateEntryKeys(entry: LayoutEntry): void {const unknownKeys = Object.keys(entry).filter((key) => !key.startsWith("__") && !VALID_ENTRY_KEYS.includes(key));@@ -562,12 +632,15 @@ export function validateEntryKeys(entry) {* Validates the types of optional entry fields.* Iterates over ENTRY_TYPE_RULES to check each field's type.*- * @param {Object} entry - The block entry object.- * @throws {BlockError} If any field has an invalid type.+ * @param entry - The block entry object.+ * @throws BlockError if any field has an invalid type.*/-export function validateEntryTypes(entry) {+export function validateEntryTypes(entry: LayoutEntry): void {+ // `LayoutEntry` has no index signature, so reading it by a dynamic field+ // name needs the two-step cast (see `asContextEntry` above).+ const entryRecord = entry as unknown as Record<string, unknown>;for (const [field, rule] of Object.entries(ENTRY_TYPE_RULES)) {- const value = entry[field];+ const value = entryRecord[field];if (value != null && !rule.validate(value)) {const actualType = rule.actual?.(value) ?? typeof value;// Throw BlockError directly - wrapValidationError will add context@@ -583,10 +656,11 @@ export function validateEntryTypes(entry) {* Validation context passed through layout validation recursion.* Created at the root level and shared across all entries to enable* cross-cutting validation (e.g., ID uniqueness across the entire tree).- *- * @typedef {Object} LayoutValidationContext- * @property {Map<string, {path: string}>} seenIds - Map of entry IDs to their paths for uniqueness validation.*/+export interface LayoutValidationContext {+ /** Map of entry IDs to their paths for uniqueness validation. */+ seenIds: Map<string, { path: string }>;+}/*** Recursively validates an outlet layout (array of block entries).@@ -596,31 +670,30 @@ export function validateEntryTypes(entry) {* - In dev/test: Eagerly resolves all factories for early error detection.* - In production: Defers factory resolution to render time.*- * @param {Array<Object>} layout - The outlet layout (array of block entries) to validate.- * @param {string} outletName - The outlet these blocks belong to.- * @param {import("discourse/services/blocks").default} blocksService - Service for validating conditions.- * @param {string} [parentPath=""] - JSON-path style parent location for error context.- * @param {Error | null} [callSiteError] - Where renderBlocks() was called from.- * @param {Array<Object>} [rootLayout] - The root layout array for error context display.- * @param {Object|null} [parentChildArgsSchema=null] - The parent container's childArgs schema, if any.- * @param {string|null} [parentBlockName=null] - The parent container's block name for error messages.- * @param {number} [depth=0] - Current nesting depth for recursion limit checking.- * @param {LayoutValidationContext} [context] - Validation context for cross-cutting concerns like ID uniqueness.- * @returns {Promise<void>} Resolves when validation completes.- * @throws {Error} If any block entry is invalid or nesting depth exceeds MAX_LAYOUT_DEPTH.+ * @param layout - The outlet layout (array of block entries) to validate.+ * @param outletName - The outlet these blocks belong to.+ * @param blocksService - Service for validating conditions.+ * @param parentPath - JSON-path style parent location for error context.+ * @param callSiteError - Where renderBlocks() was called from.+ * @param rootLayout - The root layout array for error context display.+ * @param parentChildArgsSchema - The parent container's childArgs schema, if any.+ * @param parentBlockName - The parent container's block name for error messages.+ * @param depth - Current nesting depth for recursion limit checking.+ * @param context - Validation context for cross-cutting concerns like ID uniqueness.+ * @throws Error if any block entry is invalid or nesting depth exceeds MAX_LAYOUT_DEPTH.*/export async function validateLayout(- layout,- outletName,- blocksService,+ layout: LayoutEntry[],+ outletName: string,+ blocksService: Blocks | undefined,parentPath = "",- callSiteError = null,- rootLayout = null,- parentChildArgsSchema = null,- parentBlockName = null,+ callSiteError: Error | null = null,+ rootLayout: LayoutEntry[] | null = null,+ parentChildArgsSchema: Record<string, ChildArgSchema> | null = null,+ parentBlockName: string | null = null,depth = 0,- context = { seenIds: new Map() }-) {+ context: LayoutValidationContext = { seenIds: new Map() }+): Promise<void> {// On first call, capture the root layout for error displayconst effectiveRootLayout = rootLayout ?? layout;@@ -633,7 +706,7 @@ export async function validateLayout(outletName,path: parentPath,callSiteError,- rootLayout: effectiveRootLayout,+ rootLayout: asContextLayout(effectiveRootLayout),}));}@@ -649,7 +722,7 @@ export async function validateLayout(outletName,path: parentPath,callSiteError,- rootLayout: effectiveRootLayout,+ rootLayout: asContextLayout(effectiveRootLayout),}));}@@ -661,7 +734,7 @@ export async function validateLayout(// Check ID uniqueness across the entire layout using shared contextif (entry.id) {if (context.seenIds.has(entry.id)) {- const first = context.seenIds.get(entry.id);+ const first = context.seenIds.get(entry.id)!;raiseBlockError(`Duplicate block id "${entry.id}" in outlet "${outletName}". ` +`Found at ${first.path} and ${currentPath}. Block IDs must be unique per layout.`,@@ -669,9 +742,9 @@ export async function validateLayout(...createValidationContext({outletName,path: currentPath,- entry,+ entry: asContextEntry(entry),callSiteError,- rootLayout: effectiveRootLayout,+ rootLayout: asContextLayout(effectiveRootLayout),}),errorPath: `${currentPath}.id`,}@@ -696,26 +769,25 @@ export async function validateLayout(// Recursively validate nested childrenif (entry.children) {// Get the block name for error messages when passing childArgs to children- let blockName = null;+ let blockName: string | null = null;if (childArgsSchema) {// We need the block name for error messages - resolve itconst resolved = await resolveBlockForValidation(entry.block,outletName,- createValidationContext({- outletName,+ {path: currentPath,entry,callSiteError,rootLayout: effectiveRootLayout,- })+ });if (resolved &&- typeof resolved !== "string" &&- !resolved[OPTIONAL_MISSING]+ (typeof resolved === "object" || typeof resolved === "function") &&+ !(OPTIONAL_MISSING in resolved)) {- blockName = getBlockMetadata(resolved)?.blockName;+ blockName = getBlockMetadata(resolved)?.blockName ?? null;}}@@ -742,7 +814,7 @@ export async function validateLayout(** Performs comprehensive validation including:* - Outlet name is a valid registered outlet (core or custom)- * - Block reference is valid (string name or @block-decorated class)+ * - Block reference is valid (string name or `@block`-decorated class)* - Block is registered in the registry* - Container/children relationship is valid* - No reserved arg names are used@@ -753,39 +825,34 @@ export async function validateLayout(* if a block reference is a string pointing to an unresolved factory, full* validation is deferred to render time.*- * @param {Object} entry - The block entry object.- * @param {typeof import("@glimmer/component").default | string} entry.block - Block class or name string.- * @param {Object} [entry.args] - Args to pass to the block.- * @param {Object} [entry.containerArgs] - Args required by parent container's childArgs schema.- * @param {Array<Object>} [entry.children] - Nested block entries.- * @param {Array<Object>|Object} [entry.conditions] - Conditions for rendering.- * @param {string} outletName - The outlet this block belongs to.- * @param {import("discourse/services/blocks").default} blocksService - Service for validating conditions.- * @param {string} [path] - JSON-path style location in layout (e.g., "[3].children[0]").- * @param {Error | null} [callSiteError] - Where renderBlocks() was called from.- * @param {Array<Object>} [rootLayout] - The root layout array for error context display.- * @param {Object|null} [parentChildArgsSchema=null] - The parent container's childArgs schema, if any.- * @param {string|null} [parentBlockName=null] - The parent container's block name for error messages.- * @returns {Promise<Object|null>} The block's childArgsSchema if it's a container with childArgs, otherwise null.- * @throws {Error} If validation fails.+ * @param entry - The block entry object.+ * @param outletName - The outlet this block belongs to.+ * @param blocksService - Service for validating conditions.+ * @param path - JSON-path style location in layout (e.g., "[3].children[0]").+ * @param callSiteError - Where renderBlocks() was called from.+ * @param rootLayout - The root layout array for error context display.+ * @param parentChildArgsSchema - The parent container's childArgs schema, if any.+ * @param parentBlockName - The parent container's block name for error messages.+ * @returns The block's childArgsSchema if it's a container with childArgs, otherwise null.+ * @throws Error if validation fails.*/export async function validateEntry(- entry,- outletName,- blocksService,- path,- callSiteError = null,- rootLayout = null,- parentChildArgsSchema = null,- parentBlockName = null-) {+ entry: LayoutEntry,+ outletName: string,+ blocksService: Blocks | undefined,+ path: string,+ callSiteError: Error | null = null,+ rootLayout: LayoutEntry[] | null = null,+ parentChildArgsSchema: Record<string, ChildArgSchema> | null = null,+ parentBlockName: string | null = null+): Promise<Record<string, ChildArgSchema> | null> {// Create context without blockName for early validation errorsconst earlyContext = createValidationContext({outletName,path,- entry,+ entry: asContextEntry(entry),callSiteError,- rootLayout,+ rootLayout: asContextLayout(rootLayout),});if (!isValidOutlet(outletName)) {@@ -825,7 +892,7 @@ export async function validateEntry(const resolvedBlock = await resolveBlockForValidation(entry.block,outletName,- earlyContext+ { path, entry, callSiteError, rootLayout });// If resolution returned null (error was raised), exit early@@ -833,8 +900,17 @@ export async function validateEntry(return null;}- // Optional block not registered - skip validation entirely- if (resolvedBlock?.[OPTIONAL_MISSING]) {+ // Optional block not registered - skip validation entirely. Guard for an+ // object or function before the `in` read: untyped callers can put any+ // primitive in `entry.block` (e.g. `{ block: 42 }`), and those must fall+ // through to the actionable decorator error below instead of throwing on+ // the `in` operator.+ if (+ resolvedBlock &&+ (typeof resolvedBlock === "object" ||+ typeof resolvedBlock === "function") &&+ OPTIONAL_MISSING in resolvedBlock+ ) {return null;}@@ -858,11 +934,15 @@ export async function validateEntry(return null;}- // Full validation with resolved class- const blockMeta = getBlockMetadata(resolvedBlock);+ // Full validation with resolved class. `resolvedBlock` can still be+ // `undefined` here for a block whose factory previously failed to resolve+ // (only reachable in DEBUG mode); `getBlockMetadata()`'s underlying WeakMap+ // lookup safely returns `null` for a non-object key at runtime regardless+ // of this cast, so it doesn't change behavior.+ const blockMeta = getBlockMetadata(resolvedBlock as BlockClass);if (!blockMeta) {raiseBlockError(- `Block "${resolvedBlock?.name || "unknown"}" at ${path} for outlet "${outletName}" is not a valid @block-decorated component.`,+ `Block "${(resolvedBlock as { name?: string } | undefined)?.name || "unknown"}" at ${path} for outlet "${outletName}" is not a valid @block-decorated component.`,earlyContext);return null;@@ -870,14 +950,20 @@ export async function validateEntry(const blockName = blockMeta.blockName;+ // `blockMeta` is only non-null when `resolvedBlock` was an actual+ // registered block class (the `undefined` edge case above always fails+ // that lookup and returns earlier), so `resolvedBlock` is a real+ // `BlockClass` from here on.+ const resolvedBlockClass = resolvedBlock as BlockClass;+// Build base context for all validation errors in this blockconst baseContext = createValidationContext({outletName,blockName,path,- entry,+ entry: asContextEntry(entry),callSiteError,- rootLayout,+ rootLayout: asContextLayout(rootLayout),});// Validate outlet permission (allowedOutlets/deniedOutlets)@@ -905,7 +991,7 @@ export async function validateEntry(const errorPrefix = `Invalid block "${blockName}" at ${path} for outlet "${outletName}"`;const owner = blocksService ? getOwner(blocksService) : null;wrapValidationError(- () => validateBlockArgs(entry, resolvedBlock, { owner }),+ () => validateBlockArgs(entry, resolvedBlockClass, { owner }),errorPrefix,baseContext);@@ -913,7 +999,7 @@ export async function validateEntry(// Validate constraints and custom validation (after applying defaults)validateBlockConstraints(blockMeta,- resolvedBlock,+ resolvedBlockClass,entry,blockName,baseContextdiff --git a/frontend/discourse/app/lib/blocks/index.js b/frontend/discourse/app/lib/blocks/index.tssimilarity index 98%rename from frontend/discourse/app/lib/blocks/index.jsrename to frontend/discourse/app/lib/blocks/index.tsindex 5e6bced7b14..588fa11dd8c 100644--- a/frontend/discourse/app/lib/blocks/index.js+++ b/frontend/discourse/app/lib/blocks/index.ts@@ -1,4 +1,3 @@-// @ts-check/*** Public API for the Discourse Block system.*@@ -6,15 +5,15 @@* can use when working with blocks. Internal implementation details are kept* in the `-internals/` directory and should not be imported directly.*- * @module discourse/lib/blocks- ** @example+ * ```javascript* import {* VALID_BLOCK_NAME_PATTERN,* parseBlockName,* VALID_ARG_TYPES,* matchValue,* } from "discourse/lib/blocks";+ * ```*//* Pattern Validation */@@ -35,10 +34,12 @@ export { VALID_BLOCK_NAME_PATTERN } from "discourse/lib/blocks/-internals/patter* - **Theme blocks**: `theme:theme-name:block-name`** @example+ * ```* // Valid patterns:* "group" // Core block* "chat:message-widget" // Plugin block* "theme:tactile:hero-banner" // Theme block+ * ```*/export { VALID_NAMESPACED_BLOCK_PATTERN } from "discourse/lib/blocks/-internals/patterns";@@ -46,6 +47,7 @@ export { VALID_NAMESPACED_BLOCK_PATTERN } from "discourse/lib/blocks/-internals/* Parses a full block name into its components.** @example+ * ```* parseBlockName("group")* // => { type: "core", namespace: null, name: "group" }*@@ -54,6 +56,7 @@ export { VALID_NAMESPACED_BLOCK_PATTERN } from "discourse/lib/blocks/-internals/** parseBlockName("theme:tactile:hero-banner")* // => { type: "theme", namespace: "tactile", name: "hero-banner" }+ * ```*/export { parseBlockName } from "discourse/lib/blocks/-internals/patterns";@@ -65,11 +68,13 @@ export { parseBlockName } from "discourse/lib/blocks/-internals/patterns";* instead of throwing an error.** @example+ * ```* parseBlockReference("chat:widget?")* // => { name: "chat:widget", optional: true }** parseBlockReference("hero-banner")* // => { name: "hero-banner", optional: false }+ * ```*/export { parseBlockReference } from "discourse/lib/blocks/-internals/patterns";@@ -114,10 +119,12 @@ export { VALID_PAGE_TYPES } from "discourse/lib/blocks/-internals/matching/page-* at any level of the path.** @example+ * ```* const user = { profile: { name: "Alice", settings: { theme: "dark" } } };* getByPath(user, "profile.name"); // "Alice"* getByPath(user, "profile.settings.theme"); // "dark"* getByPath(user, "profile.missing"); // undefined+ * ```*/export { getByPath } from "discourse/lib/blocks/-internals/utils";@@ -134,9 +141,11 @@ export { getByPath } from "discourse/lib/blocks/-internals/utils";* - ANY (OR): `{ any: [...] }` matches if actual matches any spec in array** @example+ * ```* matchValue({ actual: 5, expected: 5 }) // true* matchValue({ actual: 5, expected: [3, 5, 7] }) // true (OR)* matchValue({ actual: "hello", expected: /^hel/ }) // true* matchValue({ actual: 5, expected: { not: 3 } }) // true+ * ```*/export { matchValue } from "discourse/lib/blocks/-internals/matching/value-matcher";diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 930a97675e0..0efa0704ce4 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -3735,7 +3735,7 @@ class _PluginApi {* in future releases without prior notice. Use with caution in production environments.** @param {string} outletName - The block outlet identifier- * @param {Array<import("discourse/blocks/block-outlet").LayoutEntry>} blocks - Array of layout entries+ * @param {Array<import("discourse/blocks/types").LayoutEntry>} blocks - Array of layout entries** @example* ```javascript@@ -3804,7 +3804,7 @@ class _PluginApi {* @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.*- * @param {typeof import("@glimmer/component").default | string} blockOrName - Block class or name string for lazy loading.+ * @param {string | import("discourse/lib/blocks/-internals/types").BlockClass} blockOrName - Block class or name string for lazy loading.* @param {Function} [factory] - Factory function returning Promise<BlockClass> (required when first arg is name).** @example Direct class registrationdiff --git a/frontend/discourse/app/lib/registry/block-outlets.js b/frontend/discourse/app/lib/registry/block-outlets.tssimilarity index 94%rename from frontend/discourse/app/lib/registry/block-outlets.jsrename to frontend/discourse/app/lib/registry/block-outlets.tsindex 17c54b86e64..88416158b2e 100644--- a/frontend/discourse/app/lib/registry/block-outlets.js+++ b/frontend/discourse/app/lib/registry/block-outlets.ts@@ -33,7 +33,7 @@ import { VALID_BLOCK_NAME_PATTERN } from "discourse/lib/blocks";* **Rule of thumb:** If the outlet depends on ANY plugin being enabled, it MUST* be registered via `api.registerBlockOutlet()` in that plugin's code, not here.*- * @constant {ReadonlyArray<string>} BLOCK_OUTLETS - An immutable array of core block outlet identifiers+ * An immutable array of core block outlet identifiers.*/// eslint-discourse keep-array-sortedexport const BLOCK_OUTLETS = Object.freeze([diff --git a/frontend/discourse/app/services/blocks.js b/frontend/discourse/app/services/blocks.tssimilarity index 74%rename from frontend/discourse/app/services/blocks.jsrename to frontend/discourse/app/services/blocks.tsindex cb6f9eeb4ce..1b935d95afa 100644--- a/frontend/discourse/app/services/blocks.js+++ b/frontend/discourse/app/services/blocks.ts@@ -1,11 +1,14 @@-// @ts-checkimport { getOwner, setOwner } from "@ember/owner";import Service from "@ember/service";-/** @type {import("discourse/blocks/block-outlet.gjs")} */import { _hasLayout } from "discourse/blocks/block-outlet";+import type { BlockCondition } from "discourse/blocks/conditions";+import type { BlockMetadata, LayoutEntry } from "discourse/blocks/types";import { debugHooks } from "discourse/lib/blocks/-internals/debug-hooks";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";-import { evaluateConditions } from "discourse/lib/blocks/-internals/matching/condition-evaluator";+import {+ type ConditionEvaluationContext,+ evaluateConditions,+} from "discourse/lib/blocks/-internals/matching/condition-evaluator";import {getAllBlockEntries,getBlockEntry,@@ -15,8 +18,25 @@ import {} from "discourse/lib/blocks/-internals/registry/block";import { getAllConditionTypeEntries } from "discourse/lib/blocks/-internals/registry/condition";import { getAllOutlets } from "discourse/lib/blocks/-internals/registry/outlet";+import type {+ BlockClass,+ BlockRegistryEntry,+} from "discourse/lib/blocks/-internals/types";import { validateConditions } from "discourse/lib/blocks/-internals/validation/conditions";+/**+ * A registered block paired with its `@block` decorator metadata, as+ * returned by `listBlocksWithMetadata()`.+ */+export interface BlockInfo {+ /** The registered block name. */+ name: string;+ /** The block's registry entry: a resolved class, or a lazy factory. */+ component: BlockRegistryEntry;+ /** The block's `@block` decorator metadata, or `null` if unavailable. */+ metadata: BlockMetadata | null;+}+/*** Unified service for block registry and condition evaluation.*@@ -51,18 +71,13 @@ import { validateConditions } from "discourse/lib/blocks/-internals/validation/c** @experimental This API is under active development and may change or be removed* in future releases without prior notice. Use with caution in production environments.- *- * @class Blocks- * @extends Service*/export default class Blocks extends Service {/*** Map of condition type names to their instances.* Built lazily from the condition type registry when first accessed.- *- * @type {Map<string, import("discourse/blocks/conditions").BlockCondition>}*/- #conditionInstances = new Map();+ #conditionInstances = new Map<string, BlockCondition>();/*** Tracks the registry size at last initialization to detect new registrations.@@ -72,10 +87,8 @@ export default class Blocks extends Service {* 2. Size comparison is O(1) vs O(n) for set difference* 3. Avoids allocating a Set<string> for tracking*- * When registry.size > #lastKnownRegistrySize, we know new types were registered- * and need to create instances for them.- *- * @type {number}+ * When `registry.size` is greater than `#lastKnownRegistrySize`, we know new+ * types were registered and need to create instances for them.*/#lastKnownRegistrySize = 0;@@ -86,17 +99,17 @@ export default class Blocks extends Service {/*** Returns all registered block outlet names (both core and custom).*- * Core outlets are defined in `lib/registry/block-outlets.js`. Custom outlets+ * Core outlets are defined in `lib/registry/block-outlets.ts`. Custom outlets* are registered by plugins and themes via `api.registerBlockOutlet()`.*- * @returns {string[]} Array of outlet names (e.g., ["hero-blocks", "homepage-blocks", ...]).+ * @returns Array of outlet names (e.g., ["hero-blocks", "homepage-blocks", ...]).** @example* ```javascript* const outlets = this.blocks.listOutlets();* ```*/- listOutlets() {+ listOutlets(): string[] {return getAllOutlets();}@@ -107,8 +120,8 @@ export default class Blocks extends Service {* for an outlet. This method allows checking layout presence outside of* `BlockOutlet` templates.*- * @param {string} outletName - The outlet identifier to check.- * @returns {boolean} True if a layout is registered for this outlet.+ * @param outletName - The outlet identifier to check.+ * @returns True if a layout is registered for this outlet.** @example* ```javascript@@ -117,7 +130,7 @@ export default class Blocks extends Service {* }* ```*/- hasLayout(outletName) {+ hasLayout(outletName: string): boolean {return _hasLayout(outletName);}@@ -128,23 +141,22 @@ export default class Blocks extends Service {/*** Gets a registered block by name.*- * @param {string} name - The block name (e.g., "hero-banner")- * @returns {import("discourse/lib/blocks/-internals/registry/block").BlockRegistryEntry|undefined} The block entry, or undefined if not found+ * @param name - The block name (e.g., "hero-banner")+ * @returns The block entry, or undefined if not found** @example* ```javascript* const HeroBanner = this.blocks.getBlock("hero-banner");* ```*/- getBlock(name) {+ getBlock(name: string): BlockRegistryEntry | undefined {return getBlockEntry(name);}/*** Checks if a block is registered.*- * @param {string} name - The block name- * @returns {boolean}+ * @param name - The block name** @example* ```javascript@@ -153,21 +165,19 @@ export default class Blocks extends Service {* }* ```*/- hasBlock(name) {+ hasBlock(name: string): boolean {return hasBlock(name);}/*** Returns all registered block entries.*- * @returns {Array<import("discourse/lib/blocks/-internals/registry/block").BlockRegistryEntry>}- ** @example* ```javascript* const allBlocks = this.blocks.listBlocks();* ```*/- listBlocks() {+ listBlocks(): BlockRegistryEntry[] {return getAllBlockEntries().map(([, entry]) => entry);}@@ -175,8 +185,6 @@ export default class Blocks extends Service {* Returns all registered blocks with their metadata.* Useful for admin UIs and documentation generation.*- * @returns {Array<{name: string, component: import("discourse/lib/blocks/-internals/registry/block").BlockRegistryEntry, metadata: Object}>}- ** @example* ```javascript* const blocksInfo = this.blocks.listBlocksWithMetadata();@@ -185,7 +193,7 @@ export default class Blocks extends Service {* });* ```*/- listBlocksWithMetadata() {+ listBlocksWithMetadata(): BlockInfo[] {return getAllBlockEntries().map(([name, component]) => ({name,component,@@ -199,9 +207,8 @@ export default class Blocks extends Service {* Unlike `getBlock()` which returns the raw registry entry (which may be a factory),* this method ensures the returned value is always a resolved BlockClass.*- * @param {string} name - The block name (e.g., "hero-banner").- * @returns {Promise<import("discourse/lib/blocks/-internals/registry/block").BlockClass|undefined>}- * The resolved block class, or undefined if not found.+ * @param name - The block name (e.g., "hero-banner").+ * @returns The resolved block class, or undefined if not found.** @example* ```javascript@@ -211,7 +218,7 @@ export default class Blocks extends Service {* }* ```*/- async getBlockAsync(name) {+ async getBlockAsync(name: string): Promise<BlockClass | undefined> {if (!hasBlock(name)) {return undefined;}@@ -229,8 +236,8 @@ export default class Blocks extends Service {* Returns false for unregistered blocks or blocks that are registered as factory functions* but haven't been resolved yet.*- * @param {string} name - The block name.- * @returns {boolean} True if registered and immediately available.+ * @param name - The block name.+ * @returns True if registered and immediately available.** @example* ```javascript@@ -243,7 +250,7 @@ export default class Blocks extends Service {* }* ```*/- isBlockReady(name) {+ isBlockReady(name: string): boolean {if (!hasBlock(name)) {return false;}@@ -265,7 +272,7 @@ export default class Blocks extends Service {** Called at the start of validate(), evaluate(), and other condition methods.*/- #lazilyInitializeConditionInstances() {+ #lazilyInitializeConditionInstances(): void {const entries = getAllConditionTypeEntries();// Only rebuild if registry has grown since last check@@ -287,12 +294,18 @@ export default class Blocks extends Service {* Creates an instance of a condition class and stores it in the instances map.* Sets the owner on the instance to enable service injection.*- * @param {string} type - The condition type name.- * @param {typeof import("discourse/blocks/conditions").BlockCondition} ConditionClass - The condition class.+ * @param type - The condition type name.+ * @param ConditionClass - The condition class.*/- #createConditionInstance(type, ConditionClass) {+ #createConditionInstance(+ type: string,+ ConditionClass: typeof BlockCondition+ ): void {const instance = new ConditionClass();- setOwner(instance, getOwner(this));+ // This service instance is always Ember-owned (services are only ever+ // instantiated through the DI container), so `getOwner(this)` is never+ // undefined here.+ setOwner(instance, getOwner(this)!);this.#conditionInstances.set(type, instance);}@@ -305,10 +318,10 @@ export default class Blocks extends Service {* `path` property indicating where in the conditions the error occurred* (relative to the conditions root, e.g., "params.categoryId").*- * @param {Object|Array<Object>} conditionSpec - Condition spec(s) to validate.- * @throws {BlockError} If validation fails.+ * @param conditionSpec - Condition spec(s) to validate.+ * @throws A `BlockError` if validation fails.*/- validate(conditionSpec) {+ validate(conditionSpec: LayoutEntry["conditions"]): void {this.#lazilyInitializeConditionInstances();validateConditions(conditionSpec, this.#conditionInstances);}@@ -317,14 +330,14 @@ export default class Blocks extends Service {* Evaluates condition specs at render time.* Recursively evaluates nested conditions with AND/OR/NOT logic.*- * @param {Object|Array<Object>} conditionSpec - Condition spec(s) to evaluate.- * @param {Object} [context] - Evaluation context.- * @param {boolean} [context.debug] - Enable debug logging for this evaluation.- * @param {number} [context._depth] - Internal: nesting depth for logging.- * @param {Object} [context.outletArgs] - Outlet arguments passed to conditions.- * @returns {boolean} True if conditions pass, false otherwise.+ * @param conditionSpec - Condition spec(s) to evaluate.+ * @param context - Evaluation context.+ * @returns True if conditions pass, false otherwise.*/- evaluate(conditionSpec, context = {}) {+ evaluate(+ conditionSpec: LayoutEntry["conditions"],+ context: ConditionEvaluationContext = {}+ ): boolean {this.#lazilyInitializeConditionInstances();return evaluateConditions(conditionSpec, this.#conditionInstances, context);}@@ -332,10 +345,9 @@ export default class Blocks extends Service {/*** Checks if a condition type is registered.*- * @param {string} type - The condition type name- * @returns {boolean}+ * @param type - The condition type name*/- hasConditionType(type) {+ hasConditionType(type: string): boolean {this.#lazilyInitializeConditionInstances();return this.#conditionInstances.has(type);}@@ -343,10 +355,8 @@ export default class Blocks extends Service {/*** Returns all registered condition type names.* Useful for debugging and error messages.- *- * @returns {string[]}*/- getRegisteredConditionTypes() {+ getRegisteredConditionTypes(): string[] {this.#lazilyInitializeConditionInstances();return [...this.#conditionInstances.keys()];}@@ -361,7 +371,7 @@ export default class Blocks extends Service {* Container blocks can use this to conditionally render ghost blocks* for children they choose not to display.*- * @returns {boolean} True if the visual overlay (ghost blocks) is enabled.+ * @returns True if the visual overlay (ghost blocks) is enabled.** @example* ```javascript@@ -370,7 +380,7 @@ export default class Blocks extends Service {* }* ```*/- get showGhosts() {+ get showGhosts(): boolean {return debugHooks.isGhostBlocksEnabled;}}diff --git a/frontend/discourse/app/static/dev-tools/block-debug/block-info.gjs b/frontend/discourse/app/static/dev-tools/block-debug/block-info.gtssimilarity index 76%rename from frontend/discourse/app/static/dev-tools/block-debug/block-info.gjsrename to frontend/discourse/app/static/dev-tools/block-debug/block-info.gtsindex 6da4e674e32..0c01803e9d6 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/block-info.gjs+++ b/frontend/discourse/app/static/dev-tools/block-debug/block-info.gts@@ -1,32 +1,47 @@-// @ts-checkimport Component from "@glimmer/component";import { array, hash } from "@ember/helper";import DTooltip from "discourse/float-kit/components/d-tooltip";+import type {+ BlockComponent,+ BlockEntry,+} from "discourse/lib/blocks/-internals/types";import dIcon from "discourse/ui-kit/helpers/d-icon";import ArgsTable from "../shared/args-table";import ConditionsTree from "./conditions-tree";+interface BlockInfoSignature {+ Args: {+ /** The name of the block. */+ blockName: string;+ /** The block's unique ID (if set). */+ blockId?: string;+ /** The hierarchy path where the block is rendered. */+ debugLocation: string;+ /** Arguments passed to the block. */+ blockArgs?: Record<string, unknown>;+ /** Container arguments passed from parent container's childArgs. */+ containerArgs?: Record<string, unknown>;+ /** Conditions that were evaluated. */+ conditions?: BlockEntry["conditions"];+ /** Outlet arguments available to the block. */+ outletArgs?: Record<string, unknown>;+ /** The actual block component to render. */+ WrappedComponent: BlockComponent;+ };+}+/*** Visual overlay component for rendered blocks.* Wraps a block with debug information including name badge and tooltip.- *- * @param {string} blockName - The name of the block.- * @param {string} [blockId] - The block's unique ID (if set).- * @param {string} debugLocation - The hierarchy path where the block is rendered.- * @param {Object} [blockArgs] - Arguments passed to the block.- * @param {Object} [containerArgs] - Container arguments passed from parent container's childArgs.- * @param {Object} [conditions] - Conditions that were evaluated.- * @param {Object} [outletArgs] - Outlet arguments available to the block.- * @param {Component} WrappedComponent - The actual block component to render.*/-export default class BlockInfo extends Component {+export default class BlockInfo extends Component<BlockInfoSignature> {/*** Checks whether this block has any conditions configured.* Used to conditionally render the conditions section in the tooltip.*- * @returns {boolean} True if the block has conditions defined.+ * @returns True if the block has conditions defined.*/- get hasConditions() {+ get hasConditions(): boolean {return this.args.conditions != null;}@@ -34,9 +49,9 @@ export default class BlockInfo extends Component {* Checks whether this block has any arguments passed to it.* Used to conditionally render the arguments section in the tooltip.*- * @returns {boolean} True if the block has at least one argument.+ * @returns True if the block has at least one argument.*/- get hasArgs() {+ get hasArgs(): boolean {return (this.args.blockArgs != null && Object.keys(this.args.blockArgs).length > 0);@@ -46,9 +61,9 @@ export default class BlockInfo extends Component {* Checks whether this block has container args from a parent container.* Used to conditionally render the container args section in the tooltip.*- * @returns {boolean} True if the block has container args.+ * @returns True if the block has container args.*/- get hasContainerArgs() {+ get hasContainerArgs(): boolean {return (this.args.containerArgs != null &&Object.keys(this.args.containerArgs).length > 0@@ -59,9 +74,9 @@ export default class BlockInfo extends Component {* Checks whether this block has outlet args available.* Used to conditionally render the outlet args section in the tooltip.*- * @returns {boolean} True if outlet args are available.+ * @returns True if outlet args are available.*/- get hasOutletArgs() {+ get hasOutletArgs(): boolean {return (this.args.outletArgs != null &&Object.keys(this.args.outletArgs).length > 0@@ -73,9 +88,9 @@ export default class BlockInfo extends Component {* Used to show an "empty" message when there are no conditions, args,* container args, or outlet args.*- * @returns {boolean} True if there is nothing to display in the tooltip.+ * @returns True if there is nothing to display in the tooltip.*/- get isEmpty() {+ get isEmpty(): boolean {return (!this.hasConditions &&!this.hasArgs &&@@ -88,9 +103,9 @@ export default class BlockInfo extends Component {* Returns the display name for the block, including ID if set.* Format: "blockName" or "blockName(#id)".*- * @returns {string} The display name.+ * @returns The display name.*/- get displayName() {+ get displayName(): string {if (this.args.blockId) {return `${this.args.blockName}(#${this.args.blockId})`;}diff --git a/frontend/discourse/app/static/dev-tools/block-debug/button.gjs b/frontend/discourse/app/static/dev-tools/block-debug/button.gtssimilarity index 80%rename from frontend/discourse/app/static/dev-tools/block-debug/button.gjsrename to frontend/discourse/app/static/dev-tools/block-debug/button.gtsindex 5180fa80f58..e181fd030c0 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/button.gjs+++ b/frontend/discourse/app/static/dev-tools/block-debug/button.gts@@ -1,4 +1,3 @@-// @ts-checkimport Component from "@glimmer/component";import { on } from "@ember/modifier";import { action } from "@ember/object";@@ -19,9 +18,9 @@ export default class BlockDebugButton extends Component {* Determines if any block debug feature is currently enabled.* Used to highlight the toolbar button when debugging is active.*- * @returns {boolean} True if any block debug mode is enabled.+ * @returns True if any block debug mode is enabled.*/- get isActive() {+ get isActive(): boolean {return (devToolsState.blockDebug ||devToolsState.blockVisualOverlay ||@@ -34,12 +33,12 @@ export default class BlockDebugButton extends Component {* Toggles outlet boundary indicators around block outlets.* When enabled, shows visual borders around each block outlet area.*- * @param {Event} event - The checkbox change event.+ * @param event - The checkbox change event.*/@action- toggleOutletBoundaries(event) {- devToolsState.blockOutletBoundaries = /** @type {HTMLInputElement} */ (- event.target+ toggleOutletBoundaries(event: Event): void {+ devToolsState.blockOutletBoundaries = (+ event.target as HTMLInputElement).checked;}@@ -47,12 +46,12 @@ export default class BlockDebugButton extends Component {* Toggles visual overlay that displays block information on the page.* When enabled, shows badges and tooltips on rendered blocks.*- * @param {Event} event - The checkbox change event.+ * @param event - The checkbox change event.*/@action- toggleVisualOverlay(event) {- devToolsState.blockVisualOverlay = /** @type {HTMLInputElement} */ (- event.target+ toggleVisualOverlay(event: Event): void {+ devToolsState.blockVisualOverlay = (+ event.target as HTMLInputElement).checked;}@@ -61,26 +60,22 @@ export default class BlockDebugButton extends Component {* When enabled, shows placeholder outlines for blocks that weren't rendered* (e.g., failed conditions, optional missing, no visible children).*- * @param {Event} event - The checkbox change event.+ * @param event - The checkbox change event.*/@action- toggleGhostBlocks(event) {- devToolsState.blockGhostBlocks = /** @type {HTMLInputElement} */ (- event.target- ).checked;+ toggleGhostBlocks(event: Event): void {+ devToolsState.blockGhostBlocks = (event.target as HTMLInputElement).checked;}/*** Toggles condition debugging for block condition evaluation.* When enabled, logs detailed information about each block's condition checks.*- * @param {Event} event - The checkbox change event.+ * @param event - The checkbox change event.*/@action- toggleConditionDebugging(event) {- devToolsState.blockDebug = /** @type {HTMLInputElement} */ (- event.target- ).checked;+ toggleConditionDebugging(event: Event): void {+ devToolsState.blockDebug = (event.target as HTMLInputElement).checked;}<template>diff --git a/frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gjs b/frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gtssimilarity index 63%rename from frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gjsrename to frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gtsindex 2249512ff87..4d76802d05b 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gjs+++ b/frontend/discourse/app/static/dev-tools/block-debug/conditions-tree.gts@@ -1,24 +1,47 @@-// @ts-checkimport Component from "@glimmer/component";-import { trustHTML } from "@ember/template";+import { TrustedHTML, trustHTML } from "@ember/template";+import type { BlockEntry } from "discourse/lib/blocks/-internals/types";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { formatValue } from "../lib/value-formatter";+/**+ * A single node in the hierarchical condition tree produced by+ * `#formatCondition()`, ready for rendering by `ConditionNode`.+ */+interface FormattedConditionNode {+ /** Condition type, or combinator (AND/OR/NOT). */+ type: string;+ /** Nesting depth for indentation. */+ depth: number;+ /** Nested nodes, for combinator nodes. */+ children?: FormattedConditionNode[];+ /** Remaining condition arguments, for leaf nodes. */+ args?: Record<string, unknown> | null;+ /** True for leaf (non-combinator) condition nodes. */+ isLeaf?: boolean;+}++interface ConditionsTreeSignature {+ Args: {+ /** The conditions to display. */+ conditions?: BlockEntry["conditions"];+ /** Whether the conditions passed overall. */+ passed: boolean;+ };+}+/*** Displays condition hierarchy with pass/fail indicators.- *- * @param {Object|Array} conditions - The conditions to display- * @param {boolean} passed - Whether the conditions passed overall*/-export default class ConditionsTree extends Component {+export default class ConditionsTree extends Component<ConditionsTreeSignature> {/*** Transforms the raw conditions object/array into a hierarchical array of* formatted nodes for rendering. This is the entry point for the recursive* formatting. Each node may contain a `children` array for nested conditions.*- * @returns {Array<Object>} An array of condition nodes ready for rendering.+ * @returns An array of condition nodes ready for rendering.*/- get formattedConditions() {+ get formattedConditions(): FormattedConditionNode[] {return this.#formatCondition(this.args.conditions, 0);}@@ -31,16 +54,19 @@ export default class ConditionsTree extends Component {* - Object with `not`: NOT combinator, child is the negated condition.* - Object with `type`: Leaf condition node with optional arguments.*- * @param {Object|Array|null} condition - The condition to format.- * @param {number} depth - The nesting depth for indentation calculation.- * @returns {Array<Object>} An array of formatted condition nodes.+ * @param condition - The condition to format.+ * @param depth - The nesting depth for indentation calculation.+ * @returns An array of formatted condition nodes.*/- #formatCondition(condition, depth) {+ #formatCondition(+ condition: object | object[] | null | undefined,+ depth: number+ ): FormattedConditionNode[] {if (!condition) {return [];}- const items = [];+ const items: FormattedConditionNode[] = [];// Array of conditions (AND logic) - all conditions must passif (Array.isArray(condition)) {@@ -53,29 +79,32 @@ export default class ConditionsTree extends Component {}// OR combinator - at least one condition must pass- if (condition.any !== undefined) {+ const anySpec = (condition as { any?: object[] }).any;+ if (anySpec !== undefined) {items.push({type: "OR",depth,- children: condition.any.flatMap((c) =>- this.#formatCondition(c, depth + 1)- ),+ children: anySpec.flatMap((c) => this.#formatCondition(c, depth + 1)),});return items;}// NOT combinator - inverts the result of the nested condition- if (condition.not !== undefined) {+ const notSpec = (condition as { not?: object }).not;+ if (notSpec !== undefined) {items.push({type: "NOT",depth,- children: this.#formatCondition(condition.not, depth + 1),+ children: this.#formatCondition(notSpec, depth + 1),});return items;}// Single condition with type (leaf node) - extract type and remaining args- const { type, ...args } = condition;+ const { type, ...args } = condition as { type: string } & Record<+ string,+ unknown+ >;items.push({type,args: Object.keys(args).length > 0 ? args : null,@@ -100,19 +129,23 @@ export default class ConditionsTree extends Component {</template>}+interface ConditionNodeSignature {+ Args: {+ /** The condition node data from `#formatCondition()`. */+ item: FormattedConditionNode;+ /** Whether the overall conditions passed. */+ passed: boolean;+ };+}+/*** Renders a single condition node in the tree.* Handles both combinator nodes (AND, OR, NOT) and leaf condition nodes.- *- * @param {Object} item - The condition node data from #formatCondition.- * @param {boolean} passed - Whether the overall conditions passed.*/-class ConditionNode extends Component {+class ConditionNode extends Component<ConditionNodeSignature> {/*** Formatting options for condition argument values.* Enables expanded arrays, symbols, and RegExp handling for readable output.- *- * @constant {Object}*/static FORMAT_OPTIONS = {expandArrays: true,@@ -124,9 +157,9 @@ class ConditionNode extends Component {* Calculates the CSS padding for indentation based on the node's depth.* Each level adds 12px of left padding.*- * @returns {ReturnType<typeof trustHTML>} CSS style string for padding, marked as safe for binding.+ * @returns CSS style string for padding, marked as safe for binding.*/- get indentStyle() {+ get indentStyle(): TrustedHTML {return trustHTML(`padding-left: ${this.args.item.depth * 12}px`);}@@ -134,9 +167,9 @@ class ConditionNode extends Component {* Checks if this node is a boolean combinator (AND, OR, NOT) rather than* a leaf condition. Combinators are styled differently in the UI.*- * @returns {boolean} True if this is a combinator node.+ * @returns True if this is a combinator node.*/- get isCombinator() {+ get isCombinator(): boolean {return ["AND", "OR", "NOT"].includes(this.args.item.type);}@@ -144,9 +177,9 @@ class ConditionNode extends Component {* Formats the condition's arguments as a comma-separated string for display.* Returns null if there are no arguments to display.*- * @returns {string|null} Formatted arguments string, or null if no arguments.+ * @returns Formatted arguments string, or null if no arguments.*/- get argsDisplay() {+ get argsDisplay(): string | null {const args = this.args.item.args;if (!args) {return null;diff --git a/frontend/discourse/app/static/dev-tools/block-debug/debug-logger.js b/frontend/discourse/app/static/dev-tools/block-debug/debug-logger.tssimilarity index 63%rename from frontend/discourse/app/static/dev-tools/block-debug/debug-logger.jsrename to frontend/discourse/app/static/dev-tools/block-debug/debug-logger.tsindex c02e4d6f596..a7c2f1727c1 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/debug-logger.js+++ b/frontend/discourse/app/static/dev-tools/block-debug/debug-logger.ts@@ -1,4 +1,3 @@-// @ts-check/*** Block debug logger with styled console output.*@@ -7,10 +6,9 @@** This module lives in the dev-tools bundle and is only loaded when dev tools* are enabled, reducing the main application bundle size.- *- * @module discourse/static/dev-tools/block-debug/debug-logger*/+import type { ConditionResolvedValue } from "discourse/blocks/conditions/condition";import { isTypeMismatch } from "discourse/lib/blocks/-internals/matching/value-matcher";// Console output styles@@ -27,6 +25,101 @@ const ICONS = {failed: "\u2717", // X (failed)};+/** A single match result within a param/queryParam group (see `logParamGroup()`). */+export interface ParamMatch {+ /** The param/queryParam key. */+ key: string;+ /** The configured (expected) value spec. */+ expected: unknown;+ /** The actual value from the current route. */+ actual: unknown;+ /** Whether this key matched. */+ result: boolean;+}++/** Options accepted by `logCondition()`. */+export interface LogConditionOptions {+ /** Condition type or combinator (AND/OR/NOT). */+ type: string;+ /** Condition arguments: a record for a leaf condition, a display string for+ * a combinator (e.g. "3 conditions"), or `null`/omitted for a NOT combinator. */+ args?: string | Record<string, unknown> | null;+ /** Whether condition passed, or `null` for pending combinators. */+ result: boolean | null;+ /** Nesting depth for indentation. */+ depth?: number;+ /** Resolved value object, for conditions that resolve a value. */+ resolvedValue?: ConditionResolvedValue;+ /** The condition spec object, used to track pending results for+ * combinators/conditions that log before evaluation completes. */+ conditionSpec?: object;+}++/** Options accepted by `logParamGroup()`. */+export interface LogParamGroupOptions {+ /** Group label (e.g., "params", "queryParams", "params[0]"). */+ label: string;+ /** Match results. */+ matches: ParamMatch[];+ /** Overall result (all passed). */+ result: boolean;+ /** Nesting depth for indentation. */+ depth: number;+}++/** Options accepted by `logRouteState()`. */+export interface LogRouteStateOptions {+ /** The current URL path (normalized). */+ currentPath: string;+ /** URL patterns to match (if using urls). */+ expectedUrls?: string[];+ /** URL patterns to exclude (if using excludeUrls). */+ excludeUrls?: string[];+ /** Page types to match (e.g., ["CATEGORY_PAGES"]). */+ pages?: string[];+ /** The actual page type (when expected doesn't match). */+ actualPageType?: string | null;+ /** Actual page context; `null` when no page type matched. */+ actualPageContext: Record<string, unknown> | null;+ /** Nesting depth for indentation. */+ depth: number;+ /** Whether the URL/page matched (true) or not (false). */+ result: boolean;+}++/** A logged condition/combinator entry within a group's log buffer. */+interface ConditionLogEntry {+ type: string;+ args?: string | Record<string, unknown> | null;+ result: boolean | null;+ depth: number;+ resolvedValue?: ConditionResolvedValue;+}++/** A logged param-group entry, as pushed by `logParamGroup()`. */+interface ParamGroupLogEntry extends LogParamGroupOptions {+ type: "param-group";+}++/** A logged route-state entry, as pushed by `logRouteState()`. */+interface RouteStateLogEntry extends LogRouteStateOptions {+ type: "route-state";+}++/** A single entry in a group's log buffer. */+type DebugLogEntry =+ | ConditionLogEntry+ | ParamGroupLogEntry+ | RouteStateLogEntry;++/** The active evaluation group being built up between `startGroup()` and `endGroup()`. */+interface DebugLogGroup {+ blockName: string;+ blockId: string | null;+ hierarchy: string;+ logs: DebugLogEntry[];+}+/*** Block debug logger class.* Provides grouped console output for block condition evaluations.@@ -34,45 +127,36 @@ const ICONS = {class BlockDebugLogger {/*** Current evaluation group context.- *- * @type {{blockName: string, blockId: string|null, hierarchy: string, logs: Array}|null}*/- #currentGroup = null;+ #currentGroup: DebugLogGroup | null = null;/*** WeakMap to track pending log entries by condition spec object.* This allows updating log entries by reference rather than by depth/type lookup,* which is more robust for complex nested conditions.- *- * @type {WeakMap<Object, Object>}*/- #pendingLogs = new WeakMap();+ #pendingLogs = new WeakMap<object, ConditionLogEntry>();/*** Start a new evaluation group for a block render.* All subsequent logCondition calls will be collected in this group* until endGroup is called.*- * @param {string} blockName - The block being evaluated.- * @param {string|null} blockId - The block's unique ID, or null if not set.- * @param {string} hierarchy - The outlet/parent hierarchy path (e.g., "outlet-name/parent-block").+ * @param blockName - The block being evaluated.+ * @param blockId - The block's unique ID, or null if not set.+ * @param hierarchy - The outlet/parent hierarchy path (e.g., "outlet-name/parent-block").*/- startGroup(blockName, blockId, hierarchy) {+ startGroup(+ blockName: string,+ blockId: string | null,+ hierarchy: string+ ): void {this.#currentGroup = { blockName, blockId, hierarchy, logs: [] };}/*** Log a condition evaluation within the current group.* If no group is active, logs immediately to console.- *- * @param {Object} options - Log options- * @param {string} options.type - Condition type or combinator (AND/OR/NOT)- * @param {Object} [options.args] - Condition arguments- * @param {boolean|null} options.result - Whether condition passed, or null for pending combinators- * @param {number} [options.depth=0] - Nesting depth for indentation- * @param {{ value: *, hasValue: true, formatted?: Object, note?: string }|undefined} [options.resolvedValue] - Resolved value object- * @param {Object} [options.conditionSpec] - The condition spec object, used to track- * pending results for combinators/conditions that log before evaluation completes.*/logCondition({type,@@ -81,13 +165,19 @@ class BlockDebugLogger {depth = 0,resolvedValue,conditionSpec,- }) {+ }: LogConditionOptions): void {if (!this.#currentGroup) {this.#logStandalone(type, args, result);return;}- const logEntry = { type, args, result, depth, resolvedValue };+ const logEntry: ConditionLogEntry = {+ type,+ args,+ result,+ depth,+ resolvedValue,+ };this.#currentGroup.logs.push(logEntry);// Track pending logs by conditionSpec for later result updates.@@ -101,14 +191,8 @@ class BlockDebugLogger {/*** Log a param group with all matches as a nested expandable group.* Used for params/queryParams matching in route conditions.- *- * @param {Object} options - Log options.- * @param {string} options.label - Group label (e.g., "params", "queryParams", "params[0]").- * @param {Array<{key: string, expected: *, actual: *, result: boolean}>} options.matches - Match results.- * @param {boolean} options.result - Overall result (all passed).- * @param {number} options.depth - Nesting depth for indentation.*/- logParamGroup({ label, matches, result, depth }) {+ logParamGroup({ label, matches, result, depth }: LogParamGroupOptions): void {if (!this.#currentGroup) {return;}@@ -125,16 +209,6 @@ class BlockDebugLogger {* Log current URL/page state for debugging route conditions.* Shows URL/page matching status. Params and queryParams are logged separately* with proper nesting via logCondition.- *- * @param {Object} options - Log options.- * @param {string} options.currentPath - The current URL path (normalized).- * @param {Array} [options.expectedUrls] - URL patterns to match (if using urls).- * @param {Array} [options.excludeUrls] - URL patterns to exclude (if using excludeUrls).- * @param {Array} [options.pages] - Page types to match (e.g., ["CATEGORY_PAGES"]).- * @param {string} [options.actualPageType] - The actual page type (when expected doesn't match).- * @param {Object} [options.actualPageContext] - Actual page context (for determining page type match).- * @param {number} options.depth - Nesting depth for indentation.- * @param {boolean} options.result - Whether the URL/page matched (true) or not (false).*/logRouteState({currentPath,@@ -145,7 +219,7 @@ class BlockDebugLogger {actualPageContext,depth,result,- }) {+ }: LogRouteStateOptions): void {if (!this.#currentGroup) {return;}@@ -166,10 +240,13 @@ class BlockDebugLogger {* Update the result of a combinator (AND/OR/NOT) by its condition spec.* Used to set the actual result after children have been evaluated.*- * @param {Object} conditionSpec - The condition spec object used when logging.- * @param {boolean} result - The actual result.+ * @param conditionSpec - The condition spec object used when logging.+ * @param result - The actual result.*/- updateCombinatorResult(conditionSpec, result) {+ updateCombinatorResult(+ conditionSpec: object | null | undefined,+ result: boolean+ ): void {if (!this.#currentGroup || !conditionSpec) {return;}@@ -185,10 +262,13 @@ class BlockDebugLogger {* Update the result of a condition by its condition spec.* Used when the condition needs to log nested items before knowing its final result.*- * @param {Object} conditionSpec - The condition spec object used when logging.- * @param {boolean} result - The actual result.+ * @param conditionSpec - The condition spec object used when logging.+ * @param result - The actual result.*/- updateConditionResult(conditionSpec, result) {+ updateConditionResult(+ conditionSpec: object | null | undefined,+ result: boolean+ ): void {if (!this.#currentGroup || !conditionSpec) {return;}@@ -205,9 +285,9 @@ class BlockDebugLogger {* Uses console.groupCollapsed for a clean, expandable view.* Conditions with nested children are rendered as collapsible groups.*- * @param {boolean} finalResult - Whether the block will render+ * @param finalResult - Whether the block will render*/- endGroup(finalResult) {+ endGroup(finalResult: boolean): void {if (!this.#currentGroup) {return;}@@ -237,11 +317,11 @@ class BlockDebugLogger {);// Track open groups by their depth so we can close them when needed- const openGroupDepths = [];+ const openGroupDepths: number[] = [];for (let i = 0; i < logs.length; i++) {const log = logs[i];- const nextLog = logs[i + 1];+ const nextLog: DebugLogEntry | undefined = logs[i + 1];// Close any groups at same or deeper depth before rendering this logwhile (@@ -254,7 +334,7 @@ class BlockDebugLogger {}// Check if this log has children (next log is deeper)- const hasChildren = nextLog && nextLog.depth > log.depth;+ const hasChildren = !!nextLog && nextLog.depth > log.depth;this.#logTreeNode(log, hasChildren);@@ -280,39 +360,24 @@ class BlockDebugLogger {* Check if a log entry should be rendered as a collapsible group when it has children.* Param groups and route state handle their own grouping internally.*- * @param {Object} log - The log entry- * @returns {boolean} True if this log should be a group when it has children+ * @returns True if this log should be a group when it has children*/- #isGroupableLog(log) {+ #isGroupableLog(log: DebugLogEntry): boolean {const isSpecialType = ["param-group", "route-state"].includes(log.type);return !isSpecialType;}/*** Log a single node in the condition tree.- *- * @param {Object} log - The log entry.- * @param {string} log.type - Condition type.- * @param {Object} [log.args] - Condition arguments.- * @param {boolean} log.result - Pass/fail.- * @param {number} log.depth - Indentation depth.- * @param {string} [log.label] - Label for param groups.- * @param {Array} [log.matches] - Match results for param groups.- * @param {{ value: *, hasValue: true, formatted?: Object, note?: string }|undefined} [log.resolvedValue] - Resolved value object.- * @param {string} [log.currentPath] - Current URL path (for route-state type).- * @param {Array<string>} [log.expectedUrls] - Expected URL patterns (for route-state type).- * @param {Array<string>} [log.excludeUrls] - Excluded URL patterns (for route-state type).- * @param {Object} [log.pages] - Page configuration (for route-state type).- * @param {string} [log.actualPageType] - Actual page type (for route-state type).- * @param {Object} [log.actualPageContext] - Actual page context (for route-state type).- * @param {boolean} [hasChildren=false] - Whether this node has nested children.*/- #logTreeNode(log, hasChildren = false) {- const { type, args, result, resolvedValue } = log;-+ #logTreeNode(log: DebugLogEntry, hasChildren = false): void {// Handle route state (shows current URL/page status)// Uses checkmark/X to show whether the route matched- if (type === "route-state") {+ if (log.type === "route-state") {+ // `type` distinguishes the union members at runtime, but is typed as a+ // plain `string` on `ConditionLogEntry`, so it can't discriminate the+ // union for the type-checker — narrow explicitly.+ const routeLog = log as RouteStateLogEntry;const {currentPath,expectedUrls,@@ -321,7 +386,7 @@ class BlockDebugLogger {actualPageType,actualPageContext,result: routeResult,- } = log;+ } = routeLog;const routeIcon = routeResult ? ICONS.passed : ICONS.failed;const routeStyle = routeResult ? STYLES.passed : STYLES.failed;@@ -332,7 +397,7 @@ class BlockDebugLogger {const pageIcon = pageTypeMatched ? ICONS.passed : ICONS.failed;const pageStyle = pageTypeMatched ? STYLES.passed : STYLES.failed;- let pageStatus;+ let pageStatus: string;if (pageTypeMatched) {pageStatus = `on ${actualPageContext?.pageType || pages[0]}`;} else {@@ -363,12 +428,12 @@ class BlockDebugLogger {return;}- const icon = result ? ICONS.passed : ICONS.failed;- const iconStyle = result ? STYLES.passed : STYLES.failed;-- // Handle param group (params/queryParams)- if (type === "param-group") {- const { label, matches } = log;+ // Handle param group (params/queryParams). Same discrimination note as above.+ if (log.type === "param-group") {+ const paramLog = log as ParamGroupLogEntry;+ const { label, matches, result } = paramLog;+ const icon = result ? ICONS.passed : ICONS.failed;+ const iconStyle = result ? STYLES.passed : STYLES.failed;// Single key: print directly without group wrapperif (matches.length === 1) {@@ -396,6 +461,13 @@ class BlockDebugLogger {return;}+ // Remaining case: a condition or combinator (AND/OR/NOT) entry.+ const conditionLog = log as ConditionLogEntry;+ const { type, args, result, resolvedValue } = conditionLog;++ const icon = result ? ICONS.passed : ICONS.failed;+ const iconStyle = result ? STYLES.passed : STYLES.failed;+const isCombinator = ["AND", "OR", "NOT"].includes(type);// Use groupCollapsed for conditions with children, log for others@@ -412,19 +484,23 @@ class BlockDebugLogger {args ? `(${args})` : "");} else {- // Condition type has no special formatting+ // Condition type has no special formatting. `args` is always a record+ // (or absent) here — a combinator's string/null `args` was handled above.+ const argsRecord = args as Record<string, unknown> | null | undefined;+// Use formatted object if provided, otherwise add actual to argsconst hasResolved = resolvedValue?.hasValue;- let loggedArgs;- if (hasResolved && resolvedValue.formatted) {+ let loggedArgs: unknown;+ if (hasResolved && resolvedValue?.formatted) {loggedArgs = resolvedValue.formatted;} else if (hasResolved) {loggedArgs =- args && Object.keys(args).length > 0- ? { ...args, actual: resolvedValue.value }- : { actual: resolvedValue.value };+ argsRecord && Object.keys(argsRecord).length > 0+ ? { ...argsRecord, actual: resolvedValue?.value }+ : { actual: resolvedValue?.value };} else {- loggedArgs = args && Object.keys(args).length > 0 ? args : "";+ loggedArgs =+ argsRecord && Object.keys(argsRecord).length > 0 ? argsRecord : "";}// Display warning note if present (e.g., unknown setting names)@@ -446,12 +522,17 @@ class BlockDebugLogger {/*** Log a single param match with optional type mismatch hint.*- * @param {Object} match - The match object with configured (expected), actual, result.- * @param {string} label - Display label for the param.- * @param {string} icon - Pass/fail icon.- * @param {string} iconStyle - CSS style for the icon.+ * @param match - The match object with configured (expected), actual, result.+ * @param label - Display label for the param.+ * @param icon - Pass/fail icon.+ * @param iconStyle - CSS style for the icon.*/- #logParamMatch(match, label, icon, iconStyle) {+ #logParamMatch(+ match: ParamMatch,+ label: string,+ icon: string,+ iconStyle: string+ ): void {const { expected: configured, actual, result } = match;// Check for type mismatch on failed matches@@ -476,12 +557,13 @@ class BlockDebugLogger {* Get the type of value configured in the condition, unwrapping `{ any: [...] }` and arrays.* Shows all unique types if mixed (e.g., "number/string").*- * @param {*} expected - The configured value spec from the condition.- * @returns {string} The type description.+ * @returns The type description.*/- #getExpectedValueType(expected) {+ #getExpectedValueType(expected: unknown): string {// Unwrap { any: [...] } or arrays- const values = expected?.any ?? (Array.isArray(expected) ? expected : null);+ const values =+ (expected as { any?: unknown[] } | null)?.any ??+ (Array.isArray(expected) ? expected : null);if (values && values.length > 0) {const types = [...new Set(values.map((v) => typeof v))];@@ -493,12 +575,12 @@ class BlockDebugLogger {/*** Log a standalone condition (when no group is active).- *- * @param {string} type - Condition type- * @param {Object} args - Condition arguments- * @param {boolean} result - Pass/fail*/- #logStandalone(type, args, result) {+ #logStandalone(+ type: string,+ args: string | Record<string, unknown> | null | undefined,+ result: boolean | null+ ): void {const icon = result ? ICONS.passed : ICONS.failed;// eslint-disable-next-line no-consoleconsole.debug(`[Blocks] ${icon} ${type}:`, args);@@ -509,11 +591,15 @@ class BlockDebugLogger {* Uses standalone log (no group needed since there are no conditions to show).* Format matches endGroup header: `[Blocks] ✗ SKIPPED {displayName} in {hierarchy}`*- * @param {string} blockName - The name of the missing optional block.- * @param {string|null} blockId - The block's unique ID, or null if not set.- * @param {string} hierarchy - The outlet/container hierarchy path.+ * @param blockName - The name of the missing optional block.+ * @param blockId - The block's unique ID, or null if not set.+ * @param hierarchy - The outlet/container hierarchy path.*/- logOptionalMissing(blockName, blockId, hierarchy) {+ logOptionalMissing(+ blockName: string,+ blockId: string | null,+ hierarchy: string+ ): void {// Format display name with ID if availableconst displayName = blockId ? `${blockName}(#${blockId})` : blockName;@@ -530,10 +616,8 @@ class BlockDebugLogger {/*** Check if a group is currently active.- *- * @returns {boolean}*/- hasActiveGroup() {+ hasActiveGroup(): boolean {return this.#currentGroup !== null;}}diff --git a/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gjs b/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gtssimilarity index 79%rename from frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gjsrename to frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gtsindex e91daf6a657..e08a0f7f42a 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gjs+++ b/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gts@@ -1,28 +1,38 @@-// @ts-checkimport Component from "@glimmer/component";import { array, hash } from "@ember/helper";import DTooltip from "discourse/float-kit/components/d-tooltip";import { FAILURE_TYPE } from "discourse/lib/blocks/-internals/patterns";+import type {+ BlockComponent,+ BlockEntry,+} from "discourse/lib/blocks/-internals/types";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";import ArgsTable from "../shared/args-table";import ConditionsTree from "./conditions-tree";-/**- * Component signature for GhostBlock.- *- * @typedef {Object} GhostBlockSignature- * @property {Object} Args- * @property {string} Args.blockName - The name of the hidden block.- * @property {string} [Args.blockId] - The block's unique ID (if set).- * @property {string} Args.debugLocation - The hierarchy path where the block would render.- * @property {Object} [Args.blockArgs] - Arguments that would have been passed to the block.- * @property {Object} [Args.containerArgs] - Container arguments from parent container's childArgs.- * @property {Object} [Args.conditions] - Conditions that failed evaluation.- * @property {string} [Args.failureType] - The failure type constant (FAILURE_TYPE value).- * @property {string} [Args.failureReason] - Optional custom display message (overrides type-based default).- * @property {Array<{Component: import("@glint/template").ComponentLike}>} [Args.children] - Nested ghost children for containers.- */+interface GhostBlockSignature {+ Args: {+ /** The name of the hidden block. */+ blockName: string;+ /** The block's unique ID (if set). */+ blockId?: string;+ /** The hierarchy path where the block would render. */+ debugLocation: string;+ /** Arguments that would have been passed to the block. */+ blockArgs?: Record<string, unknown>;+ /** Container arguments from parent container's childArgs. */+ containerArgs?: Record<string, unknown>;+ /** Conditions that failed evaluation. */+ conditions?: BlockEntry["conditions"];+ /** The failure type constant (a `FAILURE_TYPE` value). */+ failureType?: string;+ /** Optional custom display message (overrides type-based default). */+ failureReason?: string;+ /** Nested ghost children for containers. */+ children?: Array<{ Component: BlockComponent }> | null;+ };+}/*** Ghost placeholder for blocks that are hidden.@@ -36,18 +46,16 @@ import ConditionsTree from "./conditions-tree";** For container blocks hidden due to no visible children, nested ghost children* are rendered inside to show the full block tree structure.- *- * @extends {Component<GhostBlockSignature>}*/-export default class GhostBlock extends Component {+export default class GhostBlock extends Component<GhostBlockSignature> {/*** Returns the appropriate hint message based on why the block is hidden.* If a custom `failureReason` is provided, it is displayed directly.* Otherwise, a default message is generated based on the `failureType`.*- * @returns {string} The hint message to display.+ * @returns The hint message to display.*/- get hintMessage() {+ get hintMessage(): string {if (this.args.failureReason) {return this.args.failureReason;}@@ -63,9 +71,9 @@ export default class GhostBlock extends Component {/*** Returns the section title for the status/conditions section.*- * @returns {string} Either "Status" or "Conditions".+ * @returns Either "Status" or "Conditions".*/- get sectionTitle() {+ get sectionTitle(): string {if (this.args.failureType === FAILURE_TYPE.OPTIONAL_MISSING ||this.args.failureType === FAILURE_TYPE.NO_VISIBLE_CHILDREN ||@@ -79,9 +87,9 @@ export default class GhostBlock extends Component {/*** Returns the status text shown in parentheses.*- * @returns {string} The status text (e.g., "not registered", "failed").+ * @returns The status text (e.g., "not registered", "failed").*/- get statusText() {+ get statusText(): string {if (this.args.failureType === FAILURE_TYPE.OPTIONAL_MISSING) {return i18n("js.blocks.ghost.not_registered");}@@ -99,9 +107,9 @@ export default class GhostBlock extends Component {* Only shown when conditions actually failed (not for optional missing,* no visible children, or custom reason).*- * @returns {boolean} True if conditions tree should be rendered.+ * @returns True if conditions tree should be rendered.*/- get showConditionsTree() {+ get showConditionsTree(): boolean {return (this.args.failureType !== FAILURE_TYPE.OPTIONAL_MISSING &&this.args.failureType !== FAILURE_TYPE.NO_VISIBLE_CHILDREN &&@@ -112,10 +120,10 @@ export default class GhostBlock extends Component {/*** Checks if an args object has any entries.*- * @param {Object} args - The arguments object to check.- * @returns {boolean} True if args is non-null and has at least one key.+ * @param args - The arguments object to check.+ * @returns True if args is non-null and has at least one key.*/- hasArgs(args) {+ hasArgs(args: Record<string, unknown> | undefined): boolean {return args != null && Object.keys(args).length > 0;}@@ -123,9 +131,9 @@ export default class GhostBlock extends Component {* Returns the display name for the block, including ID if set.* Format: "blockName" or "blockName(#id)".*- * @returns {string} The display name.+ * @returns The display name.*/- get displayName() {+ get displayName(): string {if (this.args.blockId) {return `${this.args.blockName}(#${this.args.blockId})`;}diff --git a/frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gjs b/frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gtssimilarity index 81%rename from frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gjsrename to frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gtsindex fdfcb1ddee8..ea9ab98345e 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gjs+++ b/frontend/discourse/app/static/dev-tools/block-debug/outlet-info.gts@@ -1,4 +1,3 @@-// @ts-checkimport Component from "@glimmer/component";import { array, hash } from "@ember/helper";import DTooltip from "discourse/float-kit/components/d-tooltip";@@ -7,32 +6,34 @@ import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import ArgsTable from "../shared/args-table";-/**- * Component signature for OutletInfo.- *- * @typedef {Object} OutletInfoSignature- * @property {Object} Args- * @property {string} Args.outletName - The name of the block outlet.- * @property {number} Args.blockCount - Number of blocks registered.- * @property {Object} [Args.outletArgs] - Arguments passed to the outlet.- * @property {Error} [Args.error] - Validation error if config failed.- * @property {Object} Blocks- * @property {[]} Blocks.default - Default block for rendering children.- */+interface OutletInfoSignature {+ Args: {+ /** The name of the block outlet. */+ outletName: string;+ /** Number of blocks registered. */+ blockCount: number;+ /** Arguments passed to the outlet. */+ outletArgs?: Record<string, unknown>;+ /** Validation error if config failed. */+ error?: Error | null;+ };+ Blocks: {+ /** Default block for rendering children. */+ default: [];+ };+}/*** Debug overlay for BlockOutlet components.* Shows outlet name badge with a tooltip containing outlet info and GitHub search link.- *- * @extends {Component<OutletInfoSignature>}*/-export default class OutletInfo extends Component {+export default class OutletInfo extends Component<OutletInfoSignature> {/*** Returns a human-readable label for the block count.*- * @returns {string} "1 block" for singular, "{n} blocks" for plural.+ * @returns "1 block" for singular, "N blocks" for plural.*/- get blockLabel() {+ get blockLabel(): string {const count = this.args.blockCount;return count === 1 ? "1 block" : `${count} blocks`;}@@ -41,9 +42,9 @@ export default class OutletInfo extends Component {* Cleans up the error message for display in the popup.* Removes the "[Blocks]" prefix while preserving formatted structure.*- * @returns {string} The cleaned error message.+ * @returns The cleaned error message.*/- get errorMessage() {+ get errorMessage(): string {let message = this.args.error?.message ?? "Unknown validation error";// Remove "[Blocks]" prefix that's added for console logging@@ -55,11 +56,13 @@ export default class OutletInfo extends Component {/*** Checks whether this outlet has any args passed to it.*- * @returns {boolean} True if outlet has at least one arg.+ * @returns True if outlet has at least one arg.*/- get hasOutletArgs() {+ get hasOutletArgs(): boolean {const outletArgs = this.args.outletArgs;- const deprecatedArgs = outletArgs?.[DEPRECATED_ARGS_KEY];+ const deprecatedArgs = outletArgs?.[DEPRECATED_ARGS_KEY] as+ | Record<string, unknown>+ | undefined;return ((outletArgs != null && Object.keys(outletArgs).length > 0) ||diff --git a/frontend/discourse/app/static/dev-tools/block-debug/patch.js b/frontend/discourse/app/static/dev-tools/block-debug/patch.tssimilarity index 50%rename from frontend/discourse/app/static/dev-tools/block-debug/patch.jsrename to frontend/discourse/app/static/dev-tools/block-debug/patch.tsindex 0d5d0b99c34..f0baf31656e 100644--- a/frontend/discourse/app/static/dev-tools/block-debug/patch.js+++ b/frontend/discourse/app/static/dev-tools/block-debug/patch.ts@@ -1,15 +1,24 @@-// @ts-check+import type Owner from "@ember/owner";import curryComponent from "ember-curry-component";import {DEBUG_CALLBACK,+ type DebugGhostBlockData,+ type DebugGhostContext,+ type DebugGhostData,debugHooks,} from "discourse/lib/blocks/-internals/debug-hooks";import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";import {FAILURE_TYPE,+ isOptionalMissing,MAX_LAYOUT_DEPTH,- OPTIONAL_MISSING,+ type OptionalMissingMarker,} from "discourse/lib/blocks/-internals/patterns";+import type {+ BlockClass,+ BlockComponent,+ BlockEntry,+} from "discourse/lib/blocks/-internals/types";import { getOwnerWithFallback } from "discourse/lib/get-owner";import devToolsState from "../state";import BlockInfo from "./block-info";@@ -17,17 +26,39 @@ import { blockDebugLogger } from "./debug-logger";import GhostBlock from "./ghost-block";import OutletInfo from "./outlet-info";+/**+ * A function that resolves a block reference (string name or class) to a+ * block class, an optional-missing marker, or null when unresolved. Matches+ * the real contract of `tryResolveBlock()`, the only implementation ever+ * passed in (see `entry-processing.ts`).+ */+type ResolveBlockFn = (+ blockRef: string | BlockClass+) => BlockClass | OptionalMissingMarker | null;++/**+ * The block data passed to the BLOCK_DEBUG callback: `DebugGhostBlockData`+ * plus the fields every caller (the render pipeline and `createDebugGhost()`)+ * always adds on top before invoking the callback.+ */+interface BlockDebugCallbackData extends DebugGhostBlockData {+ Component: BlockComponent | null;+ conditionsPassed: boolean;+}+/*** Creates a wrapper callback that only executes when block debug is enabled.** This factory eliminates the repeated `if (devToolsState.blockDebug)` checks* across all logging callbacks.*- * @param {Function} fn - The callback function to wrap.- * @returns {Function} A wrapper that calls `fn` only when debug is enabled.+ * @param fn - The callback function to wrap.+ * @returns A wrapper that calls `fn` only when debug is enabled.*/-function makeDebugCallback(fn) {- return (...args) => {+function makeDebugCallback<Args extends unknown[]>(+ fn: (...args: Args) => void+): (...args: Args) => void {+ return (...args: Args) => {if (devToolsState.blockDebug) {fn(...args);}@@ -45,38 +76,38 @@ function makeDebugCallback(fn) {* protection is validation-time depth checking in `validateLayout`, but this* provides additional safety during ghost rendering.*- * @param {Array<Object>} childEntries - Child layout entries (already preprocessed with __visible and __failureType)- * @param {import("@ember/owner").default} owner - The application owner- * @param {string} containerPath - The container's hierarchy path (e.g., "outlet/group[0]")- * @param {Object} outletArgs - Outlet arguments for context- * @param {boolean} isLoggingEnabled - Whether logging is enabled (unused, kept for API compatibility)- * @param {Function} resolveBlockFn - Function to resolve block references to classes- * @param {number} [depth=0] - Current nesting depth for recursion limit checking.- * @returns {Array<{Component: import("@glint/template").ComponentLike, isGhost?: boolean, asGhost?: Function}>} Array of ghost component data+ * @param childEntries - Child layout entries (already preprocessed with __visible and __failureType)+ * @param owner - The application owner+ * @param containerPath - The container's hierarchy path (e.g., "outlet/group[0]")+ * @param outletArgs - Outlet arguments for context+ * @param isLoggingEnabled - Whether logging is enabled (unused, kept for API compatibility)+ * @param resolveBlockFn - Function to resolve block references to classes+ * @param depth - Current nesting depth for recursion limit checking.+ * @returns Array of ghost component data*/function createGhostChildren(- childEntries,- owner,- containerPath,- outletArgs,- isLoggingEnabled,- resolveBlockFn,+ childEntries: BlockEntry[],+ owner: Owner,+ containerPath: string,+ outletArgs: Record<string, unknown> | undefined,+ isLoggingEnabled: boolean,+ resolveBlockFn: ResolveBlockFn,depth = 0-) {+): DebugGhostData[] {// Defense-in-depth: silently stop recursion if depth exceeds limit.// Primary validation happens at layout validation time in validateLayout().if (depth >= MAX_LAYOUT_DEPTH) {return [];}- const result = [];- const containerCounts = new Map();+ const result: DebugGhostData[] = [];+ const containerCounts = new Map<string, number>();for (const childEntry of childEntries) {const resolvedBlock = resolveBlockFn(childEntry.block);// Handle optional missing block- if (resolvedBlock?.optionalMissing === OPTIONAL_MISSING) {+ if (isOptionalMissing(resolvedBlock)) {const ghostData = debugHooks.getCallback(DEBUG_CALLBACK.BLOCK_DEBUG)?.({name: resolvedBlock.name,@@ -89,7 +120,7 @@ function createGhostChildren(failureType: FAILURE_TYPE.OPTIONAL_MISSING,},{ outletName: containerPath }- );+ ) as DebugGhostData | undefined;if (ghostData?.Component) {result.push(ghostData);}@@ -107,7 +138,7 @@ function createGhostChildren(// Build container path for nested containers.// Use id if available (unique), otherwise fall back to index.- let nestedContainerPath;+ let nestedContainerPath: string | undefined;if (isChildContainer) {const count = containerCounts.get(blockName) ?? 0;containerCounts.set(blockName, count + 1);@@ -116,7 +147,7 @@ function createGhostChildren(}// Recursively create ghost children for nested containers- let nestedGhostChildren = null;+ let nestedGhostChildren: DebugGhostData[] | null = null;if (isChildContainer &&childEntry.children?.length &&@@ -125,7 +156,8 @@ function createGhostChildren(nestedGhostChildren = createGhostChildren(childEntry.children,owner,- nestedContainerPath,+ // `isChildContainer` guarantees this was set above.+ nestedContainerPath as string,outletArgs,isLoggingEnabled,resolveBlockFn,@@ -147,7 +179,7 @@ function createGhostChildren(children: nestedGhostChildren,},{ outletName: containerPath }- );+ ) as DebugGhostData | undefined;if (ghostData?.Component) {result.push(ghostData);}@@ -166,41 +198,79 @@ function createGhostChildren(* Uses devToolsState via closure to check state at invocation time,* following the same pattern as plugin-outlet-debug.*/-export function patchBlockRendering() {+export function patchBlockRendering(): void {// Callback for visual overlay and ghost blocks - wraps blocks with debug info- debugHooks.setCallback(DEBUG_CALLBACK.BLOCK_DEBUG, (blockData, context) => {- const showVisualOverlay = devToolsState.blockVisualOverlay;- const showGhostBlocks = devToolsState.blockGhostBlocks;+ debugHooks.setCallback(+ DEBUG_CALLBACK.BLOCK_DEBUG,+ (blockData: BlockDebugCallbackData, context: DebugGhostContext) => {+ const showVisualOverlay = devToolsState.blockVisualOverlay;+ const showGhostBlocks = devToolsState.blockGhostBlocks;- // Check state at invocation time (devToolsState is captured in closure)- if (!showVisualOverlay && !showGhostBlocks) {- return blockData;- }+ // Check state at invocation time (devToolsState is captured in closure)+ if (!showVisualOverlay && !showGhostBlocks) {+ return blockData;+ }++ const {+ name,+ id,+ Component,+ args,+ containerArgs,+ conditions,+ conditionsPassed,+ failureType,+ failureReason,+ children,+ } = blockData;+ const { outletName } = context;+ const owner = getOwnerWithFallback() as Owner;++ // If conditions failed, return a ghost block (if ghost blocks enabled)+ if (conditionsPassed === false) {+ if (!showGhostBlocks) {+ return blockData;+ }++ // Not typed as `DebugGhostData`/`ChildBlockResult`: this object is+ // self-referential (`asGhost` returns itself), and it's missing the+ // `key` that `ChildBlockResult` requires — the caller (`createGhostBlock()`+ // / `handleOptionalMissingBlock()`) attaches `key` after this callback+ // returns. Left for TS to infer structurally, same as the block-outlet+ // module's equivalent (real, keyed) ghost-of-a-ghost pattern.+ const ghostResult = {+ Component: curryComponent(+ GhostBlock,+ {+ blockName: name,+ blockId: id,+ // Use debugLocation to avoid being overwritten by template's @outletName+ debugLocation: outletName,+ blockArgs: args,+ containerArgs,+ conditions,+ failureType,+ failureReason,+ // Children are ghost components for container blocks with no visible children+ children,+ },+ owner+ ) as BlockComponent,+ isGhost: true,+ // No-op: calling asGhost on a ghost returns itself+ asGhost: () => ghostResult,+ };+ return ghostResult;+ }- const {- name,- id,- Component,- args,- containerArgs,- conditions,- conditionsPassed,- failureType,- failureReason,- children,- } = blockData;- const { outletName } = context;- const owner = getOwnerWithFallback();-- // If conditions failed, return a ghost block (if ghost blocks enabled)- if (conditionsPassed === false) {- if (!showGhostBlocks) {+ // Wrap the rendered block with debug info (if visual overlay enabled)+ if (!showVisualOverlay) {return blockData;}- const ghostResult = {+ return {Component: curryComponent(- GhostBlock,+ BlockInfo,{blockName: name,blockId: id,@@ -209,43 +279,14 @@ export function patchBlockRendering() {blockArgs: args,containerArgs,conditions,- failureType,- failureReason,- // Children are ghost components for container blocks with no visible children- children,+ outletArgs: context.outletArgs,+ WrappedComponent: Component,},owner- ),- isGhost: true,- // No-op: calling asGhost on a ghost returns itself- asGhost: () => ghostResult,+ ) as BlockComponent,};- return ghostResult;- }-- // Wrap the rendered block with debug info (if visual overlay enabled)- if (!showVisualOverlay) {- return blockData;}-- return {- Component: curryComponent(- BlockInfo,- {- blockName: name,- blockId: id,- // Use debugLocation to avoid being overwritten by template's @outletName- debugLocation: outletName,- blockArgs: args,- containerArgs,- conditions,- outletArgs: context.outletArgs,- WrappedComponent: Component,- },- owner- ),- };- });+ );// Callback for console loggingdebugHooks.setCallback(@@ -267,70 +308,87 @@ export function patchBlockRendering() {devToolsState.blockOutletBoundaries ? OutletInfo : null);- // === Logging Callbacks ===+ /* Logging Callbacks */// These bridge the main bundle to the debug logger in dev-tools.// All use makeDebugCallback to centralize the devToolsState.blockDebug check.// Callback for logging condition evaluationsdebugHooks.setCallback(DEBUG_CALLBACK.CONDITION_LOG,- makeDebugCallback((opts) => {- blockDebugLogger.logCondition(opts);- })+ makeDebugCallback(+ (opts: Parameters<typeof blockDebugLogger.logCondition>[0]) => {+ blockDebugLogger.logCondition(opts);+ }+ ));// Callback for updating combinator (AND/OR/NOT) resultsdebugHooks.setCallback(DEBUG_CALLBACK.COMBINATOR_LOG,- makeDebugCallback((opts) => {- blockDebugLogger.updateCombinatorResult(opts.conditionSpec, opts.result);- })+ makeDebugCallback(+ (opts: { conditionSpec: object | null | undefined; result: boolean }) => {+ blockDebugLogger.updateCombinatorResult(+ opts.conditionSpec,+ opts.result+ );+ }+ ));// Callback for updating single condition resultsdebugHooks.setCallback(DEBUG_CALLBACK.CONDITION_RESULT,- makeDebugCallback((opts) => {- blockDebugLogger.updateConditionResult(opts.conditionSpec, opts.result);- })+ makeDebugCallback(+ (opts: { conditionSpec: object | null | undefined; result: boolean }) => {+ blockDebugLogger.updateConditionResult(opts.conditionSpec, opts.result);+ }+ ));// Callback for logging param group matchesdebugHooks.setCallback(DEBUG_CALLBACK.PARAM_GROUP_LOG,- makeDebugCallback((opts) => {- blockDebugLogger.logParamGroup(opts);- })+ makeDebugCallback(+ (opts: Parameters<typeof blockDebugLogger.logParamGroup>[0]) => {+ blockDebugLogger.logParamGroup(opts);+ }+ ));// Callback for logging route statedebugHooks.setCallback(DEBUG_CALLBACK.ROUTE_STATE_LOG,- makeDebugCallback((opts) => {- blockDebugLogger.logRouteState(opts);- })+ makeDebugCallback(+ (opts: Parameters<typeof blockDebugLogger.logRouteState>[0]) => {+ blockDebugLogger.logRouteState(opts);+ }+ ));// Callback for logging optional missing blocksdebugHooks.setCallback(DEBUG_CALLBACK.OPTIONAL_MISSING_LOG,- makeDebugCallback((blockName, blockId, hierarchy) => {- blockDebugLogger.logOptionalMissing(blockName, blockId, hierarchy);- })+ makeDebugCallback(+ (blockName: string, blockId: string | null, hierarchy: string) => {+ blockDebugLogger.logOptionalMissing(blockName, blockId, hierarchy);+ }+ ));// Callback for starting a logging groupdebugHooks.setCallback(DEBUG_CALLBACK.START_GROUP,- makeDebugCallback((blockName, blockId, hierarchy) => {- blockDebugLogger.startGroup(blockName, blockId, hierarchy);- })+ makeDebugCallback(+ (blockName: string, blockId: string | null, hierarchy: string) => {+ blockDebugLogger.startGroup(blockName, blockId, hierarchy);+ }+ ));// Callback for ending a logging groupdebugHooks.setCallback(DEBUG_CALLBACK.END_GROUP,- makeDebugCallback((finalResult) => {+ makeDebugCallback((finalResult: boolean) => {blockDebugLogger.endGroup(finalResult);}));@@ -341,13 +399,23 @@ export function patchBlockRendering() {return null;}return {- logCondition: (opts) => blockDebugLogger.logCondition(opts),- updateCombinatorResult: (conditionSpec, result) =>- blockDebugLogger.updateCombinatorResult(conditionSpec, result),- updateConditionResult: (conditionSpec, result) =>- blockDebugLogger.updateConditionResult(conditionSpec, result),- logParamGroup: (opts) => blockDebugLogger.logParamGroup(opts),- logRouteState: (opts) => blockDebugLogger.logRouteState(opts),+ logCondition: (+ opts: Parameters<typeof blockDebugLogger.logCondition>[0]+ ) => blockDebugLogger.logCondition(opts),+ updateCombinatorResult: (+ conditionSpec: object | null | undefined,+ result: boolean+ ) => blockDebugLogger.updateCombinatorResult(conditionSpec, result),+ updateConditionResult: (+ conditionSpec: object | null | undefined,+ result: boolean+ ) => blockDebugLogger.updateConditionResult(conditionSpec, result),+ logParamGroup: (+ opts: Parameters<typeof blockDebugLogger.logParamGroup>[0]+ ) => blockDebugLogger.logParamGroup(opts),+ logRouteState: (+ opts: Parameters<typeof blockDebugLogger.logRouteState>[0]+ ) => blockDebugLogger.logRouteState(opts),};});diff --git a/frontend/discourse/package.json b/frontend/discourse/package.jsonindex eade6dc35cc..96b65b918fe 100644--- a/frontend/discourse/package.json+++ b/frontend/discourse/package.json@@ -128,6 +128,7 @@"@rolldown/pluginutils": "1.0.1","@rollup/plugin-babel": "^7.1.0","@types/jquery": "^3.5.33",+ "@types/picomatch": "^4.0.3","@types/qunit": "^2.19.13","@types/rsvp": "^4.0.9","@types/sinon": "^21.0.1",diff --git a/frontend/discourse/tests/unit/blocks/conditions/decorator-test.js b/frontend/discourse/tests/unit/blocks/conditions/decorator-test.jsindex 6150de7704a..d795f16d8b1 100644--- a/frontend/discourse/tests/unit/blocks/conditions/decorator-test.js+++ b/frontend/discourse/tests/unit/blocks/conditions/decorator-test.js@@ -24,6 +24,29 @@ module("Unit | Blocks | Conditions | decorator", function () {);});+ test("functional invocation returns the decorated class", function (assert) {+ class TestCondition extends BlockCondition {+ evaluate() {+ return true;+ }+ }++ const Decorated = blockCondition({ type: "functional-return" })(+ TestCondition+ );++ assert.strictEqual(+ Decorated,+ TestCondition,+ "the decorator returns the class it decorated"+ );+ assert.strictEqual(+ Decorated.type,+ "functional-return",+ "the returned class carries the condition statics"+ );+ });+test("defaults to empty args object when not provided", function (assert) {@blockCondition({type: "test-no-args",diff --git a/frontend/discourse/tests/unit/lib/blocks/core/decorator-test.js b/frontend/discourse/tests/unit/lib/blocks/core/decorator-test.jsnew file mode 100644index 00000000000..f6edb16dfa4--- /dev/null+++ b/frontend/discourse/tests/unit/lib/blocks/core/decorator-test.js@@ -0,0 +1,27 @@+import Component from "@glimmer/component";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { block } from "discourse/blocks";+import { getBlockMetadata } from "discourse/lib/blocks/-internals/decorator";++module("Unit | Lib | blocks/core/decorator", function (hooks) {+ setupTest(hooks);++ test("functional invocation returns the decorated class", function (assert) {+ // eslint-disable-next-line ember/no-empty-glimmer-component-classes+ class TestBlock extends Component {}++ const Decorated = block("functional-return-block")(TestBlock);++ assert.strictEqual(+ Decorated,+ TestBlock,+ "the decorator returns the class it decorated"+ );+ assert.strictEqual(+ getBlockMetadata(Decorated).blockName,+ "functional-return-block",+ "the returned class carries the block metadata"+ );+ });+});diff --git a/frontend/discourse/tests/unit/lib/blocks/core/registration-test.js b/frontend/discourse/tests/unit/lib/blocks/core/registration-test.jsindex 88043e85685..37099cfa4a9 100644--- a/frontend/discourse/tests/unit/lib/blocks/core/registration-test.js+++ b/frontend/discourse/tests/unit/lib/blocks/core/registration-test.js@@ -67,6 +67,23 @@ module("Unit | Lib | blocks/core/registration", function (hooks) {);});+ test("throws the decorator error for a missing class", function (assert) {+ // A bad or circular import hands `undefined` to `api.registerBlock()`.+ // That must surface the actionable decorator message, not a raw+ // property-access failure from an uncaught TypeError.+ assert.throws(+ () => _registerBlock(undefined),+ /must be decorated with @block/+ );+ });++ test("throws the decorator error for a null class", function (assert) {+ assert.throws(+ () => _registerBlock(null),+ /must be decorated with @block/+ );+ });+test("throws for duplicate block name", function (assert) {@block("duplicate-block")class FirstBlock extends Component {}@@ -329,6 +346,27 @@ module("Unit | Lib | blocks/core/registration", function (hooks) {);});+ test("reports a missing return value as an invalid factory result", async function (assert) {+ // A factory that forgets to return anything resolves to `undefined`; it+ // must still produce the actionable "invalid factory result" message+ // rather than surfacing a raw property-access failure.+ _registerBlockFactory("empty-factory", async () => {});++ await assert.rejects(+ resolveBlock("empty-factory"),+ /did not return a valid @block-decorated class/+ );+ });++ test("reports a null return value as an invalid factory result", async function (assert) {+ _registerBlockFactory("null-factory", async () => null);++ await assert.rejects(+ resolveBlock("null-factory"),+ /did not return a valid @block-decorated class/+ );+ });+test("throws if factory returns block with mismatched name", async function (assert) {@block("actual-name")class MismatchedBlock extends Component {}diff --git a/frontend/discourse/tests/unit/lib/blocks/validation/layout-test.js b/frontend/discourse/tests/unit/lib/blocks/validation/layout-test.jsindex 72976be366b..49f31fdbdee 100644--- a/frontend/discourse/tests/unit/lib/blocks/validation/layout-test.js+++ b/frontend/discourse/tests/unit/lib/blocks/validation/layout-test.js@@ -5,6 +5,7 @@ import {} from "discourse/lib/blocks/-internals/validation/args";import {VALID_ENTRY_KEYS,+ validateEntry,validateEntryIdFormat,validateEntryKeys,validateEntryTypes,@@ -47,6 +48,18 @@ module("Unit | Lib | blocks/validation/layout", function () {});});+ module("validateEntry", function () {+ test("primitive block reference raises the decorator validation error", async function (assert) {+ await assert.rejects(+ validateEntry({ block: 42 }, "hero-blocks", undefined, "layout[0]"),+ (error) =>+ error.message.includes("is not a valid @block-decorated component") &&+ error.message.includes("layout[0]"),+ "an entry whose block is a truthy primitive gets the actionable validation error, not a raw TypeError"+ );+ });+ });+module("validateEntryKeys", function () {test("passes validation for entry with all valid keys", function (assert) {const config = {diff --git a/frontend/discourse/type-tests/blocks/public-api-test.ts b/frontend/discourse/type-tests/blocks/public-api-test.tsnew file mode 100644index 00000000000..e9007c924c0--- /dev/null+++ b/frontend/discourse/type-tests/blocks/public-api-test.ts@@ -0,0 +1,54 @@+import Component from "@glimmer/component";+import { expectTypeOf } from "expect-type";+import {+ type ArgSchema,+ type ArgType,+ block,+ type BlockClassNames,+ BlockCondition,+ type BlockConstraints,+ type BlockMetadata,+ type BlockNamespaceType,+ type BlockOptions,+ type BlockValidateFn,+ type ChildArgSchema,+ type LayoutEntry,+} from "discourse/blocks";+import { blockCondition } from "discourse/blocks/conditions";++// The author-facing types must be importable from the documented public entry+// point (`discourse/blocks`), not just from the internal types module.+expectTypeOf<ArgSchema>().not.toBeAny();+expectTypeOf<ArgType>().not.toBeAny();+expectTypeOf<BlockClassNames>().not.toBeAny();+expectTypeOf<BlockConstraints>().not.toBeAny();+expectTypeOf<BlockMetadata>().not.toBeAny();+expectTypeOf<BlockNamespaceType>().not.toBeAny();+expectTypeOf<BlockOptions>().not.toBeAny();+expectTypeOf<BlockValidateFn>().not.toBeAny();+expectTypeOf<ChildArgSchema>().not.toBeAny();+expectTypeOf<LayoutEntry>().not.toBeAny();++// Spot-check the shapes typed plugins depend on.+expectTypeOf<LayoutEntry["block"]>().not.toBeAny();+expectTypeOf<BlockOptions["container"]>().toEqualTypeOf<boolean | undefined>();+expectTypeOf<"string">().toExtend<ArgType>();++// eslint-disable-next-line ember/no-empty-glimmer-component-classes+class ExampleBlock extends Component {}++// Both decorators return the class they decorate, so functional (non-`@`)+// invocation keeps the class identity for plain-JS and typed callers alike.+expectTypeOf(block("example")(ExampleBlock)).toEqualTypeOf<+ typeof ExampleBlock+>();++class ExampleCondition extends BlockCondition {+ evaluate(): boolean {+ return true;+ }+}++expectTypeOf(+ blockCondition({ type: "example" })(ExampleCondition)+).toEqualTypeOf<typeof ExampleCondition>();diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ae4c13ce058..14c13ed9298 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -508,6 +508,9 @@ importers:'@types/jquery':specifier: ^3.5.33version: 3.5.33+ '@types/picomatch':+ specifier: ^4.0.3+ version: 4.0.3'@types/qunit':specifier: ^2.19.13version: 2.19.13@@ -2954,6 +2957,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-iG0T6+nYJ9FAPmx9SsUlnwcq1ZVRuCXcVEvWnntoPlrOpwtSTKNDC9uVAxTsC3PUvJ+99n4RpAcNgBbHX3JSnQ==}+'@types/[email protected]':resolution: {integrity: sha512-N4xp3v4s7f0jb2Oij6+6xw5QhH7/IgHCoGIFLCWtbEWoPkGYp8Te4mIwIP21qaurr6ed5JiPMiy2/ZoiGPkLIw==}@@ -10885,6 +10891,8 @@ snapshots:dependencies:undici-types: 7.24.6+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}