A platform for community discussion. Free, open, simple.
DEV: Convert `ResultSet` and `LegacyArrayLikeObject` to TypeScript (#45193)
Sérgio Saquetim5738288bd1ca
diff --git a/frontend/discourse/app/lib/legacy-array-like-object.js b/frontend/discourse/app/lib/legacy-array-like-object.tssimilarity index 70%rename from frontend/discourse/app/lib/legacy-array-like-object.jsrename to frontend/discourse/app/lib/legacy-array-like-object.tsindex f9ee3483f0f..eca77939b43 100644--- a/frontend/discourse/app/lib/legacy-array-like-object.js+++ b/frontend/discourse/app/lib/legacy-array-like-object.ts@@ -5,16 +5,18 @@* already existing classes that previously used the ArrayProxy mixin. It should not* be used in new development.*- * For new code, use a standard class with tracked properties and @autoTrackedArray for the content property.+ * For new code, use a standard class with tracked properties and `@autoTrackedArray` for the content property.* Example:*- * import { tracked } from '@glimmer/tracking';- * import { autoTrackedArray } from "discourse/lib/tracked-tools";+ * ```js+ * import { tracked } from '@glimmer/tracking';+ * import { autoTrackedArray } from "discourse/lib/tracked-tools";*- * class MyArrayWrapper {- * @tracked someProp;- * @autoTrackedArray content = [];- * }+ * class MyArrayWrapper {+ * @tracked someProp;+ * @autoTrackedArray content = [];+ * }+ * ```** This approach provides reactivity and array capabilities without legacy proxy patterns.*/@@ -24,7 +26,7 @@ import { trackedArray } from "@ember/reactive/collections";import deprecated from "discourse/lib/deprecated";import { isTrackedArray } from "discourse/lib/tracked-tools";-const EMBER_OBJECT_PROPERTIES = new Set([+const EMBER_OBJECT_PROPERTIES = new Set<PropertyKey>(["constructor","addObserver","cacheFor",@@ -47,7 +49,7 @@ const EMBER_OBJECT_PROPERTIES = new Set(["mergedProperties",]);-const ARRAY_PROPERTIES = new Set(+const ARRAY_PROPERTIES = new Set<PropertyKey>([...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertySymbols(Array.prototype),@@ -60,25 +62,29 @@ const ARRAY_PROPERTIES = new Set(* LegacyArrayLikeObject is an EmberObject that proxies array-like behavior to a TrackedArray,* while exposing additional properties and methods. Access array methods via `.content`.*- * @class LegacyArrayLikeObject- * @extends EmberObject- * @example- * const obj = LegacyArrayLikeObject.create({ content: [1,2,3], foo: 'bar' });- * obj.content.push(4); // Use .content for array operations- * obj.foo // 'bar'- ** Note: Must be instantiated via LegacyArrayLikeObject.create().+ *+ * @example+ * ```js+ * const obj = LegacyArrayLikeObject.create({ content: [1,2,3], foo: 'bar' });+ * obj.content.push(4); // Use .content for array operations+ * obj.foo // 'bar'+ * ```*/-export default class LegacyArrayLikeObject extends EmberObject {+export default class LegacyArrayLikeObject<T = unknown> extends EmberObject {static #isConstructing = false; // to simulate a private constructor/*** Creates an instance of LegacyArrayLikeObject. Must be used instead of `new`.*- * @param {{ content?: unknown[] } & Record<string, unknown>} [attrs] - Properties to set on the instance. `content` must be an array.- * @returns {LegacyArrayLikeObject}+ * @param attrs - Properties applied after subclass fields initialize. `content` must be an array.*/- static create(attrs = {}) {+ static create<M extends LegacyArrayLikeObject>(+ this: new (...args: never[]) => M,+ attrs?: Partial<M> & Record<string, unknown>+ ): M;++ static create(attrs: { content?: unknown[] } & Record<string, unknown> = {}) {LegacyArrayLikeObject.#isConstructing = true;const { content, ...properties } = attrs;@@ -97,10 +103,11 @@ export default class LegacyArrayLikeObject extends EmberObject {/*** Emits a deprecation warning for direct array property access.*- * @param {LegacyArrayLikeObject} instance - The instance of LegacyArrayLikeObject (or subclass) being accessed- * @param {string|number|symbol} prop - The property being accessed on the instance- * @private+ * @param instance - The instance of LegacyArrayLikeObject (or subclass) being accessed+ * @param prop - The property being accessed on the instance+ * @internal* @example+ * ```js* // Will warn about accessing array methods directly:* const obj = CustomArrayLike.create({ content: [1,2,3] });* obj[0]; // Triggers deprecation warning@@ -109,8 +116,12 @@ export default class LegacyArrayLikeObject extends EmberObject {* // Should use content instead:* obj.content[0]; // Correct usage* obj.content.push(4); // Correct usage+ * ```*/- static warnArrayDeprecation(instance, prop) {+ static warnArrayDeprecation(+ instance: LegacyArrayLikeObject,+ prop: PropertyKey+ ) {const instanceName = instance.constructor.name;const propName = isNumericIndexProp(prop)? `[${prop}]`@@ -127,16 +138,19 @@ export default class LegacyArrayLikeObject extends EmberObject {);}- #content;+ /** The proxy supplies this array; replacing it throws. Mutate its elements instead. */+ declare readonly content: T[];++ #content: T[];/*** Constructor is private. Use LegacyArrayLikeObject.create() instead.*- * @param {Array} content - The array to wrap. Must be an array.- * @throws {TypeError} If not called via .create or if content is not an array.- * @private+ * @param content - The array to wrap. Must be an array.+ * @throws `TypeError` if not called via .create or if content is not an array.+ * @internal*/- constructor(content = []) {+ constructor(content: T[] = []) {super();if (!LegacyArrayLikeObject.#isConstructing) {@@ -161,22 +175,21 @@ export default class LegacyArrayLikeObject extends EmberObject {/*** Context string to add to array access deprecation warnings.* To be overridden by subclasses to provide additional context.- *- * @returns {string|undefined} The warning context string*/- get warnContext() {+ get warnContext(): string | undefined {// to be overridden by subclasses+ return undefined;}}/*** Checks if a property is an EmberObject property or a custom instance property.*- * @param {Object} instance - The object instance to check against.- * @param {string|symbol} prop - The property name or symbol.- * @returns {boolean} True if the property belongs to the instance, false otherwise.+ * @param instance - The object instance to check against.+ * @param prop - The property name or symbol.+ * @returns True if the property belongs to the instance, false otherwise.*/-function isInstanceProperty(instance, prop) {+function isInstanceProperty(instance: object, prop: PropertyKey): boolean {return (Reflect.has(instance, prop) &&(EMBER_OBJECT_PROPERTIES.has(prop) || !ARRAY_PROPERTIES.has(prop))@@ -186,10 +199,10 @@ function isInstanceProperty(instance, prop) {/*** Checks if a property is an Array property.*- * @param {string|symbol} prop - The property name or symbol.- * @returns {boolean} True if the property is an Array property, false otherwise.+ * @param prop - The property name or symbol.+ * @returns True if the property is an Array property, false otherwise.*/-function isArrayProperty(prop) {+function isArrayProperty(prop: PropertyKey): boolean {return ARRAY_PROPERTIES.has(prop);}@@ -197,10 +210,10 @@ function isArrayProperty(prop) {* Checks if a property is a numeric array index (string or number).* Accepts numeric strings or numbers (e.g. '0', 0, '12', 12).*- * @param {string|number} prop - The property to check.- * @returns {boolean} True if the property is a numeric index, false otherwise.+ * @param prop - The property to check.+ * @returns True if the property is a numeric index, false otherwise.*/-function isNumericIndexProp(prop) {+function isNumericIndexProp(prop: PropertyKey): prop is string | number {// Accepts numeric strings or numbers (e.g. '0', 0, '12', 12)return ((typeof prop === "string" && /^\d+$/.test(prop)) ||@@ -215,11 +228,15 @@ function isNumericIndexProp(prop) {* and array properties to the underlying array.* Emits deprecation warnings for direct array property access.*- * @param {LegacyArrayLikeObject} instance - The LegacyArrayLikeObject instance.- * @param {TrackedArray} trackedItems - The underlying tracked array.- * @returns {Proxy} Proxy object that combines instance and array behaviors.+ * @param instance - The LegacyArrayLikeObject instance.+ * @param trackedItems - The underlying tracked array.+ * @returns Proxy object that combines instance and array behaviors.*/-function createProxy(instance, trackedItems) {+function createProxy<T>(+ instance: LegacyArrayLikeObject<T>,+ trackedItems: T[]+): LegacyArrayLikeObject<T> {+ // The traps expose the instance's prototype and members over the array target.return new Proxy(trackedItems, {get(target, prop, receiver) {if (prop === "content") {@@ -231,7 +248,9 @@ function createProxy(instance, trackedItems) {}if (isArrayProperty(prop) || isNumericIndexProp(prop)) {- instance.constructor.warnArrayDeprecation(instance, prop);+ (+ instance.constructor as typeof LegacyArrayLikeObject+ ).warnArrayDeprecation(instance, prop);}return Reflect.get(target, prop, receiver);@@ -249,7 +268,9 @@ function createProxy(instance, trackedItems) {}if (isArrayProperty(prop) || isNumericIndexProp(prop)) {- instance.constructor.warnArrayDeprecation(instance, prop);+ (+ instance.constructor as typeof LegacyArrayLikeObject+ ).warnArrayDeprecation(instance, prop);}return Reflect.set(target, prop, value, receiver);@@ -284,5 +305,5 @@ function createProxy(instance, trackedItems) {}return Reflect.getOwnPropertyDescriptor(target, prop);},- });+ }) as unknown as LegacyArrayLikeObject<T>;}diff --git a/frontend/discourse/app/models/result-set.js b/frontend/discourse/app/models/result-set.tssimilarity index 51%rename from frontend/discourse/app/models/result-set.jsrename to frontend/discourse/app/models/result-set.tsindex c61b7a2f32c..7eec5bdb0b9 100644--- a/frontend/discourse/app/models/result-set.js+++ b/frontend/discourse/app/models/result-set.ts@@ -2,25 +2,26 @@ import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";import { dependentKeyCompat } from "@ember/object/compat";import LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";+import type StoreService from "discourse/services/store";-export default class ResultSet extends LegacyArrayLikeObject {- @tracked extras;- @tracked findArgs;+export default class ResultSet<T = unknown> extends LegacyArrayLikeObject<T> {+ /** Endpoint-specific response extras, optionally wrapped by the model's extras class. */+ @tracked extras: unknown;+ @tracked findArgs: object | null | undefined;- /** @type {string | null | undefined} */- @tracked loadMoreUrl = null;+ @tracked loadMoreUrl: string | null | undefined = null;@tracked loading = false;@tracked loadingMore = false;- /** @type {string | null | undefined} */- @tracked refreshUrl = null;+ @tracked refreshUrl: string | null | undefined = null;@tracked refreshing = false;- @tracked resultSetMeta;++ /** Unmodified endpoint-specific metadata; narrow it before reading its fields. */+ @tracked resultSetMeta: unknown;@tracked totalRows = 0;- /** @type {import("discourse/services/store").default | null} */- store = null;- __type;+ store: StoreService | null = null;+ __type: string | undefined;get warnContext() {return "__type: " + this.__type;@@ -32,7 +33,7 @@ export default class ResultSet extends LegacyArrayLikeObject {}@action- async loadMore() {+ async loadMore(): Promise<void> {const loadMoreUrl = this.loadMoreUrl;if (!loadMoreUrl) {return;@@ -42,8 +43,9 @@ export default class ResultSet extends LegacyArrayLikeObject {if (this.content.length < totalRows && !this.loadingMore) {this.loadingMore = true;+ // Store hydration supplies store and __type before pagination is used.try {- return await this.store.appendResults(this, this.__type, loadMoreUrl);+ return await this.store!.appendResults(this, this.__type!, loadMoreUrl);} finally {this.loadingMore = false;}@@ -51,7 +53,7 @@ export default class ResultSet extends LegacyArrayLikeObject {}@action- async refresh() {+ async refresh(): Promise<void> {if (this.refreshing) {return;}@@ -62,8 +64,9 @@ export default class ResultSet extends LegacyArrayLikeObject {}this.refreshing = true;+ // Store hydration supplies store and __type before refresh is used.try {- return await this.store.refreshResults(this, this.__type, refreshUrl);+ return await this.store!.refreshResults(this, this.__type!, refreshUrl);} finally {this.refreshing = false;}diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.tsindex f9450fb3d3b..a76bd3c4bdb 100644--- a/frontend/discourse/app/services/store.ts+++ b/frontend/discourse/app/services/store.ts@@ -133,12 +133,17 @@ export type ModelCreateAttrsFor<K extends string> = K extends unknown: RestModelAttrs<ModelFor<K>>: never;-/** The content property is supplied by the legacy array proxy at runtime. */-export type ResultSetOf<M> = ResultSet & { content: M[] };+/** A collection of hydrated models. */+export type ResultSetOf<M> = ResultSet<M>;type FindArgs = string | number | object | null | undefined;type StoreRecord = RestModel & RestPayload;type StoreResults = StoreRecord | ResultSetOf<StoreRecord>;+/** Legacy cached models on the stale-update path expose collection content. */+interface LegacyStoreCollection extends RestModel {+ content: StoreRecord[];+ [key: string]: unknown;+}type ModelClass = RestModelClass &Pick<typeof RestModel, "munge"> & {create(attrs?: RestPayload): RestModelInstance;@@ -390,7 +395,7 @@ export default class StoreService extends Service {}refreshResults(- resultSet: ResultSetOf<RestModel> | Pick<RestModel, "set">,+ resultSet: ResultSetOf<unknown> | Pick<RestModel, "set">,type: string,url: string) {@@ -409,7 +414,7 @@ export default class StoreService extends Service {});}- appendResults(resultSet: ResultSetOf<RestModel>, type: string, url: string) {+ appendResults(resultSet: ResultSetOf<unknown>, type: string, url: string) {const adapter = this.adapterFor(type);return ajax(url).then((result: RestPayload) => {const typeName = underscore(this.pluralize(adapter.apiNameFor(type)));@@ -526,15 +531,20 @@ export default class StoreService extends Service {stale: StoreResults | undefined,hydrated: StoreResults,primaryKey: string+ ): StoreResults;++ /** When stale data exists, this path assumes both values expose collection content. */+ _updateStale(+ stale: LegacyStoreCollection | undefined,+ hydrated: LegacyStoreCollection,+ primaryKey: string): StoreResults {if (!stale) {return hydrated;}- // TODO(typescript-pending): cached models expose collection content dynamically;- // remove these assertions when their collection shape is declared.- const newValues = (hydrated.get("content") as StoreRecord[]).map((item) => {- let staleItem = (stale as { content: StoreRecord[] }).content.find(+ const newValues = hydrated.get("content").map((item) => {+ let staleItem = stale.content.find((i) => i.primaryKey === item.get(primaryKey));if (staleItem) {@@ -606,9 +616,7 @@ export default class StoreService extends Service {}}- // TODO(typescript-pending): create returns the legacy base type; remove this- // assertion once ResultSet declares its subclass return and proxy content.- return ResultSet.create(createArgs) as ResultSetOf<StoreRecord>;+ return ResultSet.create<ResultSetOf<StoreRecord>>(createArgs);}_extrasClass(type: string) {diff --git a/frontend/discourse/type-tests/models/result-set-test.ts b/frontend/discourse/type-tests/models/result-set-test.tsnew file mode 100644index 00000000000..84d6775ebab--- /dev/null+++ b/frontend/discourse/type-tests/models/result-set-test.ts@@ -0,0 +1,119 @@+import type EmberObject from "@ember/object";+import { expectTypeOf } from "expect-type";+import LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";+import RestModel from "discourse/models/rest";+import ResultSet from "discourse/models/result-set";+import type {+ default as StoreService,+ ResultSetOf,+} from "discourse/services/store";++class Gadget extends RestModel {+ declare label: string;+}++/** A subclass with its own fields, as CategoryList and ColorSchemes are. */+class Gadgets extends LegacyArrayLikeObject<Gadget> {+ page = 1;+ loading = false;+}++declare const store: StoreService;+declare const gadget: Gadget;+declare const results: ResultSet<Gadget>;++/* Construction: `create` returns the receiving subclass. */++expectTypeOf(LegacyArrayLikeObject.create()).toExtend<LegacyArrayLikeObject>();+expectTypeOf(+ LegacyArrayLikeObject.create({ content: [1, 2, 3], foo: "bar" })+).toExtend<LegacyArrayLikeObject>();+expectTypeOf(Gadgets.create({ content: [gadget] })).toEqualTypeOf<Gadgets>();+expectTypeOf(Gadgets.create().page).toEqualTypeOf<number>();+// Attributes other than content are applied after construction.+Gadgets.create({ content: [gadget], page: 2, loading: true });+expectTypeOf(ResultSet.create({ content: [] })).toExtend<ResultSet>();+// Non-array content throws at runtime.+// @ts-expect-error content must be an array+LegacyArrayLikeObject.create({ content: "x" });+// @ts-expect-error null content throws too+LegacyArrayLikeObject.create({ content: null });+// @ts-expect-error a subclass's content holds its element type+Gadgets.create({ content: ["x"] });+expectTypeOf(Gadgets).toExtend<typeof LegacyArrayLikeObject<Gadget>>();+expectTypeOf(Gadgets.create()).toExtend<EmberObject>();++/* Content: the proxied array is reached through `content`. */++expectTypeOf(Gadgets.create().content).toEqualTypeOf<Gadget[]>();+expectTypeOf(results.content).toEqualTypeOf<Gadget[]>();+results.content.push(gadget);+results.content.splice(0, Infinity, gadget);+expectTypeOf(results.content.find((g) => g.label === "x")).toEqualTypeOf<+ Gadget | undefined+>();+// Assigning content through the proxy throws.+// @ts-expect-error content is read-only+results.content = [];+// Direct array access is deprecated, so typed code goes through content.+// @ts-expect-error no direct array surface+expectTypeOf(results.length).toBeNumber();+// @ts-expect-error no direct array surface+results.filter(Boolean);+expectTypeOf(Gadgets.create().warnContext).toEqualTypeOf<string | undefined>();++/* ResultSet state. */++expectTypeOf(results).toExtend<LegacyArrayLikeObject<Gadget>>();+expectTypeOf(results.totalRows).toEqualTypeOf<number>();+expectTypeOf(results.loadMoreUrl).toEqualTypeOf<string | null | undefined>();+expectTypeOf(results.refreshUrl).toEqualTypeOf<string | null | undefined>();+expectTypeOf(results.loading).toEqualTypeOf<boolean>();+expectTypeOf(results.loadingMore).toEqualTypeOf<boolean>();+expectTypeOf(results.refreshing).toEqualTypeOf<boolean>();+// findAll forwards no args; find forwards its object or null.+expectTypeOf(results.findArgs).toEqualTypeOf<object | null | undefined>();+expectTypeOf(results.extras).not.toBeAny();+expectTypeOf(results.resultSetMeta).not.toBeAny();+// Response extras are assigned as received, or wrapped by an extras class.+results.extras = { type_filters: ["my"] };+expectTypeOf(results.store).toEqualTypeOf<StoreService | null>();+expectTypeOf(results.__type).toEqualTypeOf<string | undefined>();+expectTypeOf(results.warnContext).toEqualTypeOf<string>();+expectTypeOf(results.canLoadMore).toEqualTypeOf<boolean>();+expectTypeOf(results.loadMore()).resolves.toEqualTypeOf<void>();+expectTypeOf(results.refresh()).resolves.toEqualTypeOf<void>();+expectTypeOf(results.loadMore).parameters.toEqualTypeOf<[]>();++/* Store collections. */++expectTypeOf<ResultSetOf<Gadget>>().toExtend<ResultSet>();+expectTypeOf<ResultSet<Gadget>>().toExtend<ResultSetOf<Gadget>>();+expectTypeOf<ResultSetOf<Gadget>["content"]>().toEqualTypeOf<Gadget[]>();+expectTypeOf(+ store.appendResults(results, "gadget", "/gadgets?page=2")+).resolves.toEqualTypeOf<void>();+expectTypeOf(+ store.refreshResults(results, "gadget", "/gadgets")+).resolves.toEqualTypeOf<void>();++/* Subclass chains and the inherited factory. */++class Numbers extends LegacyArrayLikeObject<number> {+ page = 1;+}++class NestedNumbers extends Numbers {+ get warnContext() {+ return "numbers";+ }+}++const numbersClass: typeof LegacyArrayLikeObject<number> = Numbers;+expectTypeOf(numbersClass.create()).toExtend<EmberObject>();+expectTypeOf(+ NestedNumbers.create({ content: [1], page: 2 })+).toEqualTypeOf<NestedNumbers>();+expectTypeOf(+ ResultSet.create<ResultSet<number>>({ content: [1] }).content+).toEqualTypeOf<number[]>();