A platform for community discussion. Free, open, simple.
DEV: Convert `Site` to TypeScript (#45060)
Sérgio Saquetim3592c77a4589
diff --git a/frontend/discourse/app/models/category.ts b/frontend/discourse/app/models/category.tsindex b65ae613a98..cc0fc368fcf 100644--- a/frontend/discourse/app/models/category.ts+++ b/frontend/discourse/app/models/category.ts@@ -102,15 +102,6 @@ export interface CategoryTypeMetadata {[key: string]: unknown;}-/** TODO(typescript-pending): singleton adds these statics at runtime; remove when Site exposes them. */-type CategorySiteClass = typeof Site & {- current(): Site & {- lazy_load_categories?: boolean;- loadedCategoryIds?: Set<number | string>;- };- currentProp(key: string): unknown;-};-type CategorySearchOptions = {parentCategoryId?: number;includeUncategorized?: boolean;@@ -278,10 +269,7 @@ export default class Category extends RestModel {}static isUncategorized(categoryId: number | null | undefined): boolean {- return (- categoryId ===- (Site as CategorySiteClass).currentProp("uncategorized_category_id")- );+ return categoryId === Site.currentProp("uncategorized_category_id");}static slugEncoded(): boolean {@@ -296,8 +284,7 @@ export default class Category extends RestModel {_uncategorized ||Category.list().find((category) =>- category.id ===- (Site as CategorySiteClass).currentProp("uncategorized_category_id")+ category.id === Site.currentProp("uncategorized_category_id"));return _uncategorized;}@@ -331,25 +318,15 @@ export default class Category extends RestModel {}static list(): Category[] {- // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.- return (Site as CategorySiteClass).currentProp(- "categoriesList"- ) as Category[];+ return Site.currentProp("categoriesList");}static listByActivity(): Category[] {- // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.- return (Site as CategorySiteClass).currentProp(- "sortedCategories"- ) as Category[];+ return Site.currentProp("sortedCategories");}- static _idMap(): Map<number, Category> {- // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.- return (Site as CategorySiteClass).currentProp("categoriesById") as Map<- number,- Category- >;+ static _idMap(): Map<number | undefined, Category> {+ return Site.currentProp("categoriesById");}static findSingleBySlug(slug: string): Category | undefined {@@ -382,9 +359,9 @@ export default class Category extends RestModel {}static hasAsyncFoundAll(ids: (number | string)[]): boolean {- const loadedCategoryIds =- (Site as CategorySiteClass).current().loadedCategoryIds || new Set();- return ids.every((id) => loadedCategoryIds.has(id));+ const loadedCategoryIds = Site.current().loadedCategoryIds || new Set();+ // Only parsed numeric ids are loaded, so a string id never matches.+ return ids.every((id) => loadedCategoryIds.has(id as number));}static async asyncFindByIds(@@ -392,7 +369,7 @@ export default class Category extends RestModel {): Promise<Category[]> {// parseInt also coerces numeric IDs supplied by callers.ids = ids.map((x) => parseInt(x as string, 10));- const site = (Site as CategorySiteClass).current();+ const site = Site.current();if (!site.lazy_load_categories || this.hasAsyncFoundAll(ids)) {return this.findByIds(ids);@@ -420,7 +397,8 @@ export default class Category extends RestModel {} else {site.removeCategory(id);}- loadedCategoryIds.add(id);+ // `ids` holds the numbers parsed at the top of this method.+ loadedCategoryIds.add(id as number);}site.set("loadedCategoryIds", loadedCategoryIds);@@ -480,10 +458,7 @@ export default class Category extends RestModel {const categories = result["categories"].map((category: CategoryFields | Category) => {- // TODO(typescript-pending): Site.updateCategory returns the model without types.- category = (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category;+ category = Site.current().updateCategory(category);// `Category` extends `CategoryFields`, so the reassignment above does not// narrow the union; `updateCategory` returns the model.if (opts.includePermissions) {@@ -504,12 +479,8 @@ export default class Category extends RestModel {data: { slug_path_with_id: slugPathWithID },})) as { categories: CategoryFields[] };- const categories = result["categories"].map(- (category) =>- // TODO(typescript-pending): Site.updateCategory returns the model without types.- (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category+ const categories = result["categories"].map((category) =>+ Site.current().updateCategory(category));return categories[categories.length - 1];@@ -619,8 +590,7 @@ export default class Category extends RestModel {store: StoreService,site: Site): Category {- // TODO(typescript-pending): Site.updateCategory returns the model without types.- const model = site.updateCategory(category) as Category;+ const model = site.updateCategory(category);model.setupGroupsAndPermissions();model.setupCategoryTypes();return model;@@ -728,12 +698,8 @@ export default class Category extends RestModel {);const result = CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[cacheKey];- return result["categories"].map(- (category) =>- // TODO(typescript-pending): Site.updateCategory returns the model without types.- (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category+ return result["categories"].map((category) =>+ Site.current().updateCategory(category));}@@ -782,29 +748,17 @@ export default class Category extends RestModel {if (opts.includeAncestors) {return {- ancestors: result["ancestors"].map(- (category) =>- // TODO(typescript-pending): Site.updateCategory returns the model without types.- (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category+ ancestors: result["ancestors"].map((category) =>+ Site.current().updateCategory(category)),- categories: result["categories"].map(- (category) =>- // TODO(typescript-pending): Site.updateCategory returns the model without types.- (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category+ categories: result["categories"].map((category) =>+ Site.current().updateCategory(category)),categoriesCount: result["categories_count"],};} else {- return result["categories"].map(- (category) =>- // TODO(typescript-pending): Site.updateCategory returns the model without types.- (Site as CategorySiteClass)- .current()- .updateCategory(category) as Category+ return result["categories"].map((category) =>+ Site.current().updateCategory(category));}}@@ -876,10 +830,7 @@ export default class Category extends RestModel {get subcategories(): Category[] {return applyValueTransformer("category-subcategories",- // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.- (- this.site.categoriesByParentId as Map<number | undefined, Category[]>- ).get(this.id) || [],+ this.site.categoriesByParentId.get(this.id) || [],{ category: this });}@@ -1369,15 +1320,8 @@ export default class Category extends RestModel {permissions.forEach((p) => (rval[p.group_name] = p.permission_type));} else {// empty permissions => staff-only access- // TODO(typescript-pending): Site's group map omits its entry types; remove when Site is typed.- rval[- (- (Site as CategorySiteClass).currentProp("groupsById") as Record<- number,- { name: string }- >- )[AUTO_GROUPS.staff.id].name- ] = PermissionType.FULL;+ rval[Site.currentProp("groupsById")[AUTO_GROUPS.staff.id].name] =+ PermissionType.FULL;}return rval;}diff --git a/frontend/discourse/app/models/site.js b/frontend/discourse/app/models/site.jsdeleted file mode 100644index c67b0a197ca..00000000000--- a/frontend/discourse/app/models/site.js+++ /dev/null@@ -1,347 +0,0 @@-import { cached, tracked } from "@glimmer/tracking";-import EmberObject, { computed, get, set } from "@ember/object";-import { dependentKeyCompat } from "@ember/object/compat";-import { trackedArray } from "@ember/reactive/collections";-import { service } from "@ember/service";-import { trustHTML } from "@ember/template";-import { isEmpty } from "@ember/utils";-import {- arraySortedByProperties,- removeValueFromArray,-} from "discourse/lib/array-tools";-import { AUTO_GROUPS } from "discourse/lib/constants";-import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";-import { isRailsTesting, isTesting } from "discourse/lib/environment";-import { getOwnerWithFallback } from "discourse/lib/get-owner";-import Mobile from "discourse/lib/mobile";-import PreloadStore from "discourse/lib/preload-store";-import singleton from "discourse/lib/singleton";-import { autoTrackedArray } from "discourse/lib/tracked-tools";-import Archetype from "discourse/models/archetype";-import Category from "discourse/models/category";-import PostActionType from "discourse/models/post-action-type";-import RestModel from "discourse/models/rest";-import TrustLevel from "discourse/models/trust-level";--@singleton-export default class Site extends RestModel {- static createCurrent() {- const store = getOwnerWithFallback(this).lookup("service:store");- const siteAttributes = PreloadStore.get("site");- siteAttributes["isReadOnly"] = PreloadStore.get("isReadOnly");- siteAttributes["isStaffWritesOnly"] = PreloadStore.get("isStaffWritesOnly");- return store.createRecord("site", siteAttributes);- }-- /**- * @template {import("discourse/models/rest").RestModelClass} C- * @this {C}- * @returns {InstanceType<C>}- */- static create() {- const result = super.create.apply(this, arguments);-- if (result.categories) {- result.categories = result.categories.map((c) => {- return result.store.createRecord("category", c);- });- }-- if (result.trust_levels) {- result.trustLevels = Object.entries(result.trust_levels).map(- ([key, id]) => {- return new TrustLevel(id, key);- }- );- delete result.trust_levels;- }-- if (result.post_action_types) {- result.postActionByIdLookup = EmberObject.create();- result.post_action_types = result.post_action_types.map((p) => {- const actionType = PostActionType.create(p);- result.postActionByIdLookup.set("action" + p.id, actionType);- return actionType;- });- }-- if (result.topic_flag_types) {- result.topicFlagByIdLookup = EmberObject.create();- result.topic_flag_types = result.topic_flag_types.map((p) => {- const actionType = PostActionType.create(p);- result.topicFlagByIdLookup.set("action" + p.id, actionType);- return actionType;- });- }-- if (result.archetypes) {- result.archetypes = result.archetypes.map((a) => {- a.site = result;- return Archetype.create(a);- });- }-- if (result.user_fields) {- result.user_fields = result.user_fields.map((uf) =>- EmberObject.create(uf)- );- }-- return result;- }-- @service siteSettings;- @service capabilities;-- @tracked topicCountDesc = ["topic_count:desc"];- @autoTrackedArray categories = [];- @autoTrackedArray groups = [];-- #siteInitialized = false;-- @computed("is_readonly")- get isReadOnly() {- return this.is_readonly;- }-- set isReadOnly(value) {- set(this, "is_readonly", value);- }-- get categoriesByCount() {- return arraySortedByProperties(this.categories, this.topicCountDesc);- }-- get groupsById() {- const map = {};- Object.values(AUTO_GROUPS).forEach((g) => (map[g.id] = g));- this.groups?.forEach((g) => (map[g.id] = g));- return map;- }-- @dependentKeyCompat- get desktopView() {- return !this.mobileView;- }-- @dependentKeyCompat- get mobileView() {- this.#siteInitialized ||= getOwnerWithFallback(this).lookup(- "-application-instance:main"- )?._booted;-- if (!this.#siteInitialized) {- if (isTesting() || isRailsTesting()) {- throw new Error(- "Accessing `site.mobileView` or `site.desktopView` during the site initialization phase. " +- "Move these checks to a component, transformer, or API callback that executes during page rendering."- );- }-- deprecated(- "Accessing `site.mobileView` or `site.desktopView` during the site initialization " +- "can lead to errors and inconsistencies when the browser window is " +- "resized. Please move these checks to a component, transformer, or API callback that executes during page" +- " rendering.",- {- since: "3.5.0.beta9-dev",- id: "discourse.static-viewport-initialization",- url: "https://meta.discourse.org/t/367810",- }- );- }-- if (Mobile.mobileForced) {- return true;- }-- return withSilencedDeprecations(- "discourse.static-viewport-initialization",- () => !this.capabilities.viewport.sm- );- }-- @dependentKeyCompat- get isMobileDevice() {- deprecated(- "Site.isMobileDevice is deprecated. Use `site.mobileView` and `site.desktopView` instead for " +- "viewport-based values or `capabilities.isMobileDevice` for user-agent based detection.",- {- id: "discourse.site.is-mobile-device",- since: "3.5.0.beta9-dev",- url: "https://meta.discourse.org/t/367810",- }- );-- return this.mobileView;- }-- @dependentKeyCompat- get categoriesById() {- return new Map(this.categories.map((c) => [c.id, c]));- }-- @computed("[email protected]_category_id")- get categoriesByParentId() {- const map = new Map();- for (const category of this.categories) {- const siblings = map.get(category.parent_category_id) || [];- siblings.push(category);- map.set(category.parent_category_id, siblings);- }- return map;- }-- @computed("notification_types")- get notificationLookup() {- const result = [];- Object.keys(this.notification_types).forEach(- (k) => (result[this.notification_types[k]] = k)- );- return result;- }-- @computed("post_action_types.[]")- get flagTypes() {- const postActionTypes = this.post_action_types;- if (!postActionTypes) {- return [];- }- return trackedArray(postActionTypes.filter((type) => type.is_flag));- }-- // Sort subcategories under parents- @cached- get sortedCategories() {- return Category.sortCategories(this.categoriesByCount);- }-- // Returns it in the correct order, by setting- @computed("categories.[]")- get categoriesList() {- return this.siteSettings.fixed_category_positions- ? this.categories- : this.sortedCategories;- }-- @computed("categories.[]", "[email protected]_level")- get trackedCategoriesList() {- const trackedCategories = [];-- for (const category of this.categories) {- if (category.isTracked) {- if (- this.siteSettings.allow_uncategorized_topics ||- !category.isUncategorizedCategory- ) {- trackedCategories.push(category);- }- }- }-- return trackedCategories;- }-- get topTags() {- return this.#transformTags(this.top_tags);- }-- get categoryTopTags() {- return this.#transformTags(this.category_top_tags);- }-- groupName(groupId) {- const group = this.groupsById[groupId];- return group ? group.name : null;- }-- groupFullName(groupId) {- const group = this.groupsById[groupId];- return group ? group.full_name : null;- }-- collectUserFields(fields) {- fields = fields || {};-- let siteFields = this.user_fields;-- if (!isEmpty(siteFields)) {- return siteFields.map((f) => {- let value = fields ? fields[f.id.toString()] : null;- value = value || trustHTML("—");- return { name: f.name, value };- });- }- return [];- }-- postActionTypeById(id) {- return this.get("postActionByIdLookup.action" + id);- }-- topicFlagTypeById(id) {- return this.get("topicFlagByIdLookup.action" + id);- }-- removeCategory(id) {- const categories = this.categories;- const existingCategory = categories.find((c) => c.id === id);- if (existingCategory) {- removeValueFromArray(categories, existingCategory);- }- }-- updateCategory(newCategory) {- if (newCategory instanceof Category) {- throw new Error(- "updateCategory should be passed a pojo, not a category model instance"- );- }-- const categories = this.categories;- const categoryId = get(newCategory, "id");- const existingCategory = categories.find((c) => c.id === categoryId);-- if (newCategory.permission === null) {- delete newCategory.permission;- }-- if (newCategory.has_children == null) {- delete newCategory.has_children;- }-- if (existingCategory) {- existingCategory.setProperties(newCategory);- existingCategory.setupCategoryTypes();- return existingCategory;- } else {- newCategory = this.store.createRecord("category", newCategory);- categories.push(newCategory);- return newCategory;- }- }-- #transformTags(tags) {- if (!tags) {- return [];- }- return tags.map((tag) => this.store.createRecord("tag", tag));- }-}--if (typeof Discourse !== "undefined") {- let warned = false;- // eslint-disable-next-line no-undef- Object.defineProperty(Discourse, "Site", {- get() {- if (!warned) {- deprecated("Import the Site class instead of using Discourse.Site", {- since: "2.4.0",- id: "discourse.global.site",- });- warned = true;- }- return Site;- },- });-}diff --git a/frontend/discourse/app/models/site.ts b/frontend/discourse/app/models/site.tsnew file mode 100644index 00000000000..1a03d13f454--- /dev/null+++ b/frontend/discourse/app/models/site.ts@@ -0,0 +1,677 @@+import { cached, tracked } from "@glimmer/tracking";+import EmberObject, { computed, get, set } from "@ember/object";+import { dependentKeyCompat } from "@ember/object/compat";+import { trackedArray } from "@ember/reactive/collections";+import { service } from "@ember/service";+import { type TrustedHTML, trustHTML } from "@ember/template";+import { isEmpty } from "@ember/utils";+import {+ arraySortedByProperties,+ removeValueFromArray,+} from "discourse/lib/array-tools";+import { AUTO_GROUPS } from "discourse/lib/constants";+import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";+import { isRailsTesting, isTesting } from "discourse/lib/environment";+import { getOwnerWithFallback } from "discourse/lib/get-owner";+import Mobile from "discourse/lib/mobile";+import PreloadStore from "discourse/lib/preload-store";+import singleton from "discourse/lib/singleton";+import { autoTrackedArray } from "discourse/lib/tracked-tools";+import Archetype from "discourse/models/archetype";+import Category, {+ type CategoryFields,+ type CategoryTypeMetadata,+} from "discourse/models/category";+import PostActionType from "discourse/models/post-action-type";+import RestModel, {+ type RestModelAttrs,+ type RestModelClass,+} from "discourse/models/rest";+import type Tag from "discourse/models/tag";+import TrustLevel from "discourse/models/trust-level";+import type { CapabilitiesService } from "discourse/services/capabilities";+import type StoreService from "discourse/services/store";++/** A group as `SiteSerializer#groups` lists it. */+export interface SiteGroup {+ id: number;+ name: string;+ full_name: string;+ display_name: string;+ flair_url: string | null;+ flair_bg_color: string | null;+ flair_color: string | null;+ automatic: boolean;+}++/** An automatic group, which has only these keys until the server's group replaces it. */+export type SiteGroupLookupEntry = Pick<+ SiteGroup,+ "id" | "name" | "automatic"+> &+ Partial<Omit<SiteGroup, "id" | "name" | "automatic">>;++/** A custom user field, as `UserFieldSerializer` sends it. */+export interface SiteUserField {+ id: number;+ name: string;+ description: string;+ field_type:+ | "text"+ | "confirm"+ | "dropdown"+ | "multiselect"+ | "textarea"+ | "date";+ editable: boolean;+ required: boolean;+ requirement: "optional" | "for_all_users" | "on_signup";+ show_on_profile: boolean;+ show_on_user_card: boolean;+ show_on_signup: boolean;+ searchable: boolean;+ position: number | null;+ options?: string[];+}++/** A login method, as `AuthProviderSerializer` sends it. */+export interface SiteAuthProvider {+ can_connect: boolean;+ can_revoke: boolean;+ custom_url: string | null;+ frame_height: number | null;+ frame_width: number | null;+ icon_override: string | null;+ name: string;+ pretty_name_override: string | null;+ provider_url: string | null;+ title_override: string | null;+}++/** A tag in a top tags list. */+export interface SiteTopTag {+ id: number;+ name: string;+ slug: string;+}++/** A tag as the navigation menu lists it. */+export interface SiteSidebarTag extends SiteTopTag {+ description: string | null;+ pm_only: boolean;+}++/** A public navigation menu section, shown to anonymous visitors. */+export interface SiteSidebarSection {+ id: number;+ title: string;+ links: {+ id: number;+ name: string;+ value: string;+ icon: string;+ external: boolean;+ segment: "primary" | "secondary";+ locale: string | null;+ }[];+ slug: string;+ public: boolean;+ section_type: "community" | null;+ locale: string | null;+}++/** A theme visitors can choose. */+export interface SiteUserTheme {+ theme_id: number;+ name: string;+ default: boolean;+ color_scheme_id: number | null;+ dark_color_scheme_id: number | null;+ only_theme_color_schemes: boolean;+}++/** A color in a color scheme. `default_hex` is null when the base palette lacks the color. */+export interface SiteColor {+ name: string;+ hex: string;+ default_hex: string | null;+ is_advanced: boolean;+}++/** A color scheme visitors can choose. */+export interface SiteSelectableColorScheme {+ id: number;+ name: string;+ is_dark: boolean | null;+ theme_id: number | null;+ colors: SiteColor[];+}++/** The default theme's light or dark color scheme. */+export interface SiteColorScheme extends SiteSelectableColorScheme {+ is_base: boolean | null;+ base_scheme_id: number | null;+ theme_name: string | null;+ user_selectable: boolean;+ is_builtin_default: boolean | null;+}++/** A watched word, keyed in its list by the word's regular expression. */+export interface SiteWatchedWord {+ word: string;+ replacement?: string;+ case_sensitive: boolean;+ html?: true;+}++/** An access control entry that a target type always or never allows. */+export interface SiteAclEntry {+ type: "group" | "user";+ id: number;+ permission: string;+}++/** A category type as the site lists it, with every metadata key present. */+export interface SiteCategoryType extends CategoryTypeMetadata {+ description: string;+ icon: string | null;+}++/** The site banner; an empty object when no banner is set. */+export type SiteBanner = EmberObject & {+ html?: string;+ key?: number;+ url?: string;+};++/** A user's custom field values, keyed by user field id. */+export type SiteUserFieldValues = Record<+ string,+ string | string[] | boolean | null | undefined+>;++/**+ * Data fields on the site, as `SiteSerializer` sends them and as `create`+ * and core code reshape them.+ *+ * Most are optional because an anonymous visitor on a login-required site+ * receives only a few of them. Plugins add their own fields by augmenting this+ * interface.+ */+export interface SiteFields {+ default_archetype?: string;+ notification_types?: Record<string, number>;+ post_types?: Record<string, number>;+ user_tips?: Record<string, number>;+ /** Built by `create` from the server's `trust_levels`, which it removes. */+ trustLevels?: TrustLevel[];+ groups: SiteGroup[];+ filters: string[];+ anonymous_list_filters: string[];+ homepage_choices?: string[];+ homepage_options?: {+ id: string;+ path: string | null;+ server_side: boolean;+ }[];+ periods: string[];+ top_menu_items?: string[];+ anonymous_top_menu_items?: string[];+ uncategorized_category_id?: number;+ user_field_max_length?: number;+ post_action_types?: PostActionType[];+ topic_flag_types?: PostActionType[];+ can_create_tag?: boolean;+ can_search?: boolean;+ can_tag_topics?: boolean;+ can_tag_pms?: boolean;+ tags_filter_regexp?: string;+ top_tags?: SiteTopTag[];+ navigation_menu_site_top_tags?: SiteSidebarTag[];+ can_associate_groups?: boolean;+ wizard_required?: true;+ topic_featured_link_allowed_category_ids?: number[];+ user_themes?: SiteUserTheme[];+ user_color_schemes?: SiteSelectableColorScheme[];+ default_light_color_scheme?: SiteColorScheme | null;+ default_dark_color_scheme?: SiteColorScheme | null;+ censored_regexp?: Record<string, { case_sensitive: boolean }>[];+ shared_drafts_category_id?: number;+ custom_emoji_translation?: Record<string, string>;+ watched_words_replace?: Record<string, SiteWatchedWord> | null;+ watched_words_link?: Record<string, SiteWatchedWord> | null;+ categories: Category[];+ markdown_additional_options?: Record<string, unknown>;+ hashtag_configurations?: Record<string, string[]>;+ hashtag_icons?: Record<string, string>;+ anonymous_default_navigation_menu_tags?: SiteSidebarTag[];+ anonymous_sidebar_sections?: SiteSidebarSection[];+ whispers_allowed_groups_names?: string[];+ denied_emojis?: string[];+ tos_url?: string | null;+ privacy_policy_url?: string | null;+ system_user_avatar_template?: string;+ lazy_load_categories?: true;+ valid_flag_applies_to_types?: string[];+ full_name_required_for_signup: boolean;+ full_name_visible_in_signup: boolean;+ admin_config_login_routes?: string[];+ email_configured?: boolean;+ upcoming_changes_with_css: string[];+ permanent_upcoming_change_names?: string[];+ access_control?: {+ mandatory_acl: Record<string, SiteAclEntry[]>;+ banned_acl: Record<string, SiteAclEntry[]>;+ };+ category_types?: SiteCategoryType[];+ archetypes?: Archetype[];+ user_fields: (EmberObject & SiteUserField)[];+ auth_providers: SiteAuthProvider[];+ postActionByIdLookup?: EmberObject;+ topicFlagByIdLookup?: EmberObject;+ /** Ids of the categories loaded on demand when the site lazy-loads categories. */+ loadedCategoryIds?: Set<number>;+ narrowDesktopView?: boolean;+ banner?: SiteBanner | null;+ /** The top tags of the current category's topic list. */+ category_top_tags?: SiteTopTag[];+ is_readonly?: boolean;+ isStaffWritesOnly?: boolean;+}++/** The site's settings, as `RestModel` types them. */+type SiteSettings = RestModel["siteSettings"];++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/no-empty-object-type+export default interface Site extends SiteFields {}++@singleton+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class Site extends RestModel {+ /** The site, created on first use. Added by `@singleton`. */+ declare static current: () => Site;++ /**+ * Reads a site property, or sets it when a value is given. Added by+ * `@singleton`. Any other string, such as a property path, reads or sets an+ * untyped value.+ */+ declare static currentProp: {+ <K extends keyof Site>(property: K): Site[K];+ <K extends keyof Site>(property: K, value: Site[K]): Site[K];+ <P extends string>(+ property: P extends keyof Site ? never : P,+ value?: unknown+ ): unknown;+ };++ /** Replaces the site returned by `current`. Added by `@singleton`. */+ declare static resetCurrent: <T extends Site | null | undefined = undefined>(+ value?: T+ ) => T;++ static createCurrent(): Site {+ const store = getOwnerWithFallback(this).lookup(+ "service:store"+ ) as StoreService;+ const siteAttributes = PreloadStore.get("site");+ siteAttributes["isReadOnly"] = PreloadStore.get("isReadOnly");+ siteAttributes["isStaffWritesOnly"] = PreloadStore.get("isStaffWritesOnly");+ return store.createRecord("site", siteAttributes);+ }++ static override create<C extends RestModelClass>(+ this: C,+ ...args: [attrs?: RestModelAttrs<InstanceType<C>>]+ ): InstanceType<C> {+ // The server's payload is still raw here; the blocks below replace its+ // arrays with model instances and its trust levels with `trustLevels`.+ const result = super.create.apply(this, args) as unknown as Site & {+ trust_levels?: Record<string, number>;+ };++ if (result.categories) {+ result.categories = (+ result.categories as unknown as RestModelAttrs<Category>[]+ ).map((c) => {+ return result.store.createRecord("category", c);+ });+ }++ if (result.trust_levels) {+ result.trustLevels = Object.entries(result.trust_levels).map(+ ([key, id]) => {+ return new TrustLevel(id, key);+ }+ );+ delete result.trust_levels;+ }++ if (result.post_action_types) {+ result.postActionByIdLookup = EmberObject.create();+ result.post_action_types = (+ result.post_action_types as unknown as { id: number }[]+ ).map((p) => {+ const actionType = PostActionType.create(p);+ result.postActionByIdLookup!.set("action" + p.id, actionType);+ return actionType;+ });+ }++ if (result.topic_flag_types) {+ result.topicFlagByIdLookup = EmberObject.create();+ result.topic_flag_types = (+ result.topic_flag_types as unknown as { id: number }[]+ ).map((p) => {+ const actionType = PostActionType.create(p);+ result.topicFlagByIdLookup!.set("action" + p.id, actionType);+ return actionType;+ });+ }++ if (result.archetypes) {+ result.archetypes = (+ result.archetypes as unknown as { site?: Site }[]+ ).map((a) => {+ a.site = result;+ // TODO(typescript-pending): RestCompatModel.create is untyped; remove when it returns the subclass.+ return Archetype.create(a) as Archetype;+ });+ }++ if (result.user_fields) {+ result.user_fields = (result.user_fields as SiteUserField[]).map(+ (uf) => EmberObject.create(uf as object) as EmberObject & SiteUserField+ );+ }++ return result as unknown as InstanceType<C>;+ }++ @service declare siteSettings: SiteSettings;+ @service declare capabilities: CapabilitiesService;++ @tracked topicCountDesc: string[] = ["topic_count:desc"];+ @autoTrackedArray categories: Category[] = [];+ @autoTrackedArray groups: SiteGroup[] = [];++ #siteInitialized: boolean | undefined = false;++ @computed("is_readonly")+ get isReadOnly(): boolean | undefined {+ return this.is_readonly;+ }++ set isReadOnly(value: boolean | undefined) {+ set(this, "is_readonly", value);+ }++ get categoriesByCount(): Category[] {+ return arraySortedByProperties(this.categories, this.topicCountDesc);+ }++ get groupsById(): Record<number, SiteGroupLookupEntry> {+ const map: Record<number, SiteGroupLookupEntry> = {};+ Object.values(AUTO_GROUPS).forEach((g) => (map[g.id] = g));+ this.groups?.forEach((g) => (map[g.id] = g));+ return map;+ }++ @dependentKeyCompat+ get desktopView(): boolean {+ return !this.mobileView;+ }++ @dependentKeyCompat+ get mobileView(): boolean {+ this.#siteInitialized ||= (+ getOwnerWithFallback(this).lookup("-application-instance:main") as+ | { _booted?: boolean }+ | undefined+ )?._booted;++ if (!this.#siteInitialized) {+ if (isTesting() || isRailsTesting()) {+ throw new Error(+ "Accessing `site.mobileView` or `site.desktopView` during the site initialization phase. " ++ "Move these checks to a component, transformer, or API callback that executes during page rendering."+ );+ }++ deprecated(+ "Accessing `site.mobileView` or `site.desktopView` during the site initialization " ++ "can lead to errors and inconsistencies when the browser window is " ++ "resized. Please move these checks to a component, transformer, or API callback that executes during page" ++ " rendering.",+ {+ since: "3.5.0.beta9-dev",+ id: "discourse.static-viewport-initialization",+ url: "https://meta.discourse.org/t/367810",+ }+ );+ }++ if (Mobile.mobileForced) {+ return true;+ }++ return withSilencedDeprecations(+ "discourse.static-viewport-initialization",+ () => !this.capabilities.viewport.sm+ );+ }++ @dependentKeyCompat+ get isMobileDevice(): boolean {+ deprecated(+ "Site.isMobileDevice is deprecated. Use `site.mobileView` and `site.desktopView` instead for " ++ "viewport-based values or `capabilities.isMobileDevice` for user-agent based detection.",+ {+ id: "discourse.site.is-mobile-device",+ since: "3.5.0.beta9-dev",+ url: "https://meta.discourse.org/t/367810",+ }+ );++ return this.mobileView;+ }++ @dependentKeyCompat+ get categoriesById() {+ return new Map(this.categories.map((c) => [c.id, c]));+ }++ @computed("[email protected]_category_id")+ get categoriesByParentId() {+ const map = new Map<Category["parent_category_id"], Category[]>();+ for (const category of this.categories) {+ const siblings = map.get(category.parent_category_id) || [];+ siblings.push(category);+ map.set(category.parent_category_id, siblings);+ }+ return map;+ }++ @computed("notification_types")+ get notificationLookup() {+ const result: string[] = [];+ Object.keys(this.notification_types!).forEach(+ (k) => (result[this.notification_types![k]] = k)+ );+ return result;+ }++ @computed("post_action_types.[]")+ get flagTypes(): PostActionType[] {+ const postActionTypes = this.post_action_types;+ if (!postActionTypes) {+ return [];+ }+ // TODO(typescript-pending): PostActionType doesn't type its server fields; remove when it does.+ return trackedArray(+ postActionTypes.filter(+ (type) => (type as PostActionType & { is_flag?: boolean }).is_flag+ )+ );+ }++ // Sort subcategories under parents+ @cached+ get sortedCategories(): Category[] {+ return Category.sortCategories(this.categoriesByCount);+ }++ // Returns it in the correct order, by setting+ @computed("categories.[]")+ get categoriesList(): Category[] {+ return this.siteSettings.fixed_category_positions+ ? this.categories+ : this.sortedCategories;+ }++ @computed("categories.[]", "[email protected]_level")+ get trackedCategoriesList(): Category[] {+ const trackedCategories: Category[] = [];++ for (const category of this.categories) {+ if (category.isTracked) {+ if (+ this.siteSettings.allow_uncategorized_topics ||+ !category.isUncategorizedCategory+ ) {+ trackedCategories.push(category);+ }+ }+ }++ return trackedCategories;+ }++ get topTags(): Tag[] {+ return this.#transformTags(this.top_tags);+ }++ get categoryTopTags(): Tag[] {+ return this.#transformTags(this.category_top_tags);+ }++ groupName(groupId: number | string): string | null {+ const group = this.groupsById[groupId as number];+ return group ? group.name : null;+ }++ groupFullName(groupId: number | string): string | null | undefined {+ const group = this.groupsById[groupId as number];+ return group ? group.full_name : null;+ }++ collectUserFields(fields?: SiteUserFieldValues | null) {+ fields = fields || {};++ const siteFields = this.user_fields;++ if (!isEmpty(siteFields)) {+ return siteFields.map((f) => {+ let value:+ | SiteUserFieldValues[string]+ | TrustedHTML+ | null+ | undefined = fields ? fields[f.id.toString()] : null;+ value = value || trustHTML("—");+ return { name: f.name, value };+ });+ }+ return [];+ }++ postActionTypeById(id: number | string): PostActionType | undefined {+ return this.get("postActionByIdLookup.action" + id) as+ | PostActionType+ | undefined;+ }++ topicFlagTypeById(id: number | string): PostActionType | undefined {+ return this.get("topicFlagByIdLookup.action" + id) as+ | PostActionType+ | undefined;+ }++ removeCategory(id: number | string): void {+ const categories = this.categories;+ const existingCategory = categories.find((c) => c.id === id);+ if (existingCategory) {+ removeValueFromArray(categories, existingCategory);+ }+ }++ updateCategory(newCategory: CategoryFields): Category;+ updateCategory(+ newCategory: CategoryFields & { [key: string]: unknown }+ ): Category;++ updateCategory(+ newCategory: (CategoryFields & { [key: string]: unknown }) | Category+ ): Category {+ if (newCategory instanceof Category) {+ throw new Error(+ "updateCategory should be passed a pojo, not a category model instance"+ );+ }++ const categories = this.categories;+ const categoryId = get(newCategory, "id");+ const existingCategory = categories.find((c) => c.id === categoryId);++ if (newCategory.permission === null) {+ delete newCategory.permission;+ }++ if (newCategory.has_children == null) {+ delete newCategory.has_children;+ }++ if (existingCategory) {+ existingCategory.setProperties(newCategory);+ existingCategory.setupCategoryTypes();+ return existingCategory;+ } else {+ newCategory = this.store.createRecord("category", newCategory);+ categories.push(newCategory);+ return newCategory;+ }+ }++ #transformTags(tags: SiteTopTag[] | undefined): Tag[] {+ if (!tags) {+ return [];+ }+ // TODO(typescript-pending): the store registry has no tag entry; remove when it does.+ return tags.map(+ (tag) =>+ this.store.createRecord(+ "tag",+ tag as unknown as RestModelAttrs<RestModel>+ ) as unknown as Tag+ );+ }+}++/** The deprecated global namespace, present only on pages that still define it. */+declare const Discourse: object | undefined;++if (typeof Discourse !== "undefined") {+ let warned = false;++ Object.defineProperty(Discourse, "Site", {+ get() {+ if (!warned) {+ deprecated("Import the Site class instead of using Discourse.Site", {+ since: "2.4.0",+ id: "discourse.global.site",+ });+ warned = true;+ }+ return Site;+ },+ });+}diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.tsindex 6e4234bd61c..faed3bdf978 100644--- a/frontend/discourse/app/services/store.ts+++ b/frontend/discourse/app/services/store.ts@@ -17,11 +17,13 @@ import RestModel, {type RestPayload,} from "discourse/models/rest";import ResultSet from "discourse/models/result-set";+import type Site from "discourse/models/site";import type UserDraft from "discourse/models/user-draft";/** Model instances by store type name. Plugins add theirs through module augmentation. */export interface ModelRegistry {category: Category;+ site: Site;"user-draft": UserDraft;}diff --git a/frontend/discourse/type-tests/models/site-test.ts b/frontend/discourse/type-tests/models/site-test.tsnew file mode 100644index 00000000000..9c480371bf5--- /dev/null+++ b/frontend/discourse/type-tests/models/site-test.ts@@ -0,0 +1,421 @@+import type EmberObject from "@ember/object";+import type { TrustedHTML } from "@ember/template";+import { expectTypeOf } from "expect-type";+import type Archetype from "discourse/models/archetype";+import type Category from "discourse/models/category";+import type PostActionType from "discourse/models/post-action-type";+import type RestModel from "discourse/models/rest";+import Site, { type SiteFields } from "discourse/models/site";+import type Tag from "discourse/models/tag";+import type TrustLevel from "discourse/models/trust-level";+import type {+ default as StoreService,+ ModelFor,+} from "discourse/services/store";++/** Independent of Site's exports: SiteSerializer#groups always emits these keys. */+interface ExpectedGroup {+ id: number;+ name: string;+ full_name: string;+ display_name: string;+ flair_url: string | null;+ flair_bg_color: string | null;+ flair_color: string | null;+ automatic: boolean;+}++/** AUTO_GROUPS supplies only id, name and automatic before server groups overwrite it. */+type ExpectedGroupLookupEntry = Pick<+ ExpectedGroup,+ "id" | "name" | "automatic"+> &+ Partial<Omit<ExpectedGroup, "id" | "name" | "automatic">>;++/** UserFieldSerializer, UserField's enums and the nullable position column. */+interface ExpectedUserField {+ id: number;+ name: string;+ description: string;+ field_type:+ | "text"+ | "confirm"+ | "dropdown"+ | "multiselect"+ | "textarea"+ | "date";+ editable: boolean;+ required: boolean;+ requirement: "optional" | "for_all_users" | "on_signup";+ show_on_profile: boolean;+ show_on_user_card: boolean;+ show_on_signup: boolean;+ searchable: boolean;+ position: number | null;+ options?: string[];+}++/** AuthProviderSerializer emits unset AuthProvider accessors as null, not missing keys. */+interface ExpectedAuthProvider {+ can_connect: boolean;+ can_revoke: boolean;+ custom_url: string | null;+ frame_height: number | null;+ frame_width: number | null;+ icon_override: string | null;+ name: string;+ pretty_name_override: string | null;+ provider_url: string | null;+ title_override: string | null;+}++interface ExpectedTopTag {+ id: number;+ name: string;+ slug: string;+}++interface ExpectedSidebarTag extends ExpectedTopTag {+ description: string | null;+ pm_only: boolean;+}++/** SidebarSectionSerializer does not request link localizations or can_localize. */+interface ExpectedSidebarSection {+ id: number;+ title: string;+ links: {+ id: number;+ name: string;+ value: string;+ icon: string;+ external: boolean;+ segment: "primary" | "secondary";+ locale: string | null;+ }[];+ slug: string;+ public: boolean;+ section_type: "community" | null;+ locale: string | null;+}++interface ExpectedUserTheme {+ theme_id: number;+ name: string;+ default: boolean;+ color_scheme_id: number | null;+ dark_color_scheme_id: number | null;+ only_theme_color_schemes: boolean;+}++/** default_hex can miss a custom color in the base palette; is_dark? can return nil. */+interface ExpectedColor {+ name: string;+ hex: string;+ default_hex: string | null;+ is_advanced: boolean;+}++interface ExpectedSelectableColorScheme {+ id: number;+ name: string;+ is_dark: boolean | null;+ theme_id: number | null;+ colors: ExpectedColor[];+}++interface ExpectedColorScheme extends ExpectedSelectableColorScheme {+ is_base: boolean | null;+ base_scheme_id: number | null;+ theme_name: string | null;+ user_selectable: boolean;+ is_builtin_default: boolean | null;+}++/** WordWatcher#words_for_action compacts replacement and only includes truthy html. */+interface ExpectedWatchedWord {+ word: string;+ replacement?: string;+ case_sensitive: boolean;+ html?: true;+}++interface ExpectedAclEntry {+ type: "group" | "user";+ id: number;+ permission: string;+}++/** Categories::Types::Base#metadata and #resolved_configuration_schema. */+interface ExpectedCategoryType {+ id: string;+ name: string;+ title: string;+ description: string;+ icon: string | null;+ available: boolean;+ visible: boolean;+ configuration_schema: Record<string, Record<string, unknown>[]>;+ [key: string]: unknown;+}++/** The banner initializer also creates an empty EmberObject when there is no banner. */+type ExpectedBanner = EmberObject & {+ html?: string;+ key?: number;+ url?: string;+};++/**+ * Instance data, after Site.create's model wrapping and trust_levels deletion.+ * Site.json_for's login-required anonymous branch makes most server fields optional.+ * categories and groups instead have class-level empty-array defaults.+ */+interface ExpectedSiteFields {+ default_archetype?: string;+ notification_types?: Record<string, number>;+ post_types?: Record<string, number>;+ user_tips?: Record<string, number>;+ trustLevels?: TrustLevel[];+ groups: ExpectedGroup[];+ filters: string[];+ anonymous_list_filters: string[];+ homepage_choices?: string[];+ homepage_options?: {+ id: string;+ path: string | null;+ server_side: boolean;+ }[];+ periods: string[];+ top_menu_items?: string[];+ anonymous_top_menu_items?: string[];+ uncategorized_category_id?: number;+ user_field_max_length?: number;+ post_action_types?: PostActionType[];+ topic_flag_types?: PostActionType[];+ can_create_tag?: boolean;+ can_search?: boolean;+ can_tag_topics?: boolean;+ can_tag_pms?: boolean;+ tags_filter_regexp?: string;+ top_tags?: ExpectedTopTag[];+ navigation_menu_site_top_tags?: ExpectedSidebarTag[];+ can_associate_groups?: boolean;+ wizard_required?: true;+ topic_featured_link_allowed_category_ids?: number[];+ user_themes?: ExpectedUserTheme[];+ user_color_schemes?: ExpectedSelectableColorScheme[];+ default_light_color_scheme?: ExpectedColorScheme | null;+ default_dark_color_scheme?: ExpectedColorScheme | null;+ censored_regexp?: Record<string, { case_sensitive: boolean }>[];+ shared_drafts_category_id?: number;+ custom_emoji_translation?: Record<string, string>;+ watched_words_replace?: Record<string, ExpectedWatchedWord> | null;+ watched_words_link?: Record<string, ExpectedWatchedWord> | null;+ categories: Category[];+ markdown_additional_options?: Record<string, unknown>;+ hashtag_configurations?: Record<string, string[]>;+ hashtag_icons?: Record<string, string>;+ anonymous_default_navigation_menu_tags?: ExpectedSidebarTag[];+ anonymous_sidebar_sections?: ExpectedSidebarSection[];+ whispers_allowed_groups_names?: string[];+ denied_emojis?: string[];+ tos_url?: string | null;+ privacy_policy_url?: string | null;+ system_user_avatar_template?: string;+ lazy_load_categories?: true;+ valid_flag_applies_to_types?: string[];+ full_name_required_for_signup: boolean;+ full_name_visible_in_signup: boolean;+ admin_config_login_routes?: string[];+ email_configured?: boolean;+ upcoming_changes_with_css: string[];+ permanent_upcoming_change_names?: string[];+ access_control?: {+ mandatory_acl: Record<string, ExpectedAclEntry[]>;+ banned_acl: Record<string, ExpectedAclEntry[]>;+ };+ category_types?: ExpectedCategoryType[];+ archetypes?: Archetype[];+ user_fields: (EmberObject & ExpectedUserField)[];+ auth_providers: ExpectedAuthProvider[];+ postActionByIdLookup?: EmberObject;+ topicFlagByIdLookup?: EmberObject;+ loadedCategoryIds?: Set<number>;+ narrowDesktopView?: boolean;+ banner?: ExpectedBanner | null;+ category_top_tags?: ExpectedTopTag[];+ is_readonly?: boolean;+ isStaffWritesOnly?: boolean;+}++declare module "discourse/models/site" {+ interface SiteFields {+ type_test_plugin_flag?: boolean;+ }+}++expectTypeOf<+ Omit<SiteFields, "type_test_plugin_flag">+>().toEqualTypeOf<ExpectedSiteFields>();++declare const site: Site;+declare const store: StoreService;+declare const fields: ExpectedSiteFields;++expectTypeOf<+ Pick<Site, keyof ExpectedSiteFields>+>().toEqualTypeOf<ExpectedSiteFields>();+expectTypeOf(site.type_test_plugin_flag).toEqualTypeOf<boolean | undefined>();++/** Audit only what Site adds; Ember's own _super and metaForProperty are excluded. */+type AnyKeys<T> = {+ [K in keyof T]-?: 0 extends 1 & T[K] ? K : never;+}[keyof T];+type AnyReturnKeys<T> = {+ [K in keyof T]-?: T[K] extends (...args: never) => infer R+ ? 0 extends 1 & R+ ? K+ : never+ : never;+}[keyof T];+type OwnAnyKeys<T, Base> = Exclude<+ AnyKeys<T> | AnyReturnKeys<T>,+ AnyKeys<Base> | AnyReturnKeys<Base>+>;+expectTypeOf<OwnAnyKeys<Site, EmberObject>>().toEqualTypeOf<never>();+// The inherited create is generic in this, and inferring its return through a+// conditional type gives any even though calls resolve to Site; assert calls below.+expectTypeOf<+ Exclude<OwnAnyKeys<typeof Site, typeof EmberObject>, "create">+>().toEqualTypeOf<never>();++expectTypeOf(site.topicCountDesc).toEqualTypeOf<string[]>();+expectTypeOf(site.isReadOnly).toEqualTypeOf<boolean | undefined>();+expectTypeOf(site.desktopView).toEqualTypeOf<boolean>();+expectTypeOf(site.mobileView).toEqualTypeOf<boolean>();+expectTypeOf(site.isMobileDevice).toEqualTypeOf<boolean>();+expectTypeOf(site.categoriesByCount).toEqualTypeOf<Category[]>();+expectTypeOf(site.categoriesById).toEqualTypeOf<+ Map<number | undefined, Category>+>();+expectTypeOf(site.categoriesByParentId).toEqualTypeOf<+ Map<number | null | undefined, Category[]>+>();+expectTypeOf(site.groupsById).branded.toEqualTypeOf<+ Record<number, ExpectedGroupLookupEntry>+>();+expectTypeOf(site.notificationLookup).toEqualTypeOf<string[]>();+expectTypeOf(site.flagTypes).toEqualTypeOf<PostActionType[]>();+expectTypeOf(site.sortedCategories).toEqualTypeOf<Category[]>();+expectTypeOf(site.categoriesList).toEqualTypeOf<Category[]>();+expectTypeOf(site.trackedCategoriesList).toEqualTypeOf<Category[]>();+expectTypeOf(site.topTags).toEqualTypeOf<Tag[]>();+expectTypeOf(site.categoryTopTags).toEqualTypeOf<Tag[]>();+expectTypeOf(site.groupName(1)).toEqualTypeOf<string | null>();+expectTypeOf(site.groupName("1")).toEqualTypeOf<string | null>();+expectTypeOf(site.groupFullName(1)).toEqualTypeOf<string | null | undefined>();+expectTypeOf(site.postActionTypeById(1)).toEqualTypeOf<+ PostActionType | undefined+>();+expectTypeOf(site.postActionTypeById("1")).toEqualTypeOf<+ PostActionType | undefined+>();+expectTypeOf(site.topicFlagTypeById(1)).toEqualTypeOf<+ PostActionType | undefined+>();+expectTypeOf(site.topicFlagTypeById("1")).toEqualTypeOf<+ PostActionType | undefined+>();+expectTypeOf(+ site.updateCategory({ id: 1, permission: null })+).toEqualTypeOf<Category>();+expectTypeOf(+ site.updateCategory({ id: 1, has_children: null, plugin_payload: true })+).toEqualTypeOf<Category>();+expectTypeOf(site.removeCategory(1)).toEqualTypeOf<void>();+expectTypeOf(site.removeCategory("1")).toEqualTypeOf<void>();++// User#user_fields includes boolean confirmations and multiselect arrays.+// collectUserFields replaces false/null/missing values with a TrustedHTML dash.+expectTypeOf(site.collectUserFields).returns.toEqualTypeOf<+ { name: string; value: string | string[] | true | TrustedHTML }[]+>();+site.collectUserFields({+ "1": "Text",+ "2": ["a", "b"],+ "3": true,+ "4": false,+ "5": null,+});+site.collectUserFields(null);+site.collectUserFields(undefined);++site.isReadOnly = false;+// @ts-expect-error the read-only setter keeps the boolean backing field's type+site.isReadOnly = "false";+// @ts-expect-error category updates use numeric server ids+site.updateCategory({ id: "1" });+// @ts-expect-error category removal accepts an id, not a category payload+site.removeCategory({ id: 1 });++expectTypeOf(Site.current()).toEqualTypeOf<Site>();+expectTypeOf(Site.createCurrent()).toEqualTypeOf<Site>();+expectTypeOf(Site.resetCurrent(site)).toEqualTypeOf<Site>();+expectTypeOf(Site.resetCurrent(null)).toEqualTypeOf<null>();+expectTypeOf(Site.resetCurrent(undefined)).toEqualTypeOf<undefined>();+expectTypeOf(Site.currentProp("categories")).toEqualTypeOf<Category[]>();+expectTypeOf(Site.currentProp("categories", [])).toEqualTypeOf<Category[]>();+expectTypeOf(Site.currentProp("top_tags")).toEqualTypeOf<+ ExpectedTopTag[] | undefined+>();+expectTypeOf(Site.currentProp("isReadOnly", true)).toEqualTypeOf<+ boolean | undefined+>();+expectTypeOf(Site.currentProp("categoriesById")).toEqualTypeOf<+ Map<number | undefined, Category>+>();+expectTypeOf(Site.currentProp("type_test_plugin_flag")).toEqualTypeOf<+ boolean | undefined+>();+expectTypeOf(Site.currentProp("type_test_plugin_flag", true)).toEqualTypeOf<+ boolean | undefined+>();+declare const dynamicKey: string;+expectTypeOf(Site.currentProp(dynamicKey)).toEqualTypeOf<unknown>();+expectTypeOf(+ Site.currentProp(dynamicKey, { enabled: true })+).toEqualTypeOf<unknown>();+expectTypeOf(Site.currentProp("a.b")).toEqualTypeOf<unknown>();+expectTypeOf(Site.currentProp("a.b", 1)).toEqualTypeOf<unknown>();+// @ts-expect-error the arbitrary-string overload must not loosen known keys+Site.currentProp("categories", "invalid");+// @ts-expect-error augmentation participates in the known-key setter+Site.currentProp("type_test_plugin_flag", "true");++expectTypeOf(site).toExtend<RestModel>();+expectTypeOf(Site.create()).toEqualTypeOf<Site>();+expectTypeOf(Site.create({ ...fields })).toEqualTypeOf<Site>();+expectTypeOf(+ Site.create({ type_test_plugin_flag: true, undeclared_server_field: 1 })+).toEqualTypeOf<Site>();+// @ts-expect-error transformed category data is an array of Category instances+Site.create({ categories: [1] });+// @ts-expect-error flags are omitted when false, rather than serialized as false+Site.create({ wizard_required: false });+// @ts-expect-error lazy_load_categories is also only sent as true+Site.create({ lazy_load_categories: false });+// @ts-expect-error tags are objects with numeric ids, not tag names+Site.create({ top_tags: ["tag"] });+// @ts-expect-error watched words are regexp-keyed objects, not serialized regexp arrays+Site.create({ watched_words_replace: [] });+// @ts-expect-error plugin augmentation keeps its declared value type in create attrs+Site.create({ type_test_plugin_flag: "true" });++expectTypeOf<ModelFor<"site">>().toEqualTypeOf<Site>();+expectTypeOf(store.createRecord("site")).toEqualTypeOf<Site>();+expectTypeOf(store.createRecord("site", { ...fields })).toEqualTypeOf<Site>();+// @ts-expect-error registry attrs retain the model's declared field types+store.createRecord("site", { filters: "latest" });+// @ts-expect-error registry attrs also retain plugin augmentations+store.createRecord("site", { type_test_plugin_flag: "true" });