A platform for community discussion. Free, open, simple.
DEV: Add a skill for writing TypeScript and converting JS to TS (#43024)
Sérgio Saquetim1b7f1305e5dc
diff --git a/.skills/discourse-writing-typescript/SKILL.md b/.skills/discourse-writing-typescript/SKILL.mdnew file mode 100644index 00000000000..89f594d718c--- /dev/null+++ b/.skills/discourse-writing-typescript/SKILL.md@@ -0,0 +1,378 @@+---+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.+---++# Writing TypeScript for Discourse++Core, plugins, and themes can be authored in `.ts`/`.gts` with full TypeScript. The+reference components are+[`frontend/discourse/app/ui-kit/d-async-content.gts`](../../frontend/discourse/app/ui-kit/d-async-content.gts)+(a generic `Signature`, per-member TSDoc, documented yielded block tuples, `WithBoundArgs`)+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 bag+derived from a shared type); the developer guide is+[`26-types.md`](../../docs/developer-guides/docs/03-code-internals/26-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.++**Converting an existing `.js`/`.gjs` file?** Read+[references/js-to-ts-conversion.md](references/js-to-ts-conversion.md) first (the faithful-port+rules, rename mechanics, scope triage, and the runtime pitfall), and apply+[references/conversion-completeness.md](references/conversion-completeness.md) before+claiming any file or subsystem converted.++## Golden rules++1. **A conversion is a types-only port.** Types are erased; runtime behavior is not. Never+ change runtime code to satisfy a type. The full rule and the catalogue of changes that+ pass `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.+4. **The type-checker is necessary but NOT sufficient.** `pnpm lint:types` green does not+ mean 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+ ones.** `checkJs` is off, so untyped `.gjs`/`.js` consumers are not "safe", merely+ *unchecked for now*; they will be measured against today's `Signature` when they convert.+ Do not scope arg types to the handful of files type-checked today; that bakes in a+ too-narrow contract that makes the rest harder to convert later. Type each arg to the+ component's **true contract**: its actual runtime behavior **plus the full range of real+ call sites** (grep every consumer, typed or not), as precise as the contract truly is but+ **no narrower**. Example: `d-flash-message`'s `@flash` is `string | TrustedHTML`, not+ `string`, because live consumers pass a `trustHTML(...)` result; the typed consumers alone+ would not have revealed the untyped one that does.++## Patterns++### `.gts` component (see `d-tooltip.gts`)++```ts+interface XSignature {+ Args: { title?: string; onSelect?: (v: string) => void; /* type every @arg read */ };+ Element: HTMLButtonElement; // enables ...attributes checking+ Blocks: { default: []; item: [ItemType] };+}+export default class X extends Component<XSignature> { ... }+```++- Type `@action`/event params: `click(e: MouseEvent)`, `keyDown(e: KeyboardEvent)`.+- **Type injected services; do NOT leave `@service` bare.** This repo has no service+ `Registry` and `@service` is a bare `PropertyDecorator`, so a bare `@service foo;` makes+ `this.foo` implicitly `any` and every `this.foo.bar()` call goes unchecked: a hidden `any`+ that violates the no-`any` bar. Use Ember's documented pattern (see `d-tooltip.gts`):++ ```ts+ import type TooltipService from "discourse/float-kit/services/tooltip";+ @service declare tooltip: TooltipService; // `declare` = the decorator sets it+ ```++ Much of the codebase still uses bare `@service router;`. That+ is the loose status quo, **not** the bar to match. In a `.js`/`.gjs` `@ts-check` file you+ are not converting, the equivalent is a+ `/** @type {import("discourse/services/foo").default} */` line above `@service foo;`.++ **Importing an untyped service or model's type is NOT a chain conversion.** A service is+ often backed by an untyped model (`@service site` is `discourse/models/site.js`). Writing+ `import type Site from "discourse/models/site"; @service declare site: Site;` pulls in the+ type TS *already infers* from that `.js` file, as-is, converting nothing. Real getters and+ fields in the class body still resolve. This is strictly better than a hidden `any` and+ costs one `import type`; do it rather than leaving `@service` bare out of a fear of+ "dragging in" the model.+- **Suffix imported service class bindings with `Service`.** Name the local type binding+ after its role even when the source module exports a shorter class name or is still+ JavaScript: `import type MenuService from "discourse/float-kit/services/menu";` then+ `@service declare menu: MenuService;`. Keep the injected property name and module path+ unchanged. Do not add `Service` to models, payloads, utilities, or other non-service types.+- **`declare` for framework-set fields** generally: Ember needs `declare` on `@service` (and+ on any decorated or args field with no initializer) so TS trusts the decorator to set it.+ Fields you initialize yourself do not need it.+- **Generic component:** `class X<T> extends Component<XSignature<T>>` with+ `interface XSignature<T> { ... Blocks: { content: [value: T] } }` (see+ `d-async-content.gts`). `Element` **enables `...attributes` checking**; omit it only when+ the component takes no attributes (Glint then rejects any attribute or modifier on it), and+ set the real element type where you spread `...attributes`.++### Template-only `.gts` component (no backing class)++A `const X = <template>...</template>;` component is typed by annotating the const; there is+no generic slot to fill:++```ts+import type { TOC } from "@ember/component/template-only";++interface XSignature {+ Args: { condition?: boolean };+ Element: HTMLDivElement; // still needed for ...attributes+ Blocks: { default: [] };+}++const X: TOC<XSignature> = <template>...</template>;+export default X;+```++(`TOC` is the exported alias of `TemplateOnlyComponent`; either name works.)++### `.ts` modifier (`ember-modifier`, see `ui-kit/modifiers/d-trap-tab.ts`)++```ts+import Modifier, { type ArgsFor } from "ember-modifier";+import type Owner from "@ember/owner";++interface XSignature { Element: HTMLElement; Args: { Named: {...}; Positional: [] }; }+export default class X extends Modifier<XSignature> {+ constructor(owner: Owner, args: ArgsFor<XSignature>) { super(owner, args); ... }+ modify(element: HTMLElement, _positional: [], named: XSignature["Args"]["Named"]) { ... }+}+```++### `.ts` plain class / helper / util++Standard TS. **Export** any interfaces the file's consumers need (e.g. an `XEngineOptions`+for a constructor options bag). Reuse arg types with lookups: `items?: XEngineOptions["items"]`.++### Choose named object types deliberately++Do not mechanically create an `interface` for every object-shaped field, parameter,+response, or private state bag just to attach TSDoc. Name a shape only when the name carries+architectural value:++- Use an `interface` for a component `Signature`, a durable public or exported contract, or+ real declaration-style extension.+- Use a `type` alias for unions, intersections, discriminated variants, and other named+ shapes that do not rely on interface extension.+- Keep a small, single-use parameter/options/state shape inline. Document its nested fields+ with `/** ... */` directly in the inline type when they are part of the public signature.+- Do not extract private one-use response or state bags merely to make the file look typed.++Before defining a local type for a core service, model, helper, or API, import and inspect+the canonical core type, including the type inferred from an unconverted `.js` file. Do not+replace a canonical dependency with a feature-prefixed approximation such as+`PluginCurrentUser` or `PluginSiteSettings` merely because the core file is JavaScript.++Locally extend a core type only after verifying that the runtime really supplies a field the+canonical type omits. Tag every such extension and every temporary boundary cast with+`TODO(typescript-pending)`, state the exact typing gap, and say when the workaround can be+removed. Dynamic plugin site settings need the same TODO until core provides a typed+plugin-setting extension mechanism.++**A plain function IS a valid Glint template helper.** You do not need a class-based+`Helper` to get a precise, argument-dependent return. A generic variadic function with a+`const` type param resolves correctly both as a direct call and in `{{...}}` invocation (see+`frontend/discourse/truth-helpers/helpers/or.ts`):++```ts+export default function or<const T extends MaybeTruthy[]>(...args: T): FirstTruthy<T>;+export default function or(...args: MaybeTruthy[]) { /* impl returns a loose type */ }+```++Use the **overload pattern** (a public typed signature callers see, plus a looser+implementation signature the body satisfies) when the real return is a conditional type the+implementation cannot prove. Confirm the template-invocation typing with a Glint type test+(see "Type tests"). Keep the helper a plain function when it is also imported and called+directly (a class-based `Helper` cannot be called as `helper(a, b)`); converting a function+to a class is a runtime change, not a types-only port.++**Advanced: different signatures in template vs plain-JS position.** Overloads cannot gate+one shape to *template* invocation only; a plain-JS caller can still pick the template-only+overload and fail later. When a function genuinely needs two signatures depending on how it+is called (e.g. an `owner` argument the helper manager injects only during template+invocation, so the template form takes one fewer positional), intersect a normal call+signature with a `DirectInvokable<...>`-branded one from+`@glint/template/-private/integration`. Glint resolves the branded member for template+invocation; TypeScript uses the plain member for direct JS calls. This imports a **private**+Glint path and is a specialist tool; the overload pattern stays the default.++## JSDoc++Keep the didactic **prose** descriptions (Discourse likes docs a junior can read), but+**drop the now-redundant `@param {type}` / `@returns {type}` type tags**; the types live in+the signature. Keep `@param name - description` prose only where it adds meaning.++### Documenting the `Signature` (TSDoc, not `//`)++A `Signature` is the component's public API surface, so its members deserve docs that+**surface in editor intellisense on hover**. That means `/** ... */` TSDoc, member by member;+a `//` line comment above a property does **not** attach to it for hover.++- **Every `Args` and `Blocks` member gets its own `/** ... */`.** Do not lump several under+ one comment. (A `//` comment that merely *groups* members, such as `// Text` /+ `// Actions`, is fine as a grouping and is not meant to surface per property.)+- **Document nested object-arg inner properties too.** `icons?: { left?: string; right?:+ string }` gets a `/** ... */` on `left` and on `right`, not just on `icons`.+- **Document each yielded block value inline on the named tuple member.** TS surfaces TSDoc+ on tuple elements, so prefer per-item docs over describing them in the block's prose:++ ```ts+ /** Rendered when the data rejects; when omitted, handled per `@errorMode`. */+ error: [+ /** The rejection reason. */+ error: Error,+ /** A component, pre-bound to the error, that renders the inline error message. */+ retry: WithBoundArgs<typeof AsyncContentInlineError, "error">,+ ];+ ```++- **Say what the argument IS, not how it is wired internally.** `@type` is "The severity of+ the message", not "selects the `alert-*` modifier class". The class it maps to is an+ implementation detail the consumer does not need.+- **Explain the *why* when a member's purpose is not self-evident.** `@context` on+ `d-async-content` is not just "a value forwarded to the function form": it is **tracked**,+ so updating it re-invokes the function and reloads the data; the doc should tell the+ consumer to pass the reactive state the data source depends on.+- **Watch the phrasing.** Read each line back as a consumer would. "Icon ID displayed at the+ start" reads backwards (the *icon* is displayed, not the ID): "ID of the icon displayed at+ the start of the input." "Rendered ... (no default: a spinner)" is cryptic: "When omitted, a+ loading spinner is shown in its place." Awkward or ambiguous docs are worse than none.++## Typing untyped dependencies (the common blocker)++Consuming an **untyped `.gjs` component or helper from a `.gts` file** gives Glint no+`Signature`, so its invocation errors (`unknown not assignable to Element`, `X does not exist+in type ...`, or a helper returning a loose or wrong type). Two fixes:++- **Untyped component**: a local typed alias, tagged for later removal:++ ```ts+ import { type ComponentLike } from "@glint/template";+ import SomeWidgetUntyped from "discourse/components/some-widget";++ // TODO(typescript-pending): drop once SomeWidget is authored in .gts with a real+ // Signature, then import it directly. Untyped .gjs today, so no arg/block/attr types.+ const SomeWidget = SomeWidgetUntyped as unknown as ComponentLike<{+ Args: { ... }; Element: HTMLElement; Blocks: { default: [] };+ }>;+ ```++ Same runtime import (zero runtime effect). **Always tag `TODO(typescript-pending)`** so+ these stopgaps are greppable and get removed once the underlying component is typed.++- **Untyped helper:** either wrap the value in a typed getter at the call site, or, better,+ type the helper itself (and add a type test). `truth-helpers` is fully typed, so `or`/`and`+ already return the precise value union; a still-untyped helper can follow the same+ plain-function-with-overload pattern. Tag any interim workaround `TODO(typescript-pending)`.++- **Sibling types:** `HelperLike<Sig>` / `ModifierLike<Sig>` are the same idea for untyped+ helpers and modifiers; **`WithBoundArgs<typeof Comp, "argName">`** types a *curried*+ component you yield with some args pre-bound (e.g. an inline error component yielded to an+ `:error` block with `error` already set; see `d-async-content.gts`). The bound args become+ **optional and stay overridable** at the invocation site, the same semantics as+ `{{component}}`. Bind several with a union: `WithBoundArgs<typeof Comp, "a" | "b">`. In an+ `expect-type` test, a curried result asserts as `WithBoundArgs<typeof Comp, "arg">`, **not**+ the raw component type.++## Type tests (compile-time)++When a module's *types* carry meaning a runtime test cannot capture (an argument-dependent+return, an overload picking the right signature, a generic that must resolve to a precise+type), assert them at compile time with `expect-type` (a devDependency of+`frontend/discourse`). They are checked by `pnpm lint:types`.++- **Location:** `frontend/discourse/type-tests/<feature>/`, a **sibling** of `app/` and+ `tests/`, already in the discourse `tsconfig.json` `include`. It sits outside the QUnit+ loader glob (`tests/**/*-test.*`) and outside every `compat-modules.js` glob, so the files+ reach **neither the test nor the production bundle**. Do NOT place them under+ `truth-helpers/` or any `compat-modules` dir; that glob WOULD sweep them into the runtime+ bundle. tsconfig `include` governs type-checking only, never the bundle.+- **Naming:** the repo's `-test.ts` / `-test.gts` suffix; safe here precisely because the+ dir is outside `tests/`.+- **Direct-call tests:** `expectTypeOf(or(maybeStr, "x")).toEqualTypeOf<string>()`,+ `.not.toEqualTypeOf<boolean>()`. A mismatch surfaces either as `error TS2344` or as the+ cryptic **"Expected 1 arguments, but got 0"** on the `.toEqualTypeOf<T>()` (no-value) form;+ that IS expect-type's mismatch signal, not a real arity bug.+- **Template-invocation tests** (a helper or component whose types only surface in a+ `<template>`): a `.gts` with a typed **template-only component** (`TOC`, NOT an empty+ backing class, which trips `ember/no-empty-glimmer-component-classes`) that feeds the value+ into a typed arg (see `type-tests/truth-helpers/glint-test.gts`). Negative cases use+ `{{! @glint-expect-error }}`, the **one sanctioned** use of a Glint directive.+- **Split positives and negatives into separate `.gts` files.** A single+ `{{! @glint-expect-error }}` **anywhere** in a `.gts` makes Glint stop reporting *all+ other* type errors in that file, so a mixed file lets the positives pass **even against a+ broken declaration**. Keep positive template type-tests in files with **zero** Glint+ directives; put every `@glint-expect-error` negative in its own file (see+ `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++`{{! @glint-expect-error }}` / `{{! @glint-ignore }}` / `{{! @glint-nocheck }}` are NOT+acceptable escape hatches; fix the type instead (a `ComponentLike` shim, a narrow, a+documented `as` cast). `@glint-expect-error` is only for **type tests that assert code does+NOT compile**; `@glint-nocheck` is only for **gradual migration** of a template you are not+converting yet. If you reach for one to silence a real error, stop and type the thing.++Also: an in-`<template>` `{{! ... }}` comment must not contain backticks, `<...>` tokens,+`="..."`, or `|`; they break `ember-eslint-parser` scope analysis (spurious `no-unused-vars`+on template imports). Reword to plain prose. JS-body `//` and `/* */` are fine.++## Specific type recipes++- **Trusted HTML:** type as `TrustedHTML` imported from `@ember/template` (the return type+ of `trustHTML()`), NOT `SafeString`/`htmlSafe()`, NOT `ReturnType<typeof trustHTML>`+ (roundabout), and NOT the DOM Trusted Types `TrustedHTML` (not in this project's lib).+- **`super.willDestroy()`:** both `@glimmer/component`'s base (`willDestroy(): void {}`) and+ `@ember/object`'s `CoreObject` (`willDestroy() {}`, invoked by the framework as+ `registerDestructor(self, () => destroyable.willDestroy())`) declare **no parameters and+ are called with none**, so `super.willDestroy(...arguments)` is provably identical to+ `super.willDestroy()`. Write `super.willDestroy();` (the spread also trips eslint+ `prefer-rest-params` in `.ts`/`.gts`). This is a **method-specific** exception verified+ against source; do NOT generalize it to a `super.<hook>(...arguments)` whose base actually+ reads its arguments. Keep the spread there.+- **`@ember/render-modifiers` `{{didInsert}}`/`{{didUpdate}}` handler:** the callback is+ `(element: El, args: PositionalTuple)`; the extra positionals arrive as **one tuple in the+ 2nd param**. So `{{didInsert this.announce count}}` is `announce(el: HTMLElement, [count]:+ [number])` (destructure the tuple), not `announce(el, count)`.+- **DOM element types:** `querySelector` returns `Element` (no `.focus()`/`.tabIndex`); use+ `el.querySelector<HTMLElement>(sel)`. Type element params as `HTMLElement` /+ `HTMLInputElement` where you call element methods, not `Element`.+- **`EmberObject.create()`-populated fields:** declare them `declare foo: T;` (no runtime+ field initializer that would clobber the value `create()` sets).+- **`import type`:** use it for type-only imports; prettier may collapse it since the repo has+ no `verbatimModuleSyntax`. That is fine.+- **Args-bag / options-object param:** type it as `object`, NOT `Record<string, unknown>`. A+ named interface with no index signature is assignable to `object` but **not** to+ `Record<string, unknown>`, so `object` accepts a real component's `this.args` (and any+ interface-typed bag) while `Record<string, unknown>` rejects it.+- **Pass-through callbacks on a widely-used primitive: do not over-tighten.** For a+ lifecycle or relay callback that many consumers pass with varied shapes (a menu's+ `onClose`/`onShow`), pinning `() => void` rejects any consumer callback that takes an arg or+ returns a value. Use a named broad-but-*real* signature: `type XCallback = (...args:+ any[]) => void`. It accepts functions of any arity, documents intent, type-checks the+ internal call, and needs **no** eslint-disable. Do NOT use the bare global `Function` type+ (eslint `no-unsafe-function-type`; calling it yields `any`) nor `any`. Caveat: a value the+ *consumer* has typed as the bare `Function` will not assign even to `(...args: any[]) =>+ void`; that is the consumer's own under-typing to fix (often a lazy `@property+ {Function}`), not a reason to loosen the primitive. Precision rarely forces a consumer+ chase: a param typed `(x: T) => void` still accepts a consumer's `() => void`.++## Lint hazard: member ordering can split comments++`sort-class-members` (via `bin/lint`) reorders class members and can **split a comment that+was attached to a member it moves**: an arrow-function field (`foo = () => ...`) sorts into+the *field* bucket, landing between another field and its leading comment. When **authoring+new** code, prefer `@action` methods over arrow-function fields for template-referenced+callbacks (auto-bound AND sorted into the methods bucket). **Re-read the file after+`bin/lint --fix`** to confirm no comment got orphaned or split.++## 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).+3. `bin/qunit` for the touched files' tests: behavior plus the runtime module-resolution+ check in the conversion reference.++Green on `lint:types` alone is **not** done: a run that hangs or reports a single "Global+error ... Failed to resolve module specifier" is the runtime pitfall described in the+conversion reference.diff --git a/.skills/discourse-writing-typescript/references/conversion-completeness.md b/.skills/discourse-writing-typescript/references/conversion-completeness.mdnew file mode 100644index 00000000000..5efdb599700--- /dev/null+++ b/.skills/discourse-writing-typescript/references/conversion-completeness.md@@ -0,0 +1,55 @@+# Conversion-completeness checklist++Treat a rename as inventory movement, not completed conversion. A `.js`/`.gjs` file renamed+to `.ts`/`.gts` remains pending until its implementation satisfies every applicable item+below. Do not mark a file, service group, or plan phase complete from extension counts or a+subset of checks.++## Per-file acceptance++1. Type every injected service with its canonical class. A typed injection is still+ insufficient when a called dependency method has untyped parameters or an `any` return;+ type the dependency's relevant public method instead of allowing an unchecked value+ across the boundary. Suffix the imported service class binding with `Service`; leave the+ injection 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`.+3. Add useful TSDoc to the typed public API: exported type fields, service+ fields/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.+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 is+ missing, use the narrowest extension and a `TODO(typescript-pending)` naming the gap and+ the removal condition.+7. Treat transport, JSON, browser-storage, DOM, and untyped-component casts as explicit+ boundaries. Keep each cast narrow and tag temporary typing gaps with+ `TODO(typescript-pending)`. Never add validation or narrowing that changes behavior (see+ the faithfulness trap in `js-to-ts-conversion.md`).+8. Keep small one-use object shapes inline. Name a shape only when the name adds reuse,+ navigation, or architectural meaning; do not manufacture interfaces merely to make a file+ look typed.+9. Run `bin/lint --fix` and re-read the file after formatting and member ordering.+ Converting previously unchecked JavaScript can expose lint failures in untouched-looking+ code; those failures belong to the conversion.+10. Audit explicit `.js`/`.gjs` imports after each rename and run the relevant runtime tests.+ Tests may remain JavaScript when their conversion is out of scope, but their imports and+ runtime coverage must still work.++## Incremental evidence versus completion++- During a large migration, filter type-check output by the files under audit so unrelated+ pending files do not hide regressions. This proves only that the named files have no+ reported errors.+- Keep renamed-but-unaudited files and partially typed dependency chains marked pending. A+ consumer is not strict-grade while a dependency method it calls still leaks `any`.+- Do not count a subsystem complete until every file in its planned inventory satisfies the+ per-file checklist.+- Final acceptance still requires clean full lint and type-check, stale-import and+ suppression audits, and relevant runtime tests. Targeted green checks never substitute for+ these full gates.diff --git a/.skills/discourse-writing-typescript/references/js-to-ts-conversion.md b/.skills/discourse-writing-typescript/references/js-to-ts-conversion.mdnew file mode 100644index 00000000000..09fc323c4a1--- /dev/null+++ b/.skills/discourse-writing-typescript/references/js-to-ts-conversion.md@@ -0,0 +1,180 @@+# Converting `.js`/`.gjs` to `.ts`/`.gts`++Read this before converting an existing file. The authoring rules in `SKILL.md` still apply;+this file covers what is specific to a conversion: keeping the port faithful, the rename+mechanics, when to defer, and the runtime failure the type-checker cannot see.++## The one rule: a faithful, types-only port++**The type is erased; the runtime behavior is not.** *Never change runtime code to satisfy a+type.* Preserve every existing guard, fallback, coercion, `throw`, call, mutation, and+pass-through, **even when the new type says that path is impossible**, and solve the type+error with a truthful wider type or a documented erased `as` assertion, never a runtime+check. A type annotation asserts a contract; it does not prove that runtime callers obey it,+because types are erased at compile time and `checkJs` is off. Untyped callers, preload+payloads, MessageBus, `JSON.parse`, and server data all still reach your code shaped however+they really are, which is exactly what the old guards were there for. Deleting a "redundant"+guard is a behavior change and the single most common way a conversion silently breaks. If a+guard looks removable, it still stays: note it for a **separate** cleanup PR.++## The faithfulness trap: changes that pass `lint:types` but alter behavior++A conversion that adds types is supposed to be a runtime no-op. The trap: the new types make+certain runtime code *look* removable, so you "tidy" it while typing, and the port is no+longer faithful. Every item below is a real regression from a conversion; each type-checks+clean and reads like an improvement. **None belong in a conversion PR.** They are erased-type+reasoning applied to code that runs against real, untyped data.++**Forbidden transformations. Each is a behavior change, not a type change. Keep the original:**++1. **Deleting a null/undefined guard because the param/field is now typed non-optional.**+ `themeId: number` does not stop a runtime caller passing `null`. Keep+ `if (themeId == null) { return null; }`.+2. **Removing optional chaining because the type says the value is present.**+ `this.args.leaf?.value` to `this.args.leaf.value` throws where the old code returned a+ default. Keep every `?.`.+3. **Dropping a defensive fallback or default the type says "can't" be nullish.**+ `(value || []).map(...)` to `value.map(...)`; a removed `?? ""` / `?? null`.+4. **Removing a runtime shape check (`Array.isArray`, `typeof`) the declared type asserts.**+ `if (!Array.isArray(layout) || ...)` guards against real non-array input; a+ `LayoutEntry[]` annotation does not.+5. **Adding a type-guard *narrowing* that substitutes a fallback for a value old code passed+ through raw.** `?? null` to `isImageArgValue(v) ? v : null`; `?? ""` to+ `normalizeStoredValue(v)`; `mode` to `typeof mode === "string" ? mode : undefined`;+ `enum` to `enum.map(String)`; a truthy check to `=== true`. Invoking a guard, normalizer,+ `String()`, or a stricter comparison **is runtime code**, even though it feels like+ "safely narrowing `unknown`."+6. **Adding a NEW validation gate that rejects inputs old code accepted.** Wrapping a+ `JSON.parse` result in `if (!isRawLayoutEntry(parsed)) return;`; running a preload or+ MessageBus payload through a new validator that drops rows.+7. **Swapping a runtime primitive for a "cleaner" typed equivalent with different+ semantics.** `console.error(msg, errObj)` to `@ember/debug`'s `warn(string)` is not+ equivalent: `warn` is stripped from production, emits at a different level, and+ stringifies the object. Keep the exact original call and its `// eslint-disable`.+8. **Turning a throw into a silent success, or vice-versa.** `entry.args[k] = v` (throws+ when `args` is nullish) to `(entry.args ??= {})[k] = v` (silently initializes).+9. **Replacing an unreachable-but-present fallback with a `throw`.** `default: return+ children` to `default: throw ...`. An "impossible" branch is still behavior.++**Behavior can change with no input change.** "Any input" is not the whole surface. Also+forbidden: changing a value `import` to `import type` or reordering runtime imports (alters+module evaluation and side effects); reordering initialized fields, adding `= undefined`, or+turning a getter/method into a field or vice-versa (alters init order, own-property+presence, descriptors, framework injection); arrow-field to method or back, added/removed+`@action` or `.bind(this)` (alters callback identity and `this`); adding/removing `await` /+`return await` / `catch` / `finally` (alters scheduling and error propagation); spread-copy+vs in-place mutation, `push` vs concat (alters identity and observable mutation); `x.foo =+undefined` vs `delete x.foo` vs omission (property presence differs); `filter(Boolean)`,+dedup, sort, or a changed loop form (alters skipped values, order, callback invocations); and+runtime-producing TS constructs (`enum`, parameter properties, `namespace`, `#private`+fields, and field initializers are **not** erased annotations).++**The litmus test, applied to every hunk of your own diff:**++> "Can this change any observable runtime behavior in any execution, including module+> loading, initialization, mutation, identity, timing, logging, errors, or handling of a+> nullish, wrong-typed, or malformed value a real untyped caller could pass?"++If yes, it does not belong in the conversion. **"The type proves it can't happen" is not a+defense**: the type is erased and `checkJs` is off, so callers can and do violate it; the+guard is exactly what runs when they do.++**When TypeScript cannot prove what the old code assumed:** preserve the old runtime+operation and express the assumption with a truthful **wider type**, an **overload**, or a+documented **erased `as` assertion** at the existing loose boundary (tag it+`TODO(typescript-pending)`). Do NOT add a runtime check, fallback, coercion, or rejection+path to satisfy the checker; that is exactly transformations 5 and 6.++**Diff discipline. Self-check before claiming a file converted, and again _after_ `bin/lint+--fix`** (member and import reordering can introduce changes after your first read). Read+the conversion as a literal `git diff` of old vs new and classify every changed hunk as one+of: (a) erased type syntax: annotation, `Signature`, `declare`, `import type` for a+**newly added** type dependency (a pre-existing value import stays a value import); (b) a+formatting or import change **verified to preserve the emitted program, runtime import+order, module evaluation, and template output**; (c) a comment/JSDoc edit; (d) a mechanical+rename or module-specifier change **strictly required for the converted file to resolve**,+resolving to the same module and preserving runtime binding, evaluation order, and side+effects (identify each such hunk explicitly; this does not permit logic cleanup). **Anything+else (a changed conditional, default, guard, coercion, call argument, control-flow edge,+decorator, field order, mutation, logging call, async flow, or return shape) is a red flag+to revert.** If it seems a genuine improvement, raise it as a **separate** follow-up.++**Lint interaction:** `sort-class-members` may want an arrow-function field turned into an+`@action` method. During a conversion, do NOT make that swap; arrow-field to method changes+callback identity and `this`-binding. Keep the original member form, re-read the file after+`bin/lint --fix`, and re-run the diff check above, since the reorder itself can introduce a+behavior change.++## Rename mechanics: a single commit++git's rename detection is content similarity at diff time (50% threshold). For a **small+file**, adding types drops it below that (a 2-line `eq.js` to a typed `eq.ts` is under 50%+similar), so a single delete+add commit is not detected as a rename, and `git blame` /+GitHub / `git log --follow` show it as a fresh add.++The classic two-commit trick (commit 1 = pure `git mv` with byte-identical content, commit 2+= overwrite with the typed content) only helps on repos that keep branch commits. **Discourse+squash-merges PRs**, which collapses the whole branch into ONE commit on `main` and discards+the intermediate pure-rename commit. What lands on `main` is a single `delete .js` + `add+.ts (typed)`, so blame-through-rename depends solely on that one squashed commit's+similarity, which the branch's commit structure cannot change. The two-commit dance is pure+ceremony here.++**Therefore default to a SINGLE commit** (`git mv x.js x.ts`, overwrite with typed content,+`git add`, one commit). Do not split rename-then-types.++Practical consequence: blame-through-rename survives *only* when the typed file stays at or+above 50% similar to the original (`git status` shows `R`, not `D`+`A`). When it drops below,+as a real conversion of a small file usually does, blame breaks at the conversion commit no+matter what, and contorting the code to stay similar is not worth it. Do not promise blame+preservation you cannot deliver under squash. Files under roughly 40 alphanumeric characters+fall below git's copy-detection floor entirely (but have no meaningful history to lose).++## When to defer a whole conversion (scope triage)++Not every file is a clean "convert one file" job. Before starting, gauge the blast radius;+if it is large, **defer the file to its own coordinated PR** rather than dragging the scope+sideways into an otherwise-clean change. A clean conversion:++- pulls in **no internal untyped-component casts** (only untyped *helpers*, which need no+ cast; they resolve fine in templates), and+- produces **little or no consumer fallout** when its `Signature` tightens.++Defer when the file instead:++- **drags in several untyped internals** that each need a local `ComponentLike` or interface+ cast, and/or+- has a **large consumer surface** (dozens of call sites) where tightening leaks type errors+ across many files, and/or+- is **owned by another area** (FloatKit, FormKit) where the contract should be agreed with+ the owner.++A widely used FloatKit or FormKit primitive is the cautionary case: several sibling ui-kit+components with zero internal casts and one trivial fallout ship together in one PR; the+primitive with dozens of consumers gets its own.++## The runtime pitfall (the one that bites)++**`ember-tsc` does NOT catch runtime module-resolution errors in non-`@ts-check` `.js`/`.gjs`+consumers.** When you rename `x.gjs` to `x.gts`, any consumer that imported it with the+**explicit old extension**++```js+import X from "discourse/ui-kit/x.gjs"; // stale extension: breaks at runtime after rename+```++will pass `pnpm lint:types` (the consumer is not type-checked) but **throw a global "Failed+to resolve module specifier" at test/runtime**, breaking the whole bundle load (every test+in it fails or the run hangs to timeout). After any rename:++1. **Grep for extensioned imports** of the renamed file across the repo:+ `grep -rnE 'from "[^"]*x\.gjs"' frontend plugins themes` and fix each to+ **extensionless** (`from "discourse/ui-kit/x"`).+2. **Remove any stale `@type {import("...x.gjs")}` resolution workaround.** Such annotations+ existed only to paper over an old extensionless-resolution bug in glint (TS2307 "Cannot+ find module" on an extensionless `.gjs` import). Extensionless `.gjs` imports resolve now,+ so a `@type {import(...)}` that existed *solely* for resolution is dead weight: **delete+ it** (do not "update it to `.gts`"), then confirm `pnpm lint:types` is still green. An+ `@type {import(...)}` that documents a *real* type (e.g. an extensionless `@service` in a+ `.js` file) still stands; only the resolution stopgap is obsolete.+3. **Run the tests**, not just the type-check.diff --git a/AI-AGENTS.md b/AI-AGENTS.mdindex b9f1a8dba38..269ca94ffec 100644--- a/AI-AGENTS.md+++ b/AI-AGENTS.md@@ -26,6 +26,7 @@ Discourse is large with long history. Understand context before changes.- Prefer self-documenting code. Comments should only be added when future misunderstanding is likely. They should be terse, and should describe 'why', not 'what'. They should not be used to describe history.- In the frontend, typescript is typically used for platform-level code, javascript for business-logic- Platform-level frontend code should include accurate types & tsdoc descriptions for public APIs+- Use the skill at `.skills/discourse-writing-typescript` when authoring .ts/.gts or converting .js/.gjs to TypeScript- Simple JSDoc/TSDoc comments can be used in other code for editor intellisense, but this is not essential- In core, never name plugin features or specific libraries in comments/docs — describe by mechanism