A platform for community discussion. Free, open, simple.
DEV: Type-check core, plugins and themes under strict mode (#44400)
Sérgio Saquetim69dea4ad2b92
diff --git a/.skills/discourse-writing-typescript/SKILL.md b/.skills/discourse-writing-typescript/SKILL.mdindex faf9fe6fa27..9695f93e119 100644--- a/.skills/discourse-writing-typescript/SKILL.md+++ b/.skills/discourse-writing-typescript/SKILL.md@@ -1,6 +1,6 @@---name: discourse-writing-typescript-description: Write TypeScript for Discourse core, plugins, and themes. Use when authoring new .ts/.gts files (components, modifiers, helpers, services, utils), typing an existing public API, or converting existing .js/.gjs files to .ts/.gts. Covers the component/modifier/plain-class Signature patterns, TSDoc for Signatures, typing untyped dependencies, compile-time type tests, the strict-grade bar under the loose global tsconfig, and the faithful-port and rename pitfalls that the type-checker does NOT catch.+description: Write TypeScript for Discourse core, plugins, and themes. Use when authoring new .ts/.gts files (components, modifiers, helpers, services, utils), typing an existing public API, or converting existing .js/.gjs files to .ts/.gts. Covers the component/modifier/plain-class Signature patterns, TSDoc for Signatures, typing untyped dependencies, compile-time type tests, the `strict` bar enforced by `pnpm lint:types`, and the faithful-port and rename pitfalls that the type-checker does NOT catch.---# Writing TypeScript for Discourse@@ -13,9 +13,12 @@ and[`frontend/discourse/float-kit/components/d-tooltip.gts`](../../frontend/discourse/float-kit/components/d-tooltip.gts)(typed `@service declare` injection, `Element`, several documented `Blocks`, an option bagderived from a shared type); the developer guide is-[`27-types.md`](../../docs/developer-guides/docs/03-code-internals/27-types.md). **The-global tsconfig is deliberately NOT strict** (it extends the repo-root `tsconfig-base.json`,-which sets no `strict` and no `checkJs`); tightening it is a separate, repo-wide effort.+[`27-types.md`](../../docs/developer-guides/docs/03-code-internals/27-types.md).++**`pnpm lint:types` runs under `strict`.** Core's repo-root `tsconfig-base.json` and the+`tsconfig-plugin.json` that plugins and themes extend both set `strict: true`. `checkJs` is+off, so `.js`/`.gjs` files are not checked, but the `@discourse/types` declarations that+`lint:types` emits for them are inferred under `strict` (see golden rule 3).**Converting an existing `.js`/`.gjs` file?** Read[references/js-to-ts-conversion.md](references/js-to-ts-conversion.md) first (the faithful-port@@ -28,12 +31,17 @@ claiming any file or subsystem converted.1. **A conversion is a types-only port.** Types are erased; runtime behavior is not. Neverchange runtime code to satisfy a type. The full rule and the catalogue of changes thatpass `lint:types` but alter behavior are in the conversion reference.-2. **Write strict-grade TS anyway.** The loose global tsconfig is not a licence for- sloppiness. Author as if `strict` were on: **no `any`** (implicit or explicit), **no- `@ts-ignore`/`@ts-nocheck`/`@ts-expect-error`**, no `{{! @glint-nocheck }}`. Proper- `null`/`undefined` handling, real generics, precise `Signature`s. A documented `as` cast- at a genuine DOM or loose-runtime boundary is fine; blanket suppression is not.-3. **Never tighten the global tsconfig** in a feature PR; the blast radius is the whole repo.+2. **Write strict TS.** `pnpm lint:types` fails on what `strict` rejects, such as implicit+ `any`, unhandled `null`/`undefined` and unsound callback parameters. Beyond what it+ checks: **no explicit `any`**, **no `@ts-ignore`/`@ts-nocheck`/`@ts-expect-error`**, no+ `{{! @glint-nocheck }}`. Real narrowing, real generics, precise `Signature`s. A+ documented `as` cast at a genuine DOM or loose-runtime boundary is fine; blanket+ suppression is not.+3. **Type what JavaScript publishes.** Declarations for `.js`/`.gjs` files are inferred+ under `strict`: a field initialized to `null` is published as type `null`, an empty array+ literal often as `never[]`, and a JSDoc `{Object}` as `Object`. These reject the values+ the code really uses, so give such a value in a public class or function a real JSDoc+ type, e.g. `/** @type {number | null} */`.4. **The type-checker is necessary but NOT sufficient.** `pnpm lint:types` green does notmean the code runs. Always also run the tests (see "Verification").5. **A `Signature` is a contract for ALL consumers, across time, not just the type-checked@@ -297,11 +305,6 @@ type), assert them at compile time with `expect-type` (a devDependency of`type-tests/ui-kit/d-drag-and-drop-adoption-test.gts` vs `...-adoption-errors-test.gts`).A short comment at the top of the positives file ("keep this file free of`@glint-expect-error`") stops someone reintroducing one.-- **Non-strict gotchas** (type-level results diverge from the strict mental model): a- `Conditional<null>`/`<undefined>` often resolves to `true` not `false`; a `const`-inferred- object or tuple return carries `readonly`, which `toEqualTypeOf` treats as a mismatch; and- `string | undefined` collapses to `string`. Assert the **robust, real** cases; avoid- `null`/`undefined`-literal and object-return edge assertions that only hold under strict.## Glint directives: avoid in production code@@ -367,9 +370,9 @@ file after `bin/lint --fix`** to confirm the placement still reads well.## Verification (all three, in order)1. `bin/lint --fix <files>`: clean.-2. `pnpm lint:types` from the **repo root** (composite `ember-tsc -b`): **0 errors**. This- is the type gate; it also surfaces consumer fallout when you tighten a previously loose- type (e.g. an untyped helper's return).+2. `pnpm lint:types` from the **repo root** (composite `ember-tsc -b`): **0 errors**. It+ also surfaces consumer fallout when you tighten a previously loose type (e.g. an untyped+ helper's return).3. `bin/qunit` for the touched files' tests: behavior plus the runtime module-resolutioncheck in the conversion reference.diff --git a/.skills/discourse-writing-typescript/references/conversion-completeness.md b/.skills/discourse-writing-typescript/references/conversion-completeness.mdindex 5efdb599700..8ede54d8d84 100644--- a/.skills/discourse-writing-typescript/references/conversion-completeness.md+++ b/.skills/discourse-writing-typescript/references/conversion-completeness.md@@ -13,16 +13,16 @@ subset of checks.across the boundary. Suffix the imported service class binding with `Service`; leave theinjection property and module path unchanged.2. Type public fields, method parameters, and returns precisely. Type private state where- inference would be null-only, empty-collection-only, or otherwise misleading. Do not rely- on the loose repository tsconfig to accept implicit `any`.+ inference would be null-only, empty-collection-only, or otherwise misleading. Do not leave+ implicit `any`: `pnpm lint:types` rejects it.3. Add useful TSDoc to the typed public API: exported type fields, servicefields/methods/parameters, and every component `Signature` arg, block, nested arg field,and yielded tuple value.4. Remove redundant legacy `@param {Type}`, `@returns {Type}`, `@type`, and `@property{Type}` tags. Preserve useful prose as untyped TSDoc tags.-5. Search for bare `@service`, explicit or implicit `any`, suppression directives, stale- typed JSDoc, and undocumented casts. Passing `ember-tsc` does not prove these are absent- under the loose global configuration.+5. Search for explicit `any`, suppression directives, stale typed JSDoc, and undocumented+ casts. `pnpm lint:types` catches implicit `any`, including a bare `@service` in a+ `.ts`/`.gts` file, but not these.6. Inspect each core dependency before defining a local type. Prefer the canonical type,including one inferred from unconverted JavaScript. If a verified runtime field ismissing, use the narrowest extension and a `TODO(typescript-pending)` naming the gap anddiff --git a/docs/developer-guides/docs/03-code-internals/03-lint-and-format.md b/docs/developer-guides/docs/03-code-internals/03-lint-and-format.mdindex 8fdc5413cec..d31fe2c8d61 100644--- a/docs/developer-guides/docs/03-code-internals/03-lint-and-format.md+++ b/docs/developer-guides/docs/03-code-internals/03-lint-and-format.md@@ -108,7 +108,7 @@ When you run `bin/lint` with no file arguments, the full-repo lint also runs:- `pnpm lint:types`-This is the Glint/TypeScript-style check for Discourse's JavaScript type information.+This is the Glint/TypeScript-style check for Discourse's type information. It runs in TypeScript's `strict` mode and also generates the published declarations.> :information_source: `bin/lint path/to/file` and the pre-commit hook do **not** run the full type check. Use plain `bin/lint` when you want the complete repo-wide lint pass.diff --git a/docs/developer-guides/docs/03-code-internals/27-types.md b/docs/developer-guides/docs/03-code-internals/27-types.mdindex 62be9ff970d..c4bbdd893ba 100644--- a/docs/developer-guides/docs/03-code-internals/27-types.md+++ b/docs/developer-guides/docs/03-code-internals/27-types.md@@ -12,6 +12,12 @@ Much of this will be automatically consumed by IDEs with TypeScript/JavaScript sCore, themes and plugins can be authored directly in TypeScript. Use a `.ts` extension for plain modules, or `.gts` for Glimmer components with a `<template>` tag. Type syntax is stripped at build time, so no separate compilation step is required. Linting (`@discourse/lint-configs`) and type-checking (`pnpm lint:types`) both understand these files.+## Strict checking++`pnpm lint:types` runs in TypeScript's `strict` mode, and TypeScript in core and in the bundled plugins and themes must pass it. Plugins and themes outside this repository extend the same config, so they are checked under `strict` too. To opt out, set `"strict": false` in the `compilerOptions` of the plugin's or theme's own `tsconfig.json`.++JavaScript files are not type-checked, but the published `@discourse/types` declarations for them are generated under `strict`. A field initialized to `null` is declared with the type `null`, so give public values like this a JSDoc type such as `/** @type {number | null} */`.+## Type testsTypes whose meaning a runtime test can't capture (a generic's resolved type, an overload pick, a return type derived from arguments) can be asserted at compile time with [`expect-type`](https://github.com/mmkal/expect-type), in `.ts`/`.gts` files under `frontend/discourse/type-tests/` (e.g. `type-tests/truth-helpers/`). They are checked by `pnpm lint:types` but kept out of the test and production bundles.diff --git a/frontend/discourse-types/tsconfig-plugin.json b/frontend/discourse-types/tsconfig-plugin.jsonindex 8bddee11483..b6acc98ef27 100644--- a/frontend/discourse-types/tsconfig-plugin.json+++ b/frontend/discourse-types/tsconfig-plugin.json@@ -7,7 +7,7 @@"experimentalDecorators": true,"allowJs": true,"skipLibCheck": true,- "strict": false,+ "strict": true,"noUncheckedSideEffectImports": false,"noEmit": true,"noEmitOnError": false,diff --git a/frontend/discourse/app/lib/on-before-category-types-change.js b/frontend/discourse/app/lib/on-before-category-types-change.jsindex 8e27eeaf6c0..2c7272161d9 100644--- a/frontend/discourse/app/lib/on-before-category-types-change.js+++ b/frontend/discourse/app/lib/on-before-category-types-change.js@@ -4,11 +4,11 @@ const callbacks = [];/*** @typedef {Object} OnBeforeCategoryTypesChangeContext- * @property {Object[]} nextTypes - Normalized category type objects after the empty-to-discussion rule+ * @property {import("discourse/services/category-type-chooser").CategoryType[]} nextTypes - Normalized category type objects after the empty-to-discussion rule* (id, name, description, icon).- * @property {Object[]} previousTypes - Snapshot of the selection before this change (shallow-copied+ * @property {import("discourse/services/category-type-chooser").CategoryType[]} previousTypes - Snapshot of the selection before this change (shallow-copied* array, same object references as before).- * @property {object} category - The category being edited.+ * @property {import("discourse/models/category").default} category - The category being edited.* @property {Object} form - The Form API object for the edit category form.* @property {Object} [transientData] - Transient data from the Form wrapper, when available.*/diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 7e3d9479b39..50245ba5f55 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -1132,7 +1132,7 @@ class _PluginApi {* @param {function} toolbarEvent.addText - Append the given text to the selected text in the composer.** @callback condition- * @param {Object} composer - The composer service object.+ * @param {import("discourse/services/composer").default} composer - The composer service object.* @returns {boolean} - Whether the button should be displayed.** @param {Object} opts - An Object.@@ -2764,7 +2764,7 @@ class _PluginApi {* @param {BaseSectionLink} baseSectionLink - Factory class to inherit from.* @returns {BaseSectionLink} - A class that extends BaseSectionLink.*- * @param {(addCommunitySectionLinkCallback|Object)} arg - A callback function or an Object.+ * @param {(addCommunitySectionLinkCallback|{name: string, title: string, text: string, route?: string, href?: string, icon?: string})} arg - A callback function or an Object.* @param {string} arg.name - The name of the link. Needs to be dasherized and lowercase.* @param {string} arg.title - The title attribute for the link.* @param {string} arg.text - The text to display for the link.@@ -2822,7 +2822,7 @@ class _PluginApi {* @param {Object} arg - An object* @param {string} arg.badgeTextFunction - Function used to generate the text for the badge displayed in the section link.* @param {string} arg.route - The Ember route name to generate the href attribute for the link.- * @param {Object} [arg.routeQuery] - Object representing the query params that should be appended to the route generated.+ * @param {Record<string, unknown>} [arg.routeQuery] - Object representing the query params that should be appended to the route generated.* @param {shouldRegister} arg.shouldRegister - Function used to determine if the countable should be registered for the category.* @param {refreshCountFunction} arg.refreshCountFunction - Function used to calculate the value used to set the property for the count whenever the sidebar section link refreshes.* @param {prioritizeOverDefaults} args.prioritizeOverDefaults - Function used to determine whether the countable should be prioritized over the default countables of unread/new.@@ -3565,8 +3565,8 @@ class _PluginApi {* ```** @callback activityItemConfig- * @param {Object} periods - an object containing the periods that the block given to the `register_stat` server-side API returns.- * @returns {Object} - configuration object for the site activity item. The object must contain the following properties: `icon`, `class`, `activityText` and `period`.+ * @param {Record<string, number>} periods - an object containing the periods that the block given to the `register_stat` server-side API returns.+ * @returns {{icon: string, class: string, activityText: string, period: string}} - configuration object for the site activity item. The object must contain the following properties: `icon`, `class`, `activityText` and `period`.** @param {string} name - a string that matches the string given to the `register_stat` server-side API.* @param {activityItemConfig} func - a callback that returns an object containing properties for the custom site activity item.@@ -3731,7 +3731,7 @@ class _PluginApi {* - `previousTypes` - selection before this change* - `category`, `form`, and optionally `transientData`*- * @param {function(Object): (boolean|undefined|Promise<boolean|undefined>)} fn+ * @param {(context: import("discourse/lib/on-before-category-types-change").OnBeforeCategoryTypesChangeContext) => (boolean|undefined|Promise<boolean|undefined>)} fn*/registerOnBeforeCategoryTypesChange(fn) {registerOnBeforeCategoryTypesChange(fn);diff --git a/frontend/discourse/app/models/category-list.js b/frontend/discourse/app/models/category-list.jsindex c79b78407e9..b293b781752 100644--- a/frontend/discourse/app/models/category-list.js+++ b/frontend/discourse/app/models/category-list.js@@ -20,9 +20,9 @@ export default class CategoryList extends LegacyArrayLikeObject {/*** Creates category objects from API result data*- * @param {Object} store - The store instance- * @param {Object} result - The API result containing category data- * @param {Object} parentCategory - Optional parent category+ * @param {import("discourse/services/store").default} store - The store instance+ * @param {Record<string, unknown>} result - The API result containing category data+ * @param {import("discourse/models/category").default | null} [parentCategory] - Optional parent category* @returns {CategoryList} A new CategoryList instance with the processed categories*/static categoriesFrom(store, result, parentCategory = null) {@@ -120,8 +120,8 @@ export default class CategoryList extends LegacyArrayLikeObject {/*** Fetches and creates a list of categories*- * @param {Object} store - The store instance- * @param {Object} parentCategory - Optional parent category to filter by+ * @param {import("discourse/services/store").default} store - The store instance+ * @param {import("discourse/models/category").default | null} [parentCategory] - Optional parent category to filter by* @returns {Promise<CategoryList>} A promise that resolves to the CategoryList*/static async list(store, parentCategory = null) {@@ -160,7 +160,7 @@ export default class CategoryList extends LegacyArrayLikeObject {/*** Creates a new CategoryList instance*- * @param {Object} attrs - The attributes to initialize with+ * @param {Record<string, unknown>} [attrs] - The attributes to initialize with* @returns {CategoryList} A new CategoryList instance*/static create(attrs = {}) {diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.jsindex ff564cc0d82..a5eb7a11a58 100644--- a/frontend/discourse/app/models/composer.js+++ b/frontend/discourse/app/models/composer.js@@ -219,7 +219,11 @@ export default class Composer extends RestModel {@tracked post;@tracked reply;@tracked whisper;++ /** @type {number | null} */@tracked reply_to_post_number = null;++ /** @type {{ id?: number, username: string, name?: string | null, avatar_template: string } | null} */@tracked reply_to_user = null;@trackedlocale = this.siteSettings.content_localization_enabled@@ -232,6 +236,7 @@ export default class Composer extends RestModel {draftForceSave = false;showFullScreenExitPrompt = false;+ /** @type {number | null} */@tracked _categoryId = null;@tracked _archetypesOverride;@@ -298,6 +303,7 @@ export default class Composer extends RestModel {// We wrap categoryId this way so we can fire `applyTopicTemplate` with// the previous value as well as the new value+ /** @param {number | null | undefined} categoryId */set categoryId(categoryId) {const oldCategoryId = this._categoryId;@@ -558,6 +564,16 @@ export default class Composer extends RestModel {@computed("action", "post", "topic", "topic.title", "reply_to_user")get replyOptions() {+ /**+ * @type {{+ * userLink: { href: string, anchor: string } | null,+ * topicLink: { href: string, anchor: string } | null,+ * postLink: { href: string, anchor: string } | null,+ * userAvatar: string | null,+ * originalUser: { username: string, avatar: string } | null,+ * label?: string,+ * }}+ */const options = {userLink: null,topicLink: null,@@ -1033,7 +1049,7 @@ export default class Composer extends RestModel {@param {Boolean} [opts.whisper]@param {Boolean} [opts.noBump]@param {String} [opts.archetypeId] One of `site.archetypes` e.g. `regular` or `private_message`- @param {Object} [opts.metaData]+ @param {Record<string, unknown>} [opts.metaData]@param {Number} [opts.categoryId]@param {Number} [opts.postId]@param {Number} [opts.destinationCategoryId]diff --git a/frontend/discourse/app/models/group.js b/frontend/discourse/app/models/group.jsindex 25e1e8194a2..3b22b94f85c 100644--- a/frontend/discourse/app/models/group.js+++ b/frontend/discourse/app/models/group.js@@ -46,10 +46,18 @@ export default class Group extends RestModel {@autoTrackedArray requesters = [];user_count = 0;++ /** @type {number | null} */limit = null;++ /** @type {number | null} */offset = null;request_count = 0;++ /** @type {number | null} */requestersLimit = null;++ /** @type {number | null} */requestersOffset = null;@dependentKeyCompat@@ -342,8 +350,8 @@ export default class Group extends RestModel {email_username: this.email_username,email_from_alias: this.email_from_alias,email_password: this.email_password,- flair_icon: null,- flair_upload_id: null,+ flair_icon: /** @type {string | null} */ (null),+ flair_upload_id: /** @type {number | null} */ (null),flair_bg_color: this.flairBackgroundHexColor,flair_color: this.flairHexColor,bio_raw: this.bio_raw,diff --git a/frontend/discourse/app/models/nav-item.js b/frontend/discourse/app/models/nav-item.jsindex 7af4e555994..41fa56703d3 100644--- a/frontend/discourse/app/models/nav-item.js+++ b/frontend/discourse/app/models/nav-item.js@@ -347,6 +347,8 @@ export default class NavItem extends EmberObject {export class ExtraNavItem extends NavItem {@tracked href;@tracked count = 0;++ /** @type {((category: Category | null | undefined, args: Record<string, unknown>) => boolean) | null} */customFilter = null;}diff --git a/frontend/discourse/app/models/pending-post.js b/frontend/discourse/app/models/pending-post.jsindex c8adb7b4d28..1b8b44ca5e8 100644--- a/frontend/discourse/app/models/pending-post.js+++ b/frontend/discourse/app/models/pending-post.js@@ -6,6 +6,7 @@ import RestModel from "discourse/models/rest";import Category from "./category.js";export default class PendingPost extends RestModel {+ /** @type {string | import("@ember/template").TrustedHTML | null} */expandedExcerpt = null;truncated = false;diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.jsindex 641bf663852..ea9b697eecd 100644--- a/frontend/discourse/app/models/post-stream.js+++ b/frontend/discourse/app/models/post-stream.js@@ -77,6 +77,8 @@ export default class PostStream extends RestModel {/*** Post awaiting focus once rendered. A fresh object per request, so the* renderer can mark it `done` without writing tracked state mid-render.+ *+ * @type {{ postNumber: number, done: boolean } | null}*/@tracked focusTarget = null;@tracked gaps;@@ -1241,6 +1243,7 @@ export default class PostStream extends RestModel {.filter((item) => item != null);}+ /** @returns {globalThis.Promise<import("discourse/models/post").default[] | undefined>} */async loadIntoIdentityMap(postIds, opts) {if (isEmpty(postIds)) {return [];diff --git a/frontend/discourse/app/models/post.js b/frontend/discourse/app/models/post.jsindex 2eec87a54dd..267f1cbacc3 100644--- a/frontend/discourse/app/models/post.js+++ b/frontend/discourse/app/models/post.js@@ -153,6 +153,8 @@ export default class Post extends RestModel {@tracked cooked;@tracked cooked_hidden;@tracked created_at;++ /** @type {string | null} */@tracked customShare = null;@tracked deleted_at;@tracked deleted_by;diff --git a/frontend/discourse/app/models/result-set.js b/frontend/discourse/app/models/result-set.jsindex 48f78d4fe35..c61b7a2f32c 100644--- a/frontend/discourse/app/models/result-set.js+++ b/frontend/discourse/app/models/result-set.js@@ -6,13 +6,19 @@ import LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";export default class ResultSet extends LegacyArrayLikeObject {@tracked extras;@tracked findArgs;++ /** @type {string | null | undefined} */@tracked loadMoreUrl = null;@tracked loading = false;@tracked loadingMore = false;++ /** @type {string | null | undefined} */@tracked refreshUrl = null;@tracked refreshing = false;@tracked resultSetMeta;@tracked totalRows = 0;++ /** @type {import("discourse/services/store").default | null} */store = null;__type;diff --git a/frontend/discourse/app/models/session.js b/frontend/discourse/app/models/session.jsindex de1f786a5ea..1f94aa00cb1 100644--- a/frontend/discourse/app/models/session.js+++ b/frontend/discourse/app/models/session.js@@ -7,6 +7,8 @@ import RestModel from "discourse/models/rest";@singletonexport default class Session extends RestModel {@tracked requiresRefresh = false;++ /** @type {boolean | null} */hasFocus = null;init() {diff --git a/frontend/discourse/app/models/topic-details.js b/frontend/discourse/app/models/topic-details.jsindex 5f24a850ba5..8d2fb7e5359 100644--- a/frontend/discourse/app/models/topic-details.js+++ b/frontend/discourse/app/models/topic-details.js@@ -33,6 +33,8 @@ export default class TopicDetails extends RestCompatModel {}@tracked loaded = false;++ /** @type {import("discourse/models/topic").default | null} */topic = null;#topicId;diff --git a/frontend/discourse/app/models/topic-tracking-state.js b/frontend/discourse/app/models/topic-tracking-state.jsindex 3fc00517b29..de9dd9ecda0 100644--- a/frontend/discourse/app/models/topic-tracking-state.js+++ b/frontend/discourse/app/models/topic-tracking-state.js@@ -269,7 +269,7 @@ export default class TopicTrackingState extends EmberObject {* is called by various topic routes, as is resetTracking.** @method notifyIncoming- * @param {Object} data - The data sent by TopicTrackingState to MessageBus+ * @param {{ message_type: string, topic_id: number, payload?: Record<string, unknown> }} data - The data sent by TopicTrackingState to MessageBus* which includes the message_type, payload of the topic,* and the topic_id.*/@@ -510,7 +510,7 @@ export default class TopicTrackingState extends EmberObject {* @method sync* @param {TopicList} list* @param {String} filter - The filter used for the list e.g. new/unread- * @param {Object} queryParams - The query parameters for the list e.g. page+ * @param {Record<string, unknown>} [queryParams] - The query parameters for the list e.g. page*/sync(list, filter, queryParams) {if (!list || !list.topics) {@@ -552,6 +552,7 @@ export default class TopicTrackingState extends EmberObject {delete this.stateChangeCallbacks[callbackId];}+ /** @returns {number[] | Set<number>} */getSubCategoryIds(categoryId) {if (!categoryId) {return [];diff --git a/frontend/discourse/app/models/user-drafts-stream.js b/frontend/discourse/app/models/user-drafts-stream.jsindex 1fd4f6736db..bfc7e3b87d5 100644--- a/frontend/discourse/app/models/user-drafts-stream.js+++ b/frontend/discourse/app/models/user-drafts-stream.js@@ -15,6 +15,8 @@ export default class UserDraftsStream extends RestModel {limit = 30;loading = false;hasMore = false;++ /** @type {UserDraft[] | null} */content = null;init() {diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.jsindex cda0ff695f9..26da50173d8 100644--- a/frontend/discourse/app/models/user.js+++ b/frontend/discourse/app/models/user.js@@ -1632,6 +1632,8 @@ class UserStatusManager {user;_subscribersCount = 0;++ /** @type {import("@ember/runloop").Timer | null} */_clearStatusTimerId = null;constructor(user) {diff --git a/frontend/discourse/app/services/category-type-chooser.js b/frontend/discourse/app/services/category-type-chooser.jsindex fbe675e6078..f41f35a0377 100644--- a/frontend/discourse/app/services/category-type-chooser.js+++ b/frontend/discourse/app/services/category-type-chooser.js@@ -1,10 +1,42 @@import Service, { service } from "@ember/service";+/**+ * @typedef {{+ * id: string,+ * name: string,+ * title: string,+ * description: string,+ * icon: string,+ * available: boolean,+ * visible: boolean,+ * configuration_schema: Record<string, Record<string, unknown>[]>,+ * required_plugin?: string,+ * can_enable_plugin?: boolean,+ * contact_admin_username?: string,+ * [key: string]: unknown,+ * }} CategoryType+ */++/**+ * @typedef {{+ * type: string,+ * typeName: string,+ * typeSchema: CategoryType["configuration_schema"],+ * typeTitle: string,+ * visible: boolean,+ * available: boolean,+ * count: number,+ * }} CategoryTypeSelection+ */+export default class CategoryTypeChooser extends Service {@service router;+ /** @type {CategoryTypeSelection | null} */_selection = null;_setupComplete = false;++ /** @type {CategoryType[] | null} */_allTypes = null;get allTypes() {diff --git a/frontend/discourse/app/services/composer-action-state.js b/frontend/discourse/app/services/composer-action-state.jsindex cf7ebcfa078..2c2ba018db3 100644--- a/frontend/discourse/app/services/composer-action-state.js+++ b/frontend/discourse/app/services/composer-action-state.js@@ -13,7 +13,10 @@ export default class ComposerActionStateService extends Service {@service composer;@service dialog;+ /** @type {import("discourse/models/topic").default | null} */topicSnapshot = null;++ /** @type {import("discourse/models/post").default | null | undefined} */postSnapshot = null;get snapshot() {diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex d34c79792f0..d719b7477ba 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -121,22 +121,41 @@ export default class ComposerService extends Service {@service store;@service toasts;+ /** @type {string | null} */@tracked selectedTranslationLocale = null;++ /** @type {number | null} */messageCount = null;showEditReason = false;++ /** @type {string | null} */editReason = null;++ /** @type {number | null} */scopedCategoryId = null;++ /** @type {number | null} */prioritizedCategoryId = null;++ /** @type {number | null} */readOnlyCategoryId = null;++ /** @type {number | null} */lastValidatedAt = null;isUploading = false;isProcessingUpload = false;isCancellable;uploadProgress;++ /** @type {import("discourse/models/topic").default | null} */topic = null;++ /** @type {import("discourse/lib/link-lookup").default | null} */linkLookup = null;#onSaved = null;++ /** @type {boolean | null} */@tracked _allowPreview = null;@tracked _showPreview;@@ -773,12 +792,12 @@ export default class ComposerService extends Service {* Supports appending text once the composer is open.** @param {Object} opts - Configuration options- * @param {Object} [opts.topic] - If provided, opens composer with reply action,+ * @param {import("discourse/models/topic").default} [opts.topic] - If provided, opens composer with reply action,* using the current topic key and draft sequence* @param {boolean} [opts.fallbackToNewTopic] - If true and no draft/topic exists,* opens composer with create_topic action and new topic draft key* @param {string} [opts.insertText] - Text to append to the composer after opening- * @param {Object} [opts.openOpts] - Additional options passed to this.open when+ * @param {Partial<Parameters<ComposerService["open"]>[0]>} [opts.openOpts] - Additional options passed to this.open when* fallbackToNewTopic is true or topic is provided* @returns {Promise<void>}*/@@ -1539,7 +1558,7 @@ export default class ComposerService extends Service {@param {Number} [opts.draftSequence]@param {Boolean} [opts.skipJumpOnSave] Option to skip navigating to the post when saved in this composer session@param {Boolean} [opts.skipFormTemplate] Option to skip the form template even if configured for the category- @param {Object} [opts.hijackPreview] Replaces the preview pane, as { component, model }+ @param {{ component: import("@glint/template").ComponentLike, model?: unknown }} [opts.hijackPreview] Replaces the preview pane@param {String} [opts.selectedTranslationLocale] The locale to use for the translation@param {Function} [opts.onSaved] Called once after this composer session is saved, never if it is closed, discarded or replaced.**/diff --git a/frontend/discourse/app/services/document-title.js b/frontend/discourse/app/services/document-title.jsindex f5130b95199..38aa89e1348 100644--- a/frontend/discourse/app/services/document-title.js+++ b/frontend/discourse/app/services/document-title.js@@ -12,6 +12,8 @@ export default class DocumentElement extends Service {contextCount = 0;notificationCount = 0;++ /** @type {string | null} */#title = null;#backgroundNotify = null;diff --git a/frontend/discourse/app/services/embed-auth-flow.js b/frontend/discourse/app/services/embed-auth-flow.jsindex 3381016d62b..a86a4d6f989 100644--- a/frontend/discourse/app/services/embed-auth-flow.js+++ b/frontend/discourse/app/services/embed-auth-flow.js@@ -11,8 +11,13 @@ export default class EmbedAuthFlow extends Service {@service modal;@service siteSettings;+ /** @type {Window | null} */_popup = null;++ /** @type {ReturnType<typeof setInterval> | null} */_pollTimer = null;++ /** @type {number | null} */_pollStartedAt = null;_pollInFlight = false;diff --git a/frontend/discourse/app/services/exception.js b/frontend/discourse/app/services/exception.jsindex 438f2feb816..7a36ca34c75 100644--- a/frontend/discourse/app/services/exception.js+++ b/frontend/discourse/app/services/exception.js@@ -3,7 +3,10 @@ import { getOwner } from "@ember/owner";import Service from "@ember/service";export default class Exception extends Service {+ /** @type {unknown} */@tracked thrown = null;++ /** @type {import("@ember/routing/transition").default | null} */@tracked lastTransition = null;/**diff --git a/frontend/discourse/app/services/footer.js b/frontend/discourse/app/services/footer.jsindex aac4c330e16..a4297e1f79e 100644--- a/frontend/discourse/app/services/footer.js+++ b/frontend/discourse/app/services/footer.js@@ -8,6 +8,8 @@ import { disableImplicitInjections } from "discourse/lib/implicit-injections";@disableImplicitInjectionsexport default class FooterService extends Service {#hiders = trackedSet();++ /** @type {boolean | null} */@tracked _showFooterOverride = null;get showFooter() {diff --git a/frontend/discourse/app/services/keyboard-shortcuts.js b/frontend/discourse/app/services/keyboard-shortcuts.jsindex 4007c6a7578..9421417a20e 100644--- a/frontend/discourse/app/services/keyboard-shortcuts.js+++ b/frontend/discourse/app/services/keyboard-shortcuts.js@@ -16,6 +16,17 @@ import DiscourseURL from "discourse/lib/url";import Composer from "discourse/models/composer";import { capabilities } from "discourse/services/capabilities";+/**+ * @typedef {{+ * anonymous?: boolean,+ * global?: boolean,+ * handler?: string | ((event: KeyboardEvent) => void),+ * postAction?: string,+ * click?: string,+ * path?: string,+ * }} ShortcutBinding+ */+let disabledBindings = [];export function disableDefaultKeyboardShortcuts(bindings) {@@ -228,6 +239,7 @@ export default class KeyboardShortcutLib extends Service {return this.keyTrapper == null;}+ /** @param {ShortcutBinding | null} [binding] */bindKey(key, binding = null) {if (this.isTornDown()) {return;@@ -690,6 +702,7 @@ export default class KeyboardShortcutLib extends Service {return false;}+ /** @returns {NodeListOf<Element> | Element[]} */categoriesTopicsList() {switch (this.siteSettings.desktop_category_page_style) {case "categories_with_featured_topics":diff --git a/frontend/discourse/app/services/media-optimization-worker.js b/frontend/discourse/app/services/media-optimization-worker.jsindex 34522a16617..879372959bd 100644--- a/frontend/discourse/app/services/media-optimization-worker.js+++ b/frontend/discourse/app/services/media-optimization-worker.js@@ -31,8 +31,13 @@ export default class MediaOptimizationWorkerService extends Service {@service currentUser;@service siteSettings;+ /** @type {Worker | null} */worker = null;++ /** @type {import("@uppy/core").UppyFile<import("@uppy/core").Meta, import("@uppy/core").Body> | null} */currentComposerUploadData = null;++ /** @type {Record<string, (file?: File) => void> | null} */promiseResolvers = null;workerDoneCount = 0;workerPendingCount = 0;diff --git a/frontend/discourse/app/services/modal.js b/frontend/discourse/app/services/modal.jsindex 3f3b915ac49..2dc8a57ad7f 100644--- a/frontend/discourse/app/services/modal.js+++ b/frontend/discourse/app/services/modal.js@@ -25,6 +25,7 @@ export default class ModalService extends Service {@tracked containerElement;+ /** @type {Element | null} */triggerElement = null;@actiondiff --git a/frontend/discourse/app/services/more-topics-tabs.js b/frontend/discourse/app/services/more-topics-tabs.jsindex ec2cc167f96..babc7dfade2 100644--- a/frontend/discourse/app/services/more-topics-tabs.js+++ b/frontend/discourse/app/services/more-topics-tabs.js@@ -5,12 +5,28 @@ import { registeredTabs } from "discourse/components/more-topics";import { disableImplicitInjections } from "discourse/lib/implicit-injections";import { applyValueTransformer } from "discourse/lib/transformer";+/**+ * @typedef {{+ * id: string,+ * name: string,+ * icon?: string,+ * component: import("@glint/template").ComponentLike,+ * condition?: (opts: {+ * topic: import("discourse/models/topic").default,+ * context: "topic" | "pm",+ * }) => boolean,+ * }} MoreTopicsTab+ */+@disableImplicitInjectionsexport default class MoreTopicsTabsService extends Service {@service currentUser;@service keyValueStore;+ /** @type {import("discourse/models/topic").default | null} */@tracked topic = null;++ /** @type {MoreTopicsTab | null} */@tracked preferredTab = null;get context() {diff --git a/frontend/discourse/app/services/nested-view-cache.js b/frontend/discourse/app/services/nested-view-cache.jsindex 4e9009832c3..54c74eb5772 100644--- a/frontend/discourse/app/services/nested-view-cache.js+++ b/frontend/discourse/app/services/nested-view-cache.js@@ -41,6 +41,7 @@ export default class NestedViewCacheService extends Service {this.#forceUseCache = true;}+ /** @param {{ isPoppedState?: boolean, allowLocalSignal?: boolean } | null} [options] */consumeTraversal(options = null) {if (this.#forceUseCache) {this.#forceUseCache = false;diff --git a/frontend/discourse/app/services/pm-topic-tracking-state.js b/frontend/discourse/app/services/pm-topic-tracking-state.jsindex 89421ca05c3..a9cb428ee4e 100644--- a/frontend/discourse/app/services/pm-topic-tracking-state.js+++ b/frontend/discourse/app/services/pm-topic-tracking-state.js@@ -24,8 +24,14 @@ class PrivateMessageTopicTrackingState extends Service {@tracked isTracking = false;@tracked isTrackingIncoming = false;@tracked statesModificationCounter = 0;++ /** @type {string | null} */@tracked inbox = null;++ /** @type {string | null} */@tracked filter = null;++ /** @type {import("discourse/models/group").default | null | undefined} */@tracked activeGroup = null;@tracked newIncoming = trackedArray();states = trackedMap();diff --git a/frontend/discourse/app/services/presence.js b/frontend/discourse/app/services/presence.jsindex bb81a04fffb..69d5e219eb1 100644--- a/frontend/discourse/app/services/presence.js+++ b/frontend/discourse/app/services/presence.js@@ -17,6 +17,14 @@ import userPresent, {} from "discourse/lib/user-presence";import User from "discourse/models/user";+/**+ * @typedef {{+ * count: number,+ * last_message_id: number,+ * users?: Record<string, unknown>[],+ * }} PresenceChannelStateData+ */+const PRESENCE_INTERVAL_S = 30;const DEFAULT_PRESENCE_DEBOUNCE_MS = isTesting() ? 0 : 500;const PRESENCE_THROTTLE_MS = isTesting() ? 0 : 1000;@@ -105,6 +113,7 @@ class PresenceChannel extends EmberObject.extend(Evented) {}}+ /** @param {PresenceChannelStateData | null} [initialData] */async subscribe(initialData = null) {if (this.subscribed) {return;@@ -450,6 +459,7 @@ export default class PresenceService extends Service {await promiseProxy.promise;}+ /** @param {PresenceChannelStateData | null} [initialData] */async _subscribe(channelProxy, initialData = null) {if (this.siteSettings.login_required && !this.currentUser) {throw "Presence is only available to authenticated users on login-required sites";diff --git a/frontend/discourse/app/services/screen-track.js b/frontend/discourse/app/services/screen-track.jsindex 8bec655a131..0008335d834 100644--- a/frontend/discourse/app/services/screen-track.js+++ b/frontend/discourse/app/services/screen-track.js@@ -32,13 +32,21 @@ export default class ScreenTrack extends Service {_ajaxFailures = 0;_consolidatedTimings = [];++ /** @type {number | null} */_lastTick = null;++ /** @type {number | null} */_lastScrolled = null;_lastFlush = 0;_timings = new Map();_totalTimings = new Map();_topicTime = 0;++ /** @type {number[] | null} */_onscreen = null;++ /** @type {number[] | null} */_readOnscreen = null;_readPosts = new Set();_inProgress = false;diff --git a/frontend/discourse/app/services/scroll-manager.js b/frontend/discourse/app/services/scroll-manager.jsindex be3eb43f54e..99bcc9411f3 100644--- a/frontend/discourse/app/services/scroll-manager.js+++ b/frontend/discourse/app/services/scroll-manager.js@@ -21,7 +21,7 @@ export default class ScrollManager extends Service {* Binds scroll events to a component and calls its 'scrolled' method when scrolling occurs** @method bindScrolling- * @param {Object} target The component that will receive 'scrolled' method calls+ * @param {{ scrolled: () => void }} target The component that will receive 'scrolled' method calls* @param {Object} [opts={}] Configuration options* @param {Number} [opts.throttle=100] Throttle time in milliseconds; this is the time interval between every call of the scroll event* @public@@ -77,7 +77,7 @@ export default class ScrollManager extends Service {* Unbinds scroll events from a component** @method unbindScrolling- * @param {Object} target The component to unbind scroll events from+ * @param {{ scrolled: () => void }} target The component to unbind scroll events from* @public*/unbindScrolling(target) {diff --git a/frontend/discourse/app/services/session-store.js b/frontend/discourse/app/services/session-store.jsindex d52a59adfb8..f4544881500 100644--- a/frontend/discourse/app/services/session-store.js+++ b/frontend/discourse/app/services/session-store.js@@ -7,6 +7,7 @@ const DISCOURSE_PREFIX = "discourse_";@disableImplicitInjectionsexport default class SessionStoreService extends Service {+ /** @type {string | null} */context = null;constructor(ctx = DISCOURSE_PREFIX) {diff --git a/frontend/discourse/app/services/shared-content.js b/frontend/discourse/app/services/shared-content.jsindex f2ecf87cfcf..7bbd6f4e5f9 100644--- a/frontend/discourse/app/services/shared-content.js+++ b/frontend/discourse/app/services/shared-content.js@@ -12,6 +12,7 @@ import {export default class SharedContent extends Service {@service appEvents;+ /** @type {{ body: string, files: File[] } | null} */@tracked pending = null;get hasPending() {diff --git a/frontend/discourse/app/services/sidebar-state.js b/frontend/discourse/app/services/sidebar-state.jsindex 46ad7bebf41..3f16600270d 100644--- a/frontend/discourse/app/services/sidebar-state.js+++ b/frontend/discourse/app/services/sidebar-state.js@@ -24,6 +24,8 @@ export default class SidebarState extends Service {@tracked mode = COMBINED_MODE;@tracked filter = "";@tracked isForcingSidebar = false;++ /** @type {string | null} */@tracked forcingSidebarPanel = null;panels = panels;diff --git a/frontend/discourse/app/services/user-nav-sidebar-state-manager.js b/frontend/discourse/app/services/user-nav-sidebar-state-manager.jsindex 583a9282588..dc66608d1ca 100644--- a/frontend/discourse/app/services/user-nav-sidebar-state-manager.js+++ b/frontend/discourse/app/services/user-nav-sidebar-state-manager.js@@ -18,6 +18,8 @@ export default class UserNavSidebarStateManager extends Service {* Where the viewer was before they opened a user's admin page. Captured on* arrival rather than read from history as they go, so that moving between* that page's own tabs doesn't rewrite where they came from.+ *+ * @type {string | null}*/@tracked entryURL = null;diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gtsindex d77218196a3..00432ff22d0 100644--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts@@ -27,9 +27,8 @@ type Measurement = number | null | (() => number | null);* A bound, which unlike a size is expected to be known. There is nothing to clamp* against until it is, so a consumer with no limit should leave the arg off.*- * `strictNullChecks` is off repo-wide, so a nullable measurement still type-checks- * here. The gesture holds the line instead. It skips a bound that does not- * resolve, rather than reading it as zero.+ * Untyped consumers can still pass a nullable measurement, so the gesture skips+ * a bound that does not resolve, rather than reading it as zero.*/type Bound = number | (() => number);diff --git a/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gtsindex eca809c7192..0d52f6d0884 100644--- a/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gts+++ b/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gts@@ -3,9 +3,8 @@// suppresses reporting elsewhere in its file, which would let a positive pass// against a broken declaration. Positives live in d-button-action-test.gts.//-// Each case stays on one line, hence the short names: the strict and non-strict-// projects report a multi-line invocation's error on different lines, and a-// directive only covers the line after it.+// Each case stays on one line, hence the short names, so the directive above it+// covers the whole invocation.import DButton from "discourse/ui-kit/d-button";interface Topic {@@ -22,10 +21,10 @@ declare function withEvent(topic: Topic, event: Event): void;declare function readEvent(param: undefined, event: Event): void;declare function save(draft: Draft): void;-// A handler that needs a parameter while `@actionParam` is omitted is also rejected,-// but only under `strictNullChecks`, where `undefined` stops fitting every type. This-// file is checked by the non-strict project as well, so that case is not asserted here.const Negatives = <template>+ {{! @glint-expect-error - the handler wants a Draft but @actionParam is omitted }}+ <DButton @action={{save}} />+{{! @glint-expect-error - the handler wants a Draft but @actionParam is a Topic }}<DButton @action={{save}} @actionParam={{topic}} />diff --git a/tsconfig-base.json b/tsconfig-base.jsonindex 36c7c7c1f1e..6f62cc4fe23 100644--- a/tsconfig-base.json+++ b/tsconfig-base.json@@ -10,7 +10,7 @@"experimentalDecorators": true,"allowJs": true,"skipLibCheck": true,- "strict": false,+ "strict": true,"noUncheckedSideEffectImports": false,"noEmit": false,"noEmitOnError": false,