From 5ee8538edf1395cbe3ed3a04597292aeb39bddc6 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:02:24 -0500 Subject: [PATCH 01/26] Support standard decorators in controller, target, targets and attr The same exports now accept TypeScript's legacy experimentalDecorators and standard (TC39 2023-11) decorator calls. Legacy calls take the existing code path. - @controller registers from a class initializer, after static fields. - @attr records names in decorator metadata; @controller registers them, walking undecorated base classes. Symbol.metadata is defined if missing. - @target/@targets decorate public instance accessors and throw on assignment. - Context types are structural so the .d.ts loads on TypeScript < 5.0. - Tests: test/standard runs in the browser compiled with standard decorators; test/types fixtures type-check in both modes via npm run lint. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .eslintrc.json | 2 +- docs/_guide/attrs.md | 2 +- docs/_guide/decorators.md | 23 +++- docs/_guide/targets.md | 2 +- docs/_guide/you-will-need.md | 4 +- package-lock.json | 194 +++++++++++++++++++++----------- package.json | 10 +- src/attr.ts | 54 ++++++++- src/bind.ts | 2 +- src/controller.ts | 47 ++++++-- src/decorator-context.ts | 64 +++++++++++ src/target.ts | 47 +++++++- test/standard/attr.ts | 209 +++++++++++++++++++++++++++++++++++ test/standard/controller.ts | 64 +++++++++++ test/standard/metadata.ts | 29 +++++ test/standard/target.ts | 110 ++++++++++++++++++ test/standard/tsconfig.json | 9 ++ test/types/decorators.ts | 37 +++++++ tsconfig.json | 4 +- web-test-runner.config.js | 25 ++++- 20 files changed, 848 insertions(+), 90 deletions(-) create mode 100644 src/decorator-context.ts create mode 100644 test/standard/attr.ts create mode 100644 test/standard/controller.ts create mode 100644 test/standard/metadata.ts create mode 100644 test/standard/target.ts create mode 100644 test/standard/tsconfig.json create mode 100644 test/types/decorators.ts diff --git a/.eslintrc.json b/.eslintrc.json index d5c785f1..d0b5d929 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -11,7 +11,7 @@ }, "overrides": [ { - "files": "test/*", + "files": "test/**", "rules": { "@typescript-eslint/no-empty-function": "off" }, diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index 2374054c..937b133d 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -16,7 +16,7 @@ Catalyst includes the `@attr` decorator, which provides nice syntax sugar to sim - The attribute name is automatically [observed, meaning `attributeChangedCallback` will fire when it changes](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks). - Assigning a value in the class description will make that value the _default_ value, so when the element is connected that value is set (unless the element has the attribute defined already). -To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute. +To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute. With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), `@attr` needs decorator metadata support, which TypeScript has from version 5.2. ### Example diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index e27f2f3d..b023e6ca 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -5,7 +5,7 @@ title: Decorators subtitle: Using TypeScript for ergonomics --- -Decorators are used heavily in Catalyst, because they provide really clean ergonomics and makes using the library a lot easier. Decorators are a special, (currently) non standard, feature of TypeScript. You'll need to turn the `experimentalDecorators` option on inside of your TypeScript project to use them (if you're using `@babel/plugin-proposal-decorators` plugin, you need to use [`legacy` option](https://babeljs.io/docs/en/babel-plugin-proposal-decorators#legacy)). +Decorators are used heavily in Catalyst, because they provide really clean ergonomics and makes using the library a lot easier. Catalyst's decorators work with both TypeScript's legacy `experimentalDecorators` option (or the `@babel/plugin-proposal-decorators` [`legacy` option](https://babeljs.io/docs/en/babel-plugin-proposal-decorators#legacy)) and [standard decorators](#standard-decorators). The same imports work in both modes. You can read more about [decorators in the TypeScript handbook](https://www.typescriptlang.org/docs/handbook/decorators.html), but here's quick guide: @@ -83,6 +83,25 @@ class HelloWorldElement extends HTMLElement { } ``` +### Standard decorators + +TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) decorators when `experimentalDecorators` is off. `@controller`, `@attr`, `@target` and `@targets` support them, with two differences from legacy decorators: + +- `@target` and `@targets` must decorate an `accessor`. Standard decorators can't decorate `declare` fields, and a plain field would hide the getter the decorator defines: + + ```typescript + @controller + class HelloWorldElement extends HTMLElement { + @target accessor output!: HTMLElement + @targets accessor items!: HTMLElement[] + } + ``` + + Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. + +Catalyst's member decorators only support public, non-static members. `@controller` registers the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. + ### Supporting `strictPropertyInitialization` TypeScript comes with various "strict" mode settings, one of which is `strictPropertyInitialization` which lets TypeScript catch potential class properties which might not be assigned during construction of a class. This option conflicts with Catalyst's `@target`/`@targets` decorators, which safely do the assignment but TypeScript's simple heuristics cannot detect this. There are two ways to work around this: @@ -96,7 +115,7 @@ TypeScript comes with various "strict" mode settings, one of which is `strictPro } ``` - Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing. + Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing. With [standard decorators](#standard-decorators), use the definite initialization operator on an accessor instead: `@target accessor something!: HTMLElement`. 2. You can also disable the compiler option (other strict mode rules can still apply) in your `tsconfig.json` like so: diff --git a/docs/_guide/targets.md b/docs/_guide/targets.md index 877522b2..4983d39b 100644 --- a/docs/_guide/targets.md +++ b/docs/_guide/targets.md @@ -139,7 +139,7 @@ Important to note here is that nodes from the `shadowRoot` get returned _first_. ### What about without Decorators? -If you're using decorators, then the `@target` and `@targets` decorators will turn the decorated properties into getters. +If you're using decorators, then the `@target` and `@targets` decorators will turn the decorated properties into getters. With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), decorate an accessor instead of a field: `@target accessor output!: HTMLElement`. If you're not using decorators, then you'll need to make a `getter`, and call `findTarget(this, key)` or `findTargets(this, key)` in the getter, for example: diff --git a/docs/_guide/you-will-need.md b/docs/_guide/you-will-need.md index a56495ee..3fe986cc 100644 --- a/docs/_guide/you-will-need.md +++ b/docs/_guide/you-will-need.md @@ -8,7 +8,7 @@ Catalyst is available as an npm module `@github/catalyst`. To install into your ### TypeScript -Catalyst has no strict dependencies, but it relies on TypeScript for decorator support, so you should also configure your project to use TypeScript. [Read the TypeScript docs on how to set up TypeScript on a new project](https://www.typescriptlang.org/docs/home.html). +Catalyst has no strict dependencies, but it relies on TypeScript for decorator support, so you should also configure your project to use TypeScript. [Read the TypeScript docs on how to set up TypeScript on a new project](https://www.typescriptlang.org/docs/home.html). Catalyst's decorators work with both the `experimentalDecorators` option and standard decorators; see [Decorators]({{ site.baseurl }}/guide/decorators). ### Polyfills @@ -20,6 +20,8 @@ Catalyst uses modern browser standards, and so requires evergreen browsers or ma Please note this list may increase over time. Catalyst will never ship with polyfills that add missing browser functionality, but will continue to use the latest Web Standards, and so may require more polyfills as new releases come out. +The one exception is `Symbol.metadata`, which [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators) use to store metadata. TypeScript only attaches decorator metadata when `Symbol.metadata` exists, so if it is missing, Catalyst defines it as `Symbol.for('Symbol.metadata')` when it loads. That is the key SWC's and Babel's decorator helpers fall back to. Lit also defines `Symbol.metadata` when it is missing. + ### Build considerations When using build tools, some JavaScript minifiers modify the class name that Catalyst relies on. You know you have an issue if you encounter the error `"c" is not a valid custom element name`. diff --git a/package-lock.json b/package-lock.json index 9ae3418a..8f3dc91b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,8 +14,8 @@ "@open-wc/testing": "^4.0.0", "@size-limit/preset-small-lib": "^8.0.1", "@types/mocha": "^10.0.10", - "@typescript-eslint/eslint-plugin": "^5.36.1", - "@typescript-eslint/parser": "^5.36.1", + "@typescript-eslint/eslint-plugin": "^5.62.0", + "@typescript-eslint/parser": "^5.62.0", "@web/dev-server-esbuild": "^0.3.2", "@web/test-runner": "^0.20.0", "eslint": "^8.23.0", @@ -23,7 +23,7 @@ "sinon": "^14.0.0", "size-limit": "^8.0.1", "tslib": "^2.4.0", - "typescript": "^4.8.2" + "typescript": "^5.9.3" } }, "node_modules/@babel/code-frame": { @@ -92,6 +92,35 @@ "node": ">=12" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha1-iRG9crLDZApUNgngQAuMTS5+fLY=", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha1-vM32Fbz3tujbgw7AuNIcmiXeWXs=", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/@eslint/eslintrc": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.1.tgz", @@ -1728,10 +1757,11 @@ } }, "node_modules/@types/json-schema": { - "version": "7.0.11", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.11.tgz", - "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", - "dev": true + "version": "7.0.15", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha1-WWoXRyM2lNUPatinhp/Lb1bPWEE=", + "dev": true, + "license": "MIT" }, "node_modules/@types/json5": { "version": "0.0.29", @@ -1814,6 +1844,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/serve-static": { "version": "1.13.10", "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.10.tgz", @@ -1877,18 +1914,20 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.36.1.tgz", - "integrity": "sha512-iC40UK8q1tMepSDwiLbTbMXKDxzNy+4TfPWgIL661Ym0sD42vRcQU93IsZIrmi+x292DBr60UI/gSwfdVYexCA==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", + "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/type-utils": "5.36.1", - "@typescript-eslint/utils": "5.36.1", + "@eslint-community/regexpp": "^4.4.0", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/type-utils": "5.62.0", + "@typescript-eslint/utils": "5.62.0", "debug": "^4.3.4", - "functional-red-black-tree": "^1.0.1", + "graphemer": "^1.4.0", "ignore": "^5.2.0", - "regexpp": "^3.2.0", + "natural-compare-lite": "^1.4.0", "semver": "^7.3.7", "tsutils": "^3.21.0" }, @@ -1910,14 +1949,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.36.1.tgz", - "integrity": "sha512-/IsgNGOkBi7CuDfUbwt1eOqUXF9WGVBW9dwEe1pi+L32XrTsZIgmDFIi2RxjzsvB/8i+MIf5JIoTEH8LOZ368A==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/typescript-estree": "5.36.1", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", "debug": "^4.3.4" }, "engines": { @@ -1937,13 +1977,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.36.1.tgz", - "integrity": "sha512-pGC2SH3/tXdu9IH3ItoqciD3f3RRGCh7hb9zPdN2Drsr341zgd6VbhP5OHQO/reUqihNltfPpMpTNihFMarP2w==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/visitor-keys": "5.36.1" + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" }, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -1954,13 +1995,14 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.36.1.tgz", - "integrity": "sha512-xfZhfmoQT6m3lmlqDvDzv9TiCYdw22cdj06xY0obSznBsT///GK5IEZQdGliXpAOaRL34o8phEvXzEo/VJx13Q==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", + "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/typescript-estree": "5.36.1", - "@typescript-eslint/utils": "5.36.1", + "@typescript-eslint/typescript-estree": "5.62.0", + "@typescript-eslint/utils": "5.62.0", "debug": "^4.3.4", "tsutils": "^3.21.0" }, @@ -1981,10 +2023,11 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.36.1.tgz", - "integrity": "sha512-jd93ShpsIk1KgBTx9E+hCSEuLCUFwi9V/urhjOWnOaksGZFbTOxAT47OH2d4NLJnLhkVD+wDbB48BuaycZPLBg==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", "dev": true, + "license": "MIT", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -1994,13 +2037,14 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.36.1.tgz", - "integrity": "sha512-ih7V52zvHdiX6WcPjsOdmADhYMDN15SylWRZrT2OMy80wzKbc79n8wFW0xpWpU0x3VpBz/oDgTm2xwDAnFTl+g==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/visitor-keys": "5.36.1", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -2021,17 +2065,20 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.36.1.tgz", - "integrity": "sha512-lNj4FtTiXm5c+u0pUehozaUWhh7UYKnwryku0nxJlYUEWetyG92uw2pr+2Iy4M/u0ONMKzfrx7AsGBTCzORmIg==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/utils/-/utils-5.62.0.tgz", + "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", "dev": true, + "license": "MIT", "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.36.1", - "@typescript-eslint/types": "5.36.1", - "@typescript-eslint/typescript-estree": "5.36.1", + "@types/semver": "^7.3.12", + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" + "semver": "^7.3.7" }, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -2045,12 +2092,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.36.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.36.1.tgz", - "integrity": "sha512-ojB9aRyRFzVMN3b5joSYni6FAS10BBSCAfKJhjJAV08t/a95aM6tAhz+O1jF+EtgxktuSO3wJysp2R+Def/IWQ==", + "version": "5.62.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", "dev": true, + "license": "MIT", "dependencies": { - "@typescript-eslint/types": "5.36.1", + "@typescript-eslint/types": "5.62.0", "eslint-visitor-keys": "^3.3.0" }, "engines": { @@ -4968,9 +5016,10 @@ }, "node_modules/eslint-scope": { "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eslint-scope/-/eslint-scope-5.1.1.tgz", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" @@ -5007,12 +5056,16 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "version": "3.4.3", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha1-DNcv6FUOPC6uFWqWpN3c0cisWAA=", "dev": true, + "license": "Apache-2.0", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/eslint/node_modules/ansi-styles": { @@ -5304,9 +5357,10 @@ }, "node_modules/estraverse": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -5965,6 +6019,13 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "dev": true }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha1-+y8dVeDjoYSa7/yQxPoN1ToOZsY=", + "dev": true, + "license": "MIT" + }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -7866,6 +7927,13 @@ "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, + "node_modules/natural-compare-lite": { + "version": "1.4.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/natural-compare-lite/-/natural-compare-lite-1.4.1.tgz", + "integrity": "sha512-8Mz06azhPqiDlxhUaUTjBhNAbib/1MoPr89kgmuV6Ir8ICT2/Q/XSYg6VfL3fq2x8MpSQX8sqyI/NeZ5GsGyXA==", + "dev": true, + "license": "MIT" + }, "node_modules/negotiator": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", @@ -8399,10 +8467,11 @@ } }, "node_modules/prettier": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.6.2.tgz", - "integrity": "sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew==", + "version": "2.8.8", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true, + "license": "MIT", "bin": { "prettier": "bin-prettier.js" }, @@ -9827,16 +9896,17 @@ } }, "node_modules/typescript": { - "version": "4.8.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.2.tgz", - "integrity": "sha512-C0I1UsrrDHo2fYI5oaCGbSejwX4ch+9Y5jTQELvovfmFkK3HHSZJB8MSJcWLmCUBzQBchCrZ9rMRV6GuNrvGtw==", + "version": "5.9.3", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" } }, "node_modules/typical": { diff --git a/package.json b/package.json index a34ef14f..08c3bed1 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "build:docs": "cd docs && JEKYLL_ENV=production bundle exec jekyll build", "clean": "tsc --build --clean tsconfig.build.json", "lint": "eslint . --ignore-path .gitignore", - "postlint": "tsc", + "postlint": "tsc && tsc -p test/standard", "prepack": "npm run build", "presize": "npm run build", "size": "size-limit", @@ -40,8 +40,8 @@ "@open-wc/testing": "^4.0.0", "@size-limit/preset-small-lib": "^8.0.1", "@types/mocha": "^10.0.10", - "@typescript-eslint/eslint-plugin": "^5.36.1", - "@typescript-eslint/parser": "^5.36.1", + "@typescript-eslint/eslint-plugin": "^5.62.0", + "@typescript-eslint/parser": "^5.62.0", "@web/dev-server-esbuild": "^0.3.2", "@web/test-runner": "^0.20.0", "eslint": "^8.23.0", @@ -49,13 +49,13 @@ "sinon": "^14.0.0", "size-limit": "^8.0.1", "tslib": "^2.4.0", - "typescript": "^4.8.2" + "typescript": "^5.9.3" }, "size-limit": [ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "2.5kb" + "limit": "3kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index 2d7472fc..743d9597 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -1,19 +1,69 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' import {meta} from './core.js' +import type {MemberContext} from './decorator-context.js' +import {hasOwn, isDecoratorContext, memberName, ownMetadata} from './decorator-context.js' const attrKey = 'attr' type attrValue = string | number | boolean +const standardAttrs = Symbol.for('catalyst:attr') + /** * Attr is a decorator which tags a property as one to be initialized via * `initializeAttrs`. * * The signature is typed such that the property must be one of a String, * Number or Boolean. This matches the behavior of `initializeAttrs`. + * + * It supports both TypeScript's `experimentalDecorators` and standard + * decorators. With standard decorators it can decorate a field, accessor, + * getter or setter, and records the name in the class's decorator metadata + * for `@controller` to register. + */ +export function attr( + value: unknown, + context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> +): void +export function attr(proto: Record, key: K): void +export function attr(proto: unknown, keyOrContext: unknown): void { + if (!isDecoratorContext(keyOrContext)) { + meta(proto as Record, attrKey).add(keyOrContext as string) + return + } + const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) + const metadata = keyOrContext.metadata as Record | undefined + if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') + // Metadata inherits from the parent class's metadata, so only append to this class's own list. + if (hasOwn(metadata, standardAttrs)) metadata[standardAttrs]!.push(name) + else metadata[standardAttrs] = [name] +} + +const registeredStandardAttrs = new WeakSet() + +/** + * Registers the `@attr` members recorded in decorator metadata by standard + * decorators, so `initializeAttrs` and `defineObservedAttributes` find them. + * + * Walks up the class chain to include undecorated base classes, stopping at a + * class already registered, whose attrs `meta` copies to subclasses. Reads each + * class's own metadata because a class without a class decorator may get + * metadata that doesn't inherit from its parent's. */ -export function attr(proto: Record, key: K): void { - meta(proto, attrKey).add(key) +export function registerStandardAttrs(classObject: CustomElementClass): void { + const levels: string[][] = [] + for ( + let current: unknown = classObject; + typeof current === 'function' && !registeredStandardAttrs.has(current); + current = Object.getPrototypeOf(current) + ) { + const metadata = ownMetadata(current) + if (metadata && hasOwn(metadata, standardAttrs)) levels.unshift(metadata[standardAttrs] as string[]) + } + // Base class attrs first, matching the order legacy decorators register them in. + const attrs = meta(classObject.prototype, attrKey) + for (const key of levels.flat()) attrs.add(key) + registeredStandardAttrs.add(classObject) } /** diff --git a/src/bind.ts b/src/bind.ts index fe6d91af..4f617af9 100644 --- a/src/bind.ts +++ b/src/bind.ts @@ -101,7 +101,7 @@ function* bindings(el: Element): Iterable { type: action.slice(0, eventSep), tag: action.slice(eventSep + 1, methodSep), method: action.slice(methodSep + 1) || 'handleEvent' - } || 'handleEvent' + } } } diff --git a/src/controller.ts b/src/controller.ts index 0b4b74d6..dd719b02 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -1,20 +1,53 @@ import {CatalystDelegate} from './core.js' +import {registerStandardAttrs} from './attr.js' import type {CustomElementClass} from './custom-element.js' +import type {ClassContext} from './decorator-context.js' +import {isDecoratorContext} from './decorator-context.js' + +/** + * The decorator returned by `controller(name)`. It accepts both TypeScript's + * `experimentalDecorators` and standard decorator calls. + */ +export interface ControllerDecorator { + (classObject: C, context: ClassContext): void + (classObject: CustomElementClass): void +} + /** * Controller is a decorator to be used over a class that extends HTMLElement. * It will automatically `register()` the component in the customElement * registry, as well as ensuring `bind(this)` is called on `connectedCallback`, * wrapping the classes `connectedCallback` method if needed. + * + * It supports both TypeScript's `experimentalDecorators` and standard + * decorators. */ +export function controller(classObject: C, context: ClassContext): void export function controller(classObject: CustomElementClass): void -export function controller(name: string): (classObject: CustomElementClass) => void +export function controller(name: string): ControllerDecorator export function controller( - classObjectOrName: CustomElementClass | string -): void | ((classObject: CustomElementClass) => void) { + classObjectOrName: CustomElementClass | string, + context?: unknown +): void | ControllerDecorator { if (typeof classObjectOrName === 'string') { - return (classObject: CustomElementClass) => { - new CatalystDelegate(classObject, classObjectOrName) - } + const name = classObjectOrName + return (classObject: CustomElementClass, classContext?: unknown) => decorate(classObject, classContext, name) } - new CatalystDelegate(classObjectOrName) + decorate(classObjectOrName, context) +} + +function decorate(classObject: CustomElementClass, context: unknown, name?: string) { + if (!isDecoratorContext(context)) return defineController(classObject, name) + // Standard class decorators run before static fields such as `observedAttributes` and `attrPrefix` are assigned. + // Class initializers run after them, which is when legacy class decorators run. + const classContext = context as ClassContext + classContext.addInitializer(function (this: CustomElementClass) { + defineController(this, name) + }) +} + +function defineController(classObject: CustomElementClass, name?: string) { + // Picks up `@attr` members compiled as standard decorators, including when `controller` is called directly. + registerStandardAttrs(classObject) + new CatalystDelegate(classObject, name) } diff --git a/src/decorator-context.ts b/src/decorator-context.ts new file mode 100644 index 00000000..0a9db418 --- /dev/null +++ b/src/decorator-context.ts @@ -0,0 +1,64 @@ +/** + * The parts of standard (TC39) decorator contexts that Catalyst uses. Declared structurally rather than using + * TypeScript's `ClassDecoratorContext` and friends so the published types still load in TypeScript versions before + * 5.0, which lack them. + */ +export interface ClassContext { + readonly kind: 'class' + readonly name: string | undefined + readonly metadata?: object + addInitializer(initializer: (this: C) => void): void +} + +// Catalyst's member decorators only support public instance members with string names. TypeScript passes literal +// `static` and `private` types, so other members fail to type-check. +export interface MemberContext { + readonly kind: Kind + readonly name: string + readonly static: false + readonly private: false + readonly metadata?: object + readonly access: {get?(object: This): Value; set?(object: This, value: Value): void} + addInitializer(initializer: (this: This) => void): void +} + +export interface AccessorTarget { + get(this: This): Value + set(this: This, value: Value): void +} + +export interface AccessorResult { + get?(this: This): Value + set?(this: This, value: Value): void + init?(this: This, value: Value): Value +} + +// Lets compilers that only attach decorator metadata when `Symbol.metadata` exists (such as TypeScript) do so. Uses +// the same fallback key as the SWC and Babel helpers, and leaves an existing definition alone. +;(Symbol as {metadata?: symbol}).metadata ??= Symbol.for('Symbol.metadata') + +export const hasOwn = (object: object, key: PropertyKey): boolean => Object.prototype.hasOwnProperty.call(object, key) + +/** + * Returns the decorator metadata of the class itself, ignoring metadata it inherits from its parent class. + */ +export function ownMetadata(classObject: object): Record | undefined { + // Look the key up on every call, like the SWC and Babel helpers: another library may define `Symbol.metadata` + // after this module loads. + const key = (Symbol as {metadata?: symbol}).metadata ?? Symbol.for('Symbol.metadata') + if (hasOwn(classObject, key)) return (classObject as Record>)[key] +} + +// Standard decorators receive a context object as their second argument; legacy decorators receive the member name. +export function isDecoratorContext(value: unknown): value is ClassContext | MemberContext { + return typeof value === 'object' && value !== null && 'kind' in value && 'addInitializer' in value +} + +export function memberName(decorator: string, context: ClassContext | MemberContext, kinds: string[]): string { + // `kinds` never includes 'class', so class contexts fail the first check. + const member = context as MemberContext + if (!kinds.includes(member.kind) || member.static || member.private || typeof member.name !== 'string') { + throw new TypeError(`@${decorator} must decorate a public instance ${kinds.join('/')}`) + } + return member.name +} diff --git a/src/target.ts b/src/target.ts index 0ce510e6..20e19079 100644 --- a/src/target.ts +++ b/src/target.ts @@ -1,5 +1,7 @@ import {findTarget, findTargets} from './findtarget.js' import {meta} from './core.js' +import type {AccessorResult, AccessorTarget, MemberContext} from './decorator-context.js' +import {isDecoratorContext, memberName} from './decorator-context.js' /** * Target is a decorator which - when assigned to a property field on the @@ -7,9 +9,19 @@ import {meta} from './core.js' * returns a call to `findTarget(this, key)` where `key` is the name of the * property field. In other words, `@target foo` becomes a getter for * `findTarget(this, 'foo')`. + * + * With standard decorators it must decorate an accessor: + * `@target accessor foo!: HTMLElement`. */ -export function target(proto: Record, key: K): void { - meta(proto, 'target').add(key) +export function target( + value: AccessorTarget, + context: MemberContext<'accessor', This, Value> +): AccessorResult +export function target(proto: Record, key: K): void +export function target(proto: unknown, keyOrContext: unknown): unknown { + if (isDecoratorContext(keyOrContext)) return standardTarget('target', keyOrContext, findTarget) + const key = keyOrContext as string + meta(proto as Record, 'target').add(key) Object.defineProperty(proto, key, { configurable: true, get() { @@ -24,9 +36,19 @@ export function target(proto: Record, key: K): voi * returns a call to `findTargets(this, key)` where `key` is the name of the * property field. In other words, `@targets foo` becomes a getter for * `findTargets(this, 'foo')`. + * + * With standard decorators it must decorate an accessor: + * `@targets accessor foos!: HTMLElement[]`. */ -export function targets(proto: Record, key: K): void { - meta(proto, 'targets').add(key) +export function targets( + value: AccessorTarget, + context: MemberContext<'accessor', This, Value> +): AccessorResult +export function targets(proto: Record, key: K): void +export function targets(proto: unknown, keyOrContext: unknown): unknown { + if (isDecoratorContext(keyOrContext)) return standardTarget('targets', keyOrContext, findTargets) + const key = keyOrContext as string + meta(proto as Record, 'targets').add(key) Object.defineProperty(proto, key, { configurable: true, get() { @@ -34,3 +56,20 @@ export function targets(proto: Record, key: K): vo } }) } + +function standardTarget( + decorator: string, + context: Parameters[1], + find: (controller: HTMLElement, name: string) => unknown +) { + const key = memberName(decorator, context, ['accessor']) + return { + get(this: HTMLElement) { + return find(this, key) + }, + // Legacy decorators define a getter-only property, so assigning to it throws. + set() { + throw new TypeError(`Cannot set @${decorator} ${key}`) + } + } +} diff --git a/test/standard/attr.ts b/test/standard/attr.ts new file mode 100644 index 00000000..c69ffca5 --- /dev/null +++ b/test/standard/attr.ts @@ -0,0 +1,209 @@ +import {expect, fixture, html} from '@open-wc/testing' +import {controller} from '../../src/controller.js' +import {attr} from '../../src/attr.js' +import type {CustomElementClass} from '../../src/custom-element.js' + +const symbolWithMetadata = Symbol as {metadata?: symbol} +const observed = (classObject: CustomElementClass) => classObject.observedAttributes + +describe('Attr (standard decorators)', () => { + { + @controller + class StandardAttrElement extends HTMLElement { + @attr fooBar = 'hello' + @attr accessor fooCount = 2 + fooBaz = 1 + + #bing = 'world' + get bingBaz() { + return this.#bing + } + @attr set bingBaz(value: string) { + this.#bing = value + } + + @attr get fooFlag() { + return false + } + } + + let instance: StandardAttrElement + beforeEach(async () => { + instance = await fixture(html``) + }) + + it('does not alter field values from their initial value', () => { + expect(instance).to.have.property('fooBar', 'hello') + expect(instance).to.have.property('fooCount', 2) + expect(instance).to.have.property('fooBaz', 1) + expect(instance).to.have.property('bingBaz', 'world') + expect(instance).to.have.property('fooFlag', false) + }) + + it('reflects the initial value as an attribute, if not present', () => { + expect(instance).to.have.attribute('data-foo-bar', 'hello') + expect(instance).to.have.attribute('data-foo-count', '2') + expect(instance).to.not.have.attribute('data-foo-baz') + expect(instance).to.have.attribute('data-bing-baz', 'world') + expect(instance).to.not.have.attribute('data-foo-flag') + }) + + it('prioritises the value in the attribute over the property', async () => { + instance = await fixture( + html`` + ) + expect(instance).to.have.property('fooBar', 'goodbye') + expect(instance).to.have.property('fooCount', 5) + expect(instance).to.have.property('bingBaz', 'universe') + }) + + it('changes the property when the attribute changes', () => { + instance.setAttribute('data-foo-bar', 'goodbye') + instance.setAttribute('data-foo-count', '7') + instance.setAttribute('data-foo-flag', '') + expect(instance).to.have.property('fooBar', 'goodbye') + expect(instance).to.have.property('fooCount', 7) + expect(instance).to.have.property('fooFlag', true) + }) + + it('changes the attribute when the property changes', () => { + instance.fooBar = 'goodbye' + instance.fooCount = 3 + instance.bingBaz = 'universe' + expect(instance).to.have.attribute('data-foo-bar', 'goodbye') + expect(instance).to.have.attribute('data-foo-count', '3') + expect(instance).to.have.attribute('data-bing-baz', 'universe') + }) + + it('observes the attributes', () => { + expect(observed(StandardAttrElement)).to.have.members([ + 'data-foo-bar', + 'data-foo-count', + 'data-bing-baz', + 'data-foo-flag' + ]) + }) + } + + it('respects a static attrPrefix', async () => { + @controller + class StandardPrefixAttrElement extends HTMLElement { + static attrPrefix = 'foo-' + @attr URLBar = 'b' + } + const instance = await fixture(html``) + expect(instance).to.have.attribute('foo-url-bar', 'b') + }) + + it('registers attrs from undecorated base classes, base class first', async () => { + class Base extends HTMLElement { + @attr baseValue = 'base' + } + class Middle extends Base { + @attr middleValue = 1 + } + @controller + class StandardInheritedAttrElement extends Middle { + @attr ownValue = true + } + const instance = await fixture( + html`` + ) + expect(observed(StandardInheritedAttrElement)).to.eql(['data-base-value', 'data-middle-value', 'data-own-value']) + expect(instance).to.have.attribute('data-base-value', 'base') + expect(instance).to.have.attribute('data-middle-value', '1') + expect(instance).to.have.attribute('data-own-value', '') + }) + + it('inherits attrs from a parent controller without adding to it', async () => { + @controller + class StandardParentAttrElement extends HTMLElement { + @attr parentValue = 'p' + } + @controller + class StandardChildAttrElement extends StandardParentAttrElement { + @attr childValue = 'c' + } + expect(observed(StandardParentAttrElement)).to.eql(['data-parent-value']) + // Like legacy decorators, the inherited list repeats the parent's attributes. + expect([...new Set(observed(StandardChildAttrElement))]).to.eql(['data-parent-value', 'data-child-value']) + const child = await fixture(html``) + expect(child).to.have.attribute('data-parent-value', 'p') + expect(child).to.have.attribute('data-child-value', 'c') + }) + + it('keeps attrs of subclasses sharing an undecorated base class separate', () => { + class SharedBase extends HTMLElement { + @attr shared = '' + } + @controller + class StandardFirstSiblingElement extends SharedBase { + @attr first = '' + } + @controller + class StandardSecondSiblingElement extends SharedBase { + @attr second = '' + } + expect(observed(StandardFirstSiblingElement)).to.eql(['data-shared', 'data-first']) + expect(observed(StandardSecondSiblingElement)).to.eql(['data-shared', 'data-second']) + }) + + it('reads metadata stored under a Symbol.metadata defined after Catalyst loaded', async () => { + const original = symbolWithMetadata.metadata + symbolWithMetadata.metadata = Symbol('late metadata') + try { + @controller + class StandardLateMetadataElement extends HTMLElement { + @attr late = 'yes' + } + const instance = await fixture( + html`` + ) + expect(instance.getAttribute('data-late')).to.equal('yes') + } finally { + symbolWithMetadata.metadata = original + } + }) + + it('throws a clear error without decorator metadata', () => { + const original = symbolWithMetadata.metadata + delete symbolWithMetadata.metadata + try { + expect( + () => + class extends HTMLElement { + @attr foo = '' + } + ).to.throw(TypeError, '@attr requires decorator metadata') + } finally { + symbolWithMetadata.metadata = original + } + }) + + it('throws for unsupported members', () => { + const message = '@attr must decorate a public instance field/accessor/getter/setter' + expect( + () => + class extends HTMLElement { + // @ts-expect-error static members are not supported + @attr static foo = '' + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error private members are not supported + @attr #foo = '' + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error methods are not supported + @attr foo() { + return '' + } + } + ).to.throw(TypeError, message) + }) +}) diff --git a/test/standard/controller.ts b/test/standard/controller.ts new file mode 100644 index 00000000..54f48ab5 --- /dev/null +++ b/test/standard/controller.ts @@ -0,0 +1,64 @@ +import {expect, fixture, html} from '@open-wc/testing' +import {fake} from 'sinon' +import {controller} from '../../src/controller.js' +import {attr} from '../../src/attr.js' + +describe('controller (standard decorators)', () => { + it('registers the element', async () => { + @controller + class StandardRegisterElement extends HTMLElement {} + const instance = await fixture(html``) + expect(instance).to.be.instanceof(StandardRegisterElement) + expect(instance).to.have.attribute('data-catalyst', '') + }) + + it('registers the element with a custom name', async () => { + @controller('standard-named-widget') + class StandardNamedElement extends HTMLElement {} + const instance = await fixture(html``) + expect(instance).to.be.instanceof(StandardNamedElement) + expect(instance).to.have.attribute('data-catalyst', '') + }) + + it('registers attrs when called as a function', async () => { + controller('standard-function-attr')( + class extends HTMLElement { + @attr foo = 'bar' + } + ) + const instance = await fixture(html``) + expect(instance.getAttribute('data-foo')).to.equal('bar') + }) + + it('binds actions', async () => { + @controller + class StandardBindElement extends HTMLElement { + foo = fake() + } + const instance = await fixture(html` + + `) + instance.querySelector('button')!.click() + expect(instance.foo).to.have.callCount(1) + }) + + it('defines the element after static fields are assigned', async () => { + const changed: string[] = [] + @controller + class StandardStaticsElement extends HTMLElement { + static observedAttributes = ['data-extra'] + static attrPrefix = 'x-' + @attr name = 'a' + attributeChangedCallback(name: string) { + changed.push(name) + } + } + const instance = await fixture(html``) + expect(instance.getAttribute('x-name')).to.equal('a') + changed.length = 0 + instance.setAttribute('data-extra', '1') + instance.setAttribute('x-name', 'b') + expect(changed).to.eql(['data-extra', 'x-name']) + expect(instance.name).to.equal('b') + }) +}) diff --git a/test/standard/metadata.ts b/test/standard/metadata.ts new file mode 100644 index 00000000..f5d0fbea --- /dev/null +++ b/test/standard/metadata.ts @@ -0,0 +1,29 @@ +// Imports Catalyst first and avoids @open-wc/testing, because Lit defines `Symbol.metadata` too. +import {controller} from '../../src/controller.js' +import {attr} from '../../src/attr.js' + +function assert(condition: boolean, message: string) { + if (!condition) throw new Error(message) +} + +describe('Symbol.metadata (standard decorators)', () => { + it('is defined when Catalyst loads, so TypeScript output includes decorator metadata', () => { + const metadata = (Symbol as {metadata?: symbol}).metadata + assert(metadata === Symbol.for('Symbol.metadata'), `expected Symbol.metadata, got ${String(metadata)}`) + }) + + it('registers attrs from TypeScript output', () => { + @controller + class StandardMetadataElement extends HTMLElement { + @attr foo = 'bar' + } + const instance = document.createElement('standard-metadata') + document.body.append(instance) + assert(instance instanceof StandardMetadataElement, 'expected the element to be defined') + assert( + instance.getAttribute('data-foo') === 'bar', + `expected data-foo="bar", got ${instance.getAttribute('data-foo')}` + ) + instance.remove() + }) +}) diff --git a/test/standard/target.ts b/test/standard/target.ts new file mode 100644 index 00000000..b90426e1 --- /dev/null +++ b/test/standard/target.ts @@ -0,0 +1,110 @@ +import {expect, fixture, html} from '@open-wc/testing' +import {target, targets} from '../../src/target.js' +import {controller} from '../../src/controller.js' + +describe('Targetable (standard decorators)', () => { + @controller + class StandardTargetElement extends HTMLElement { + @target accessor foo!: Element + bar = 'hello' + @target accessor baz!: Element + @target accessor qux!: Element + @target accessor shadow!: Element + @target accessor bing!: Element + @targets accessor foos!: Element[] + } + + let instance: StandardTargetElement + beforeEach(async () => { + instance = await fixture(html` + +
+
+
+
+
+
+
+
+
`) + }) + + describe('target', () => { + it('returns the first element where closest tag is the controller', () => { + expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') + expect(instance.querySelector('standard-target')).to.have.property('foo').exist.with.attribute('id', 'el2') + }) + + it('does not assign to non-target decorated properties', () => { + expect(instance).to.have.property('bar', 'hello') + }) + + it('returns the element with the exact target name', () => { + expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') + expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') + expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') + }) + + it('prioritises shadowRoot targets over others', () => { + instance.attachShadow({mode: 'open'}) + const shadowEl = document.createElement('div') + shadowEl.setAttribute('data-target', 'standard-target.foo') + instance.shadowRoot!.appendChild(shadowEl) + expect(instance).to.have.property('foo', shadowEl) + }) + + it('throws on assignment, like the getter-only legacy property', () => { + expect(() => { + instance.foo = document.body + }).to.throw(TypeError, 'Cannot set @target foo') + }) + }) + + describe('targets', () => { + it('returns all elements where closest tag is the controller', () => { + expect(instance).to.have.property('foos').with.lengthOf(2) + expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') + expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') + }) + + it('throws on assignment', () => { + expect(() => { + instance.foos = [] + }).to.throw(TypeError, 'Cannot set @targets foos') + }) + }) + + it('throws for members other than public instance accessors', () => { + const message = '@target must decorate a public instance accessor' + expect( + () => + class extends HTMLElement { + // @ts-expect-error fields would shadow the getter + @target foo!: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error static members are not supported + @target static accessor foo: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error private members are not supported + @target accessor #foo!: Element + } + ).to.throw(TypeError, message) + expect( + () => + class extends HTMLElement { + // @ts-expect-error methods are not supported + @targets foo() { + return [] + } + } + ).to.throw(TypeError, '@targets must decorate a public instance accessor') + }) +}) diff --git a/test/standard/tsconfig.json b/test/standard/tsconfig.json new file mode 100644 index 00000000..2550fd61 --- /dev/null +++ b/test/standard/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": ["*.ts", "../types/*.ts"], + "exclude": [], + "compilerOptions": { + "experimentalDecorators": false, + "target": "ES2022" + } +} diff --git a/test/types/decorators.ts b/test/types/decorators.ts new file mode 100644 index 00000000..2da87939 --- /dev/null +++ b/test/types/decorators.ts @@ -0,0 +1,37 @@ +// Compile-time checks, run under both decorator modes: `tsc` (experimentalDecorators) and `tsc -p test/standard` +// (standard decorators). Nothing here runs. `@target` and `@targets` need `accessor` in standard mode and a plain +// field in legacy mode, so they're covered by test/target.ts and test/standard/target.ts instead. +import {controller} from '../../src/controller.js' +import {attr} from '../../src/attr.js' +import type {CustomElementClass} from '../../src/custom-element.js' + +@controller +export class TypesElement extends HTMLElement { + static attrPrefix = 'types-' + static observedAttributes = ['data-extra'] + + @attr text = '' + @attr count = 0 + @attr enabled = false + + @attr + get computed(): string { + return '' + } + set computed(value: string) { + this.text = value + } + + // @ts-expect-error attrs must be strings, numbers or booleans + @attr date = new Date() +} + +@controller('types-named-element') +export class TypesNamedElement extends HTMLElement {} + +controller('types-direct-element')(class TypesDirectElement extends HTMLElement {}) +controller(class TypesDirectUnnamedElement extends HTMLElement {}) +attr(TypesElement.prototype, 'text') + +// The decorator `controller(name)` returns is still assignable to the legacy class decorator type. +export const named: (classObject: CustomElementClass) => void = controller('types-assigned-element') diff --git a/tsconfig.json b/tsconfig.json index d1749ff4..9b7b7916 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "include": ["src", "test"], + "exclude": ["test/standard"], "compilerOptions": { "baseUrl": ".", "esModuleInterop": true, @@ -10,6 +11,7 @@ "noEmit": true, "sourceMap": true, "strict": true, - "target": "ES2020" + "target": "ES2020", + "types": ["mocha"] } } diff --git a/web-test-runner.config.js b/web-test-runner.config.js index 68d0a046..85ac5668 100644 --- a/web-test-runner.config.js +++ b/web-test-runner.config.js @@ -1,10 +1,31 @@ import {esbuildPlugin} from '@web/dev-server-esbuild' +import ts from 'typescript' + +// esbuild only lowers legacy decorators, so compile test/standard with TypeScript's standard decorators first. Emit +// ES2020 so esbuild has nothing left to lower: its class lowering renames classes, and Catalyst derives tag names from +// class names. +const standardDecorators = { + name: 'standard-decorators', + transform(context) { + if (!context.path.includes('/test/standard/')) return + const {outputText} = ts.transpileModule(context.body, { + fileName: context.path, + compilerOptions: { + experimentalDecorators: false, + target: ts.ScriptTarget.ES2020, + useDefineForClassFields: true, + module: ts.ModuleKind.ESNext + } + }) + return {body: outputText} + } +} export default { - files: ['test/*'], + files: ['test/*.ts', 'test/standard/*.ts'], nodeResolve: true, concurrency: 1, testsFinishTimeout: 30000, - plugins: [esbuildPlugin({ts: true, target: 'es2020'})], + plugins: [standardDecorators, esbuildPlugin({ts: true, target: 'es2020'})], filterBrowserLogs: log => !log.args.some(arg => typeof arg === 'string' && arg.includes('Lit is in dev mode')) } From 75d399e1630d6a4ca5793c0efd955c36f0ca6b73 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:09:33 -0500 Subject: [PATCH 02/26] Guard Symbol.metadata against frozen Symbol, register standard attrs in manual setup Importing Catalyst no longer throws when Symbol is frozen (SES lockdown). defineObservedAttributes and initializeAttrs now pick up standard @attr members without @controller, as they do for legacy decorators. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 7 ++++++- src/decorator-context.ts | 6 +++++- test/frozen-symbol.ts | 13 +++++++++++++ test/standard/attr.ts | 24 +++++++++++++++++++++++- 4 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 test/frozen-symbol.ts diff --git a/src/attr.ts b/src/attr.ts index 743d9597..7c6d5acb 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -51,6 +51,7 @@ const registeredStandardAttrs = new WeakSet() * metadata that doesn't inherit from its parent's. */ export function registerStandardAttrs(classObject: CustomElementClass): void { + if (registeredStandardAttrs.has(classObject)) return const levels: string[][] = [] for ( let current: unknown = classObject; @@ -91,7 +92,10 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) initialized.add(instance) const proto = Object.getPrototypeOf(instance) const prefix = proto?.constructor?.attrPrefix ?? 'data-' - if (!names) names = meta(proto, attrKey) + if (!names) { + if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) + names = meta(proto, attrKey) + } for (const key of names) { const value = (>(instance))[key] const name = mustDasherize(`${prefix}${key}`) @@ -133,6 +137,7 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) } export function defineObservedAttributes(classObject: CustomElementClass): void { + registerStandardAttrs(classObject) let observed = classObject.observedAttributes || [] const prefix = classObject.attrPrefix ?? 'data-' diff --git a/src/decorator-context.ts b/src/decorator-context.ts index 0a9db418..5b069c2c 100644 --- a/src/decorator-context.ts +++ b/src/decorator-context.ts @@ -35,7 +35,11 @@ export interface AccessorResult { // Lets compilers that only attach decorator metadata when `Symbol.metadata` exists (such as TypeScript) do so. Uses // the same fallback key as the SWC and Babel helpers, and leaves an existing definition alone. -;(Symbol as {metadata?: symbol}).metadata ??= Symbol.for('Symbol.metadata') +try { + ;(Symbol as {metadata?: symbol}).metadata ??= Symbol.for('Symbol.metadata') +} catch { + // `Symbol` is frozen, for example by SES `lockdown()`. Legacy decorators don't need metadata. +} export const hasOwn = (object: object, key: PropertyKey): boolean => Object.prototype.hasOwnProperty.call(object, key) diff --git a/test/frozen-symbol.ts b/test/frozen-symbol.ts new file mode 100644 index 00000000..8ab138b0 --- /dev/null +++ b/test/frozen-symbol.ts @@ -0,0 +1,13 @@ +import {expect} from '@open-wc/testing' + +describe('frozen Symbol', () => { + it('can still import Catalyst', async () => { + const symbolWithMetadata = Symbol as {metadata?: symbol} + // Lit, loaded by @open-wc/testing, defines `Symbol.metadata`. Remove it so Catalyst tries to define it. + delete symbolWithMetadata.metadata + Object.freeze(Symbol) + const catalyst = await import('../src/index.js') + expect(catalyst.controller).to.be.a('function') + expect(symbolWithMetadata.metadata).to.equal(undefined) + }) +}) diff --git a/test/standard/attr.ts b/test/standard/attr.ts index c69ffca5..a7d5f8d9 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -1,6 +1,6 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../../src/controller.js' -import {attr} from '../../src/attr.js' +import {attr, defineObservedAttributes, initializeAttrs} from '../../src/attr.js' import type {CustomElementClass} from '../../src/custom-element.js' const symbolWithMetadata = Symbol as {metadata?: symbol} @@ -85,6 +85,28 @@ describe('Attr (standard decorators)', () => { }) } + it('registers attrs for defineObservedAttributes and initializeAttrs without @controller', async () => { + class StandardManualAttrElement extends HTMLElement { + @attr foo = 'bar' + connectedCallback() { + initializeAttrs(this) + } + } + defineObservedAttributes(StandardManualAttrElement) + customElements.define('standard-manual-attr', StandardManualAttrElement) + expect(observed(StandardManualAttrElement)).to.eql(['data-foo']) + + class StandardInitializeOnlyElement extends HTMLElement { + @attr foo = 'baz' + connectedCallback() { + initializeAttrs(this) + } + } + customElements.define('standard-initialize-only', StandardInitializeOnlyElement) + const instance = await fixture(html``) + expect(instance.getAttribute('data-foo')).to.equal('baz') + }) + it('respects a static attrPrefix', async () => { @controller class StandardPrefixAttrElement extends HTMLElement { From 82f5effbd3c646cc468935defd594f1070e636c2 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:11:49 -0500 Subject: [PATCH 03/26] Point lockfile entries at registry.npmjs.org Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package-lock.json | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8f3dc91b..0108136b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -94,7 +94,7 @@ }, "node_modules/@eslint-community/eslint-utils": { "version": "4.10.1", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", "integrity": "sha1-iRG9crLDZApUNgngQAuMTS5+fLY=", "dev": true, "license": "MIT", @@ -113,7 +113,7 @@ }, "node_modules/@eslint-community/regexpp": { "version": "4.12.2", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", "integrity": "sha1-vM32Fbz3tujbgw7AuNIcmiXeWXs=", "dev": true, "license": "MIT", @@ -1758,7 +1758,7 @@ }, "node_modules/@types/json-schema": { "version": "7.0.15", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@types/json-schema/-/json-schema-7.0.15.tgz", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "integrity": "sha1-WWoXRyM2lNUPatinhp/Lb1bPWEE=", "dev": true, "license": "MIT" @@ -1846,7 +1846,7 @@ }, "node_modules/@types/semver": { "version": "7.8.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@types/semver/-/semver-7.8.0.tgz", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", "dev": true, "license": "MIT" @@ -1915,7 +1915,7 @@ }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", "dev": true, "license": "MIT", @@ -1950,7 +1950,7 @@ }, "node_modules/@typescript-eslint/parser": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", "dev": true, "license": "BSD-2-Clause", @@ -1978,7 +1978,7 @@ }, "node_modules/@typescript-eslint/scope-manager": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", "dev": true, "license": "MIT", @@ -1996,7 +1996,7 @@ }, "node_modules/@typescript-eslint/type-utils": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", "dev": true, "license": "MIT", @@ -2024,7 +2024,7 @@ }, "node_modules/@typescript-eslint/types": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/types/-/types-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", "dev": true, "license": "MIT", @@ -2038,7 +2038,7 @@ }, "node_modules/@typescript-eslint/typescript-estree": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", "dev": true, "license": "BSD-2-Clause", @@ -2066,7 +2066,7 @@ }, "node_modules/@typescript-eslint/utils": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/utils/-/utils-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", "dev": true, "license": "MIT", @@ -2093,7 +2093,7 @@ }, "node_modules/@typescript-eslint/visitor-keys": { "version": "5.62.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", "dev": true, "license": "MIT", @@ -5016,7 +5016,7 @@ }, "node_modules/eslint-scope": { "version": "5.1.1", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eslint-scope/-/eslint-scope-5.1.1.tgz", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "license": "BSD-2-Clause", @@ -5057,7 +5057,7 @@ }, "node_modules/eslint-visitor-keys": { "version": "3.4.3", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", "integrity": "sha1-DNcv6FUOPC6uFWqWpN3c0cisWAA=", "dev": true, "license": "Apache-2.0", @@ -5357,7 +5357,7 @@ }, "node_modules/estraverse": { "version": "4.3.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/estraverse/-/estraverse-4.3.0.tgz", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true, "license": "BSD-2-Clause", @@ -6021,7 +6021,7 @@ }, "node_modules/graphemer": { "version": "1.4.0", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/graphemer/-/graphemer-1.4.0.tgz", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", "integrity": "sha1-+y8dVeDjoYSa7/yQxPoN1ToOZsY=", "dev": true, "license": "MIT" @@ -7929,7 +7929,7 @@ }, "node_modules/natural-compare-lite": { "version": "1.4.1", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/natural-compare-lite/-/natural-compare-lite-1.4.1.tgz", + "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.1.tgz", "integrity": "sha512-8Mz06azhPqiDlxhUaUTjBhNAbib/1MoPr89kgmuV6Ir8ICT2/Q/XSYg6VfL3fq2x8MpSQX8sqyI/NeZ5GsGyXA==", "dev": true, "license": "MIT" @@ -8468,7 +8468,7 @@ }, "node_modules/prettier": { "version": "2.8.8", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/prettier/-/prettier-2.8.8.tgz", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true, "license": "MIT", @@ -9897,7 +9897,7 @@ }, "node_modules/typescript": { "version": "5.9.3", - "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/typescript/-/typescript-5.9.3.tgz", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", From 02c874b8ac4af9b089a5ef744e76f80de0ff9dfd Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:00:22 -0500 Subject: [PATCH 04/26] Run shared decorator tests under both legacy and standard decorators npm test now runs web-test-runner twice. The second run compiles test/attr.ts, test/bind.ts and test/controller.ts with standard decorators, plus test/standard for standard-only syntax. Target assertions live in test/helpers/target-tests.ts, used by a legacy and a standard fixture. Cross-mode cases moved from test/standard into the shared files. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package.json | 2 +- test/attr.ts | 82 +++++++++++++++++++++++++- test/controller.ts | 29 +++++++++ test/helpers/target-tests.ts | 94 ++++++++++++++++++++++++++++++ test/standard/attr.ts | 88 +--------------------------- test/standard/controller.ts | 64 -------------------- test/standard/target.ts | 69 ++++------------------ test/standard/tsconfig.json | 2 +- test/target.ts | 79 +------------------------ web-test-runner-standard.config.js | 32 ++++++++++ web-test-runner.config.js | 25 +------- 11 files changed, 255 insertions(+), 311 deletions(-) create mode 100644 test/helpers/target-tests.ts delete mode 100644 test/standard/controller.ts create mode 100644 web-test-runner-standard.config.js diff --git a/package.json b/package.json index 08c3bed1..f56371a2 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "prepack": "npm run build", "presize": "npm run build", "size": "size-limit", - "test": "web-test-runner" + "test": "web-test-runner && web-test-runner --config web-test-runner-standard.config.js" }, "prettier": "@github/prettier-config", "devDependencies": { diff --git a/test/attr.ts b/test/attr.ts index 7eab85bf..48310d1e 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -1,6 +1,9 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../src/controller.js' -import {attr} from '../src/attr.js' +import {attr, defineObservedAttributes, initializeAttrs} from '../src/attr.js' +import type {CustomElementClass} from '../src/custom-element.js' + +const observed = (classObject: CustomElementClass) => classObject.observedAttributes describe('Attr', () => { { @@ -177,4 +180,81 @@ describe('Attr', () => { expect(instance.getAttributeNames()).to.include('foo-clip-x') }) }) + + describe('inheritance', () => { + it('registers attrs from undecorated base classes, base class first', async () => { + class Base extends HTMLElement { + @attr baseValue = 'base' + } + class Middle extends Base { + @attr middleValue = 1 + } + @controller + class InheritedAttrTest extends Middle { + @attr ownValue = true + } + const instance = await fixture(html``) + expect(observed(InheritedAttrTest)).to.eql(['data-base-value', 'data-middle-value', 'data-own-value']) + expect(instance).to.have.attribute('data-base-value', 'base') + expect(instance).to.have.attribute('data-middle-value', '1') + expect(instance).to.have.attribute('data-own-value', '') + }) + + it('inherits attrs from a parent controller without adding to it', async () => { + @controller + class ParentAttrTest extends HTMLElement { + @attr parentValue = 'p' + } + @controller + class ChildAttrTest extends ParentAttrTest { + @attr childValue = 'c' + } + expect(observed(ParentAttrTest)).to.eql(['data-parent-value']) + // The inherited list repeats the parent's attributes. + expect([...new Set(observed(ChildAttrTest))]).to.eql(['data-parent-value', 'data-child-value']) + const child = await fixture(html``) + expect(child).to.have.attribute('data-parent-value', 'p') + expect(child).to.have.attribute('data-child-value', 'c') + }) + + it('keeps attrs of subclasses sharing an undecorated base class separate', () => { + class SharedBase extends HTMLElement { + @attr shared = '' + } + @controller + class FirstSiblingAttrTest extends SharedBase { + @attr first = '' + } + @controller + class SecondSiblingAttrTest extends SharedBase { + @attr second = '' + } + expect(observed(FirstSiblingAttrTest)).to.eql(['data-shared', 'data-first']) + expect(observed(SecondSiblingAttrTest)).to.eql(['data-shared', 'data-second']) + }) + }) + + describe('without @controller', () => { + it('registers attrs for defineObservedAttributes and initializeAttrs', async () => { + class ManualAttrTest extends HTMLElement { + @attr foo = 'bar' + connectedCallback() { + initializeAttrs(this) + } + } + defineObservedAttributes(ManualAttrTest) + customElements.define('manual-attr-test', ManualAttrTest) + expect(observed(ManualAttrTest)).to.eql(['data-foo']) + + class InitializeOnlyAttrTest extends HTMLElement { + @attr foo = 'baz' + connectedCallback() { + initializeAttrs(this) + } + } + customElements.define('initialize-only-attr-test', InitializeOnlyAttrTest) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'baz') + }) + }) }) diff --git a/test/controller.ts b/test/controller.ts index 872a26e0..7c4a4095 100644 --- a/test/controller.ts +++ b/test/controller.ts @@ -27,6 +27,35 @@ describe('controller', () => { expect(instance).to.exist }) + it('registers attrs when called as a function', async () => { + class FunctionAttrElement extends HTMLElement { + @attr foo = 'bar' + } + controller('function-attr-element')(FunctionAttrElement) + instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'bar') + }) + + it('defines the element after static fields are assigned', async () => { + const changed: string[] = [] + @controller + class ControllerStaticsElement extends HTMLElement { + static observedAttributes = ['data-extra'] + static attrPrefix = 'x-' + @attr name = 'a' + attributeChangedCallback(name: string) { + changed.push(name) + } + } + const element = await fixture(html``) + expect(element).to.have.attribute('x-name', 'a') + changed.length = 0 + element.setAttribute('data-extra', '1') + element.setAttribute('x-name', 'b') + expect(changed).to.eql(['data-extra', 'x-name']) + expect(element.name).to.equal('b') + }) + it('adds data-catalyst to elements with custom names', async () => { @controller('custom-named-element') // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/test/helpers/target-tests.ts b/test/helpers/target-tests.ts new file mode 100644 index 00000000..c4c70255 --- /dev/null +++ b/test/helpers/target-tests.ts @@ -0,0 +1,94 @@ +import {expect, fixture, html} from '@open-wc/testing' + +/** + * Target tests shared by both decorator modes. test/target.ts (legacy decorators) and test/standard/target.ts + * (standard decorators) each define `` with `foo`, `baz`, `qux`, `shadow` and `bing` targets, a `foos` + * targets list and a plain `bar = 'hello'` field, then call this. + */ +export function targetTests() { + let instance: HTMLElement + beforeEach(async () => { + instance = await fixture(html` + +
+
+
+
+
+
+
+
+
+
`) + }) + + describe('target', () => { + it('returns the first element where closest tag is the controller', async () => { + expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') + expect(instance.querySelector('target-test')).to.have.property('foo').exist.with.attribute('id', 'el2') + }) + + it('does not assign to non-target decorated properties', async () => { + expect(instance).to.have.property('bar', 'hello') + }) + + it('returns the first element that has the exact target name', async () => { + expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') + }) + + it('returns target when there are mutliple target values', async () => { + expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') + }) + + it('returns targets when there are mutliple target values with different controllers', async () => { + expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') + }) + + it('returns targets from the shadowRoot, if available', async () => { + instance.attachShadow({mode: 'open'}) + const el = document.createElement('div') + el.setAttribute('data-target', 'target-test.shadow') + instance.shadowRoot!.appendChild(el) + expect(instance).to.have.property('shadow', el) + }) + + it('prioritises shadowRoot targets over others', async () => { + instance.attachShadow({mode: 'open'}) + const shadowEl = document.createElement('div') + shadowEl.setAttribute('data-target', 'target-test.foo') + instance.shadowRoot!.appendChild(shadowEl) + expect(instance).to.have.property('foo', shadowEl) + }) + }) + + it('throws when a target is assigned, because it is a getter', () => { + expect(() => { + ;(instance as unknown as Record).foo = document.body + }).to.throw(TypeError) + expect(() => { + ;(instance as unknown as Record).foos = [] + }).to.throw(TypeError) + }) + + describe('targets', () => { + it('returns all elements where closest tag is the controller', async () => { + expect(instance).to.have.property('foos').with.lengthOf(2) + expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') + expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') + }) + + it('returns all elements inside a shadow root', async () => { + instance.attachShadow({mode: 'open'}) + const els = [document.createElement('div'), document.createElement('div'), document.createElement('div')] + for (const el of els) el.setAttribute('data-targets', 'target-test.foos') + instance.shadowRoot!.append(...els) + + expect(instance).to.have.property('foos').with.lengthOf(5) + expect(instance).to.have.nested.property('foos[0]', els[0]) + expect(instance).to.have.nested.property('foos[1]', els[1]) + expect(instance).to.have.nested.property('foos[2]', els[2]) + expect(instance).to.have.nested.property('foos[3]').with.attribute('id', 'el4') + expect(instance).to.have.nested.property('foos[4]').with.attribute('id', 'el5') + }) + }) +} diff --git a/test/standard/attr.ts b/test/standard/attr.ts index a7d5f8d9..899c6a83 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -1,11 +1,12 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../../src/controller.js' -import {attr, defineObservedAttributes, initializeAttrs} from '../../src/attr.js' +import {attr} from '../../src/attr.js' import type {CustomElementClass} from '../../src/custom-element.js' const symbolWithMetadata = Symbol as {metadata?: symbol} const observed = (classObject: CustomElementClass) => classObject.observedAttributes +// Shared @attr behaviour is in test/attr.ts, which also runs with standard decorators. describe('Attr (standard decorators)', () => { { @controller @@ -85,91 +86,6 @@ describe('Attr (standard decorators)', () => { }) } - it('registers attrs for defineObservedAttributes and initializeAttrs without @controller', async () => { - class StandardManualAttrElement extends HTMLElement { - @attr foo = 'bar' - connectedCallback() { - initializeAttrs(this) - } - } - defineObservedAttributes(StandardManualAttrElement) - customElements.define('standard-manual-attr', StandardManualAttrElement) - expect(observed(StandardManualAttrElement)).to.eql(['data-foo']) - - class StandardInitializeOnlyElement extends HTMLElement { - @attr foo = 'baz' - connectedCallback() { - initializeAttrs(this) - } - } - customElements.define('standard-initialize-only', StandardInitializeOnlyElement) - const instance = await fixture(html``) - expect(instance.getAttribute('data-foo')).to.equal('baz') - }) - - it('respects a static attrPrefix', async () => { - @controller - class StandardPrefixAttrElement extends HTMLElement { - static attrPrefix = 'foo-' - @attr URLBar = 'b' - } - const instance = await fixture(html``) - expect(instance).to.have.attribute('foo-url-bar', 'b') - }) - - it('registers attrs from undecorated base classes, base class first', async () => { - class Base extends HTMLElement { - @attr baseValue = 'base' - } - class Middle extends Base { - @attr middleValue = 1 - } - @controller - class StandardInheritedAttrElement extends Middle { - @attr ownValue = true - } - const instance = await fixture( - html`` - ) - expect(observed(StandardInheritedAttrElement)).to.eql(['data-base-value', 'data-middle-value', 'data-own-value']) - expect(instance).to.have.attribute('data-base-value', 'base') - expect(instance).to.have.attribute('data-middle-value', '1') - expect(instance).to.have.attribute('data-own-value', '') - }) - - it('inherits attrs from a parent controller without adding to it', async () => { - @controller - class StandardParentAttrElement extends HTMLElement { - @attr parentValue = 'p' - } - @controller - class StandardChildAttrElement extends StandardParentAttrElement { - @attr childValue = 'c' - } - expect(observed(StandardParentAttrElement)).to.eql(['data-parent-value']) - // Like legacy decorators, the inherited list repeats the parent's attributes. - expect([...new Set(observed(StandardChildAttrElement))]).to.eql(['data-parent-value', 'data-child-value']) - const child = await fixture(html``) - expect(child).to.have.attribute('data-parent-value', 'p') - expect(child).to.have.attribute('data-child-value', 'c') - }) - - it('keeps attrs of subclasses sharing an undecorated base class separate', () => { - class SharedBase extends HTMLElement { - @attr shared = '' - } - @controller - class StandardFirstSiblingElement extends SharedBase { - @attr first = '' - } - @controller - class StandardSecondSiblingElement extends SharedBase { - @attr second = '' - } - expect(observed(StandardFirstSiblingElement)).to.eql(['data-shared', 'data-first']) - expect(observed(StandardSecondSiblingElement)).to.eql(['data-shared', 'data-second']) - }) - it('reads metadata stored under a Symbol.metadata defined after Catalyst loaded', async () => { const original = symbolWithMetadata.metadata symbolWithMetadata.metadata = Symbol('late metadata') diff --git a/test/standard/controller.ts b/test/standard/controller.ts deleted file mode 100644 index 54f48ab5..00000000 --- a/test/standard/controller.ts +++ /dev/null @@ -1,64 +0,0 @@ -import {expect, fixture, html} from '@open-wc/testing' -import {fake} from 'sinon' -import {controller} from '../../src/controller.js' -import {attr} from '../../src/attr.js' - -describe('controller (standard decorators)', () => { - it('registers the element', async () => { - @controller - class StandardRegisterElement extends HTMLElement {} - const instance = await fixture(html``) - expect(instance).to.be.instanceof(StandardRegisterElement) - expect(instance).to.have.attribute('data-catalyst', '') - }) - - it('registers the element with a custom name', async () => { - @controller('standard-named-widget') - class StandardNamedElement extends HTMLElement {} - const instance = await fixture(html``) - expect(instance).to.be.instanceof(StandardNamedElement) - expect(instance).to.have.attribute('data-catalyst', '') - }) - - it('registers attrs when called as a function', async () => { - controller('standard-function-attr')( - class extends HTMLElement { - @attr foo = 'bar' - } - ) - const instance = await fixture(html``) - expect(instance.getAttribute('data-foo')).to.equal('bar') - }) - - it('binds actions', async () => { - @controller - class StandardBindElement extends HTMLElement { - foo = fake() - } - const instance = await fixture(html` - - `) - instance.querySelector('button')!.click() - expect(instance.foo).to.have.callCount(1) - }) - - it('defines the element after static fields are assigned', async () => { - const changed: string[] = [] - @controller - class StandardStaticsElement extends HTMLElement { - static observedAttributes = ['data-extra'] - static attrPrefix = 'x-' - @attr name = 'a' - attributeChangedCallback(name: string) { - changed.push(name) - } - } - const instance = await fixture(html``) - expect(instance.getAttribute('x-name')).to.equal('a') - changed.length = 0 - instance.setAttribute('data-extra', '1') - instance.setAttribute('x-name', 'b') - expect(changed).to.eql(['data-extra', 'x-name']) - expect(instance.name).to.equal('b') - }) -}) diff --git a/test/standard/target.ts b/test/standard/target.ts index b90426e1..29d26794 100644 --- a/test/standard/target.ts +++ b/test/standard/target.ts @@ -1,10 +1,11 @@ import {expect, fixture, html} from '@open-wc/testing' import {target, targets} from '../../src/target.js' import {controller} from '../../src/controller.js' +import {targetTests} from '../helpers/target-tests.js' describe('Targetable (standard decorators)', () => { @controller - class StandardTargetElement extends HTMLElement { + class TargetTestElement extends HTMLElement { @target accessor foo!: Element bar = 'hello' @target accessor baz!: Element @@ -14,64 +15,16 @@ describe('Targetable (standard decorators)', () => { @targets accessor foos!: Element[] } - let instance: StandardTargetElement - beforeEach(async () => { - instance = await fixture(html` - -
-
-
-
-
-
-
-
-
`) - }) - - describe('target', () => { - it('returns the first element where closest tag is the controller', () => { - expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') - expect(instance.querySelector('standard-target')).to.have.property('foo').exist.with.attribute('id', 'el2') - }) - - it('does not assign to non-target decorated properties', () => { - expect(instance).to.have.property('bar', 'hello') - }) - - it('returns the element with the exact target name', () => { - expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') - expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') - expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') - }) - - it('prioritises shadowRoot targets over others', () => { - instance.attachShadow({mode: 'open'}) - const shadowEl = document.createElement('div') - shadowEl.setAttribute('data-target', 'standard-target.foo') - instance.shadowRoot!.appendChild(shadowEl) - expect(instance).to.have.property('foo', shadowEl) - }) - - it('throws on assignment, like the getter-only legacy property', () => { - expect(() => { - instance.foo = document.body - }).to.throw(TypeError, 'Cannot set @target foo') - }) - }) - - describe('targets', () => { - it('returns all elements where closest tag is the controller', () => { - expect(instance).to.have.property('foos').with.lengthOf(2) - expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') - expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') - }) + targetTests() - it('throws on assignment', () => { - expect(() => { - instance.foos = [] - }).to.throw(TypeError, 'Cannot set @targets foos') - }) + it('names the target in the assignment error', async () => { + const instance = await fixture(html``) + expect(() => { + instance.foo = document.body + }).to.throw(TypeError, 'Cannot set @target foo') + expect(() => { + instance.foos = [] + }).to.throw(TypeError, 'Cannot set @targets foos') }) it('throws for members other than public instance accessors', () => { diff --git a/test/standard/tsconfig.json b/test/standard/tsconfig.json index 2550fd61..0cc9707c 100644 --- a/test/standard/tsconfig.json +++ b/test/standard/tsconfig.json @@ -1,6 +1,6 @@ { "extends": "../../tsconfig.json", - "include": ["*.ts", "../types/*.ts"], + "include": ["*.ts", "../attr.ts", "../bind.ts", "../controller.ts", "../helpers/*.ts", "../types/*.ts"], "exclude": [], "compilerOptions": { "experimentalDecorators": false, diff --git a/test/target.ts b/test/target.ts index 8967040c..4e496cc1 100644 --- a/test/target.ts +++ b/test/target.ts @@ -1,6 +1,6 @@ -import {expect, fixture, html} from '@open-wc/testing' import {target, targets} from '../src/target.js' import {controller} from '../src/controller.js' +import {targetTests} from './helpers/target-tests.js' describe('Targetable', () => { @controller @@ -19,80 +19,5 @@ describe('Targetable', () => { @target shadows!: Element[] } - let instance: HTMLElement - beforeEach(async () => { - instance = await fixture(html` - -
-
-
-
-
-
-
-
-
-
`) - }) - - describe('target', () => { - it('returns the first element where closest tag is the controller', async () => { - expect(instance).to.have.property('foo').exist.with.attribute('id', 'el4') - expect(instance.querySelector('target-test')).to.have.property('foo').exist.with.attribute('id', 'el2') - }) - - it('does not assign to non-target decorated properties', async () => { - expect(instance).to.have.property('bar', 'hello') - }) - - it('returns the first element that has the exact target name', async () => { - expect(instance).to.have.property('baz').exist.with.attribute('id', 'el5') - }) - - it('returns target when there are mutliple target values', async () => { - expect(instance).to.have.property('bing').exist.with.attribute('id', 'el6') - }) - - it('returns targets when there are mutliple target values with different controllers', async () => { - expect(instance).to.have.property('qux').exist.with.attribute('id', 'el8') - }) - - it('returns targets from the shadowRoot, if available', async () => { - instance.attachShadow({mode: 'open'}) - const el = document.createElement('div') - el.setAttribute('data-target', 'target-test.shadow') - instance.shadowRoot!.appendChild(el) - expect(instance).to.have.property('shadow', el) - }) - - it('prioritises shadowRoot targets over others', async () => { - instance.attachShadow({mode: 'open'}) - const shadowEl = document.createElement('div') - shadowEl.setAttribute('data-target', 'target-test.foo') - instance.shadowRoot!.appendChild(shadowEl) - expect(instance).to.have.property('foo', shadowEl) - }) - }) - - describe('targets', () => { - it('returns all elements where closest tag is the controller', async () => { - expect(instance).to.have.property('foos').with.lengthOf(2) - expect(instance).to.have.nested.property('foos[0]').with.attribute('id', 'el4') - expect(instance).to.have.nested.property('foos[1]').with.attribute('id', 'el5') - }) - - it('returns all elements inside a shadow root', async () => { - instance.attachShadow({mode: 'open'}) - const els = [document.createElement('div'), document.createElement('div'), document.createElement('div')] - for (const el of els) el.setAttribute('data-targets', 'target-test.foos') - instance.shadowRoot!.append(...els) - - expect(instance).to.have.property('foos').with.lengthOf(5) - expect(instance).to.have.nested.property('foos[0]', els[0]) - expect(instance).to.have.nested.property('foos[1]', els[1]) - expect(instance).to.have.nested.property('foos[2]', els[2]) - expect(instance).to.have.nested.property('foos[3]').with.attribute('id', 'el4') - expect(instance).to.have.nested.property('foos[4]').with.attribute('id', 'el5') - }) - }) + targetTests() }) diff --git a/web-test-runner-standard.config.js b/web-test-runner-standard.config.js new file mode 100644 index 00000000..e74cf9f2 --- /dev/null +++ b/web-test-runner-standard.config.js @@ -0,0 +1,32 @@ +import ts from 'typescript' +import config from './web-test-runner.config.js' + +// Tests that use Catalyst's decorators with the same syntax in both modes. They run here with standard decorators, +// and in web-test-runner.config.js with legacy decorators. test/standard has tests that need standard-only syntax. +export const sharedFiles = ['test/attr.ts', 'test/bind.ts', 'test/controller.ts'] + +// esbuild only lowers legacy decorators, so compile tests with TypeScript's standard decorators first. Emit ES2020 so +// esbuild has nothing left to lower: its class lowering renames classes, and Catalyst derives tag names from class +// names. +const standardDecorators = { + name: 'standard-decorators', + transform(context) { + if (!context.path.startsWith('/test/') || !context.path.endsWith('.ts')) return + const {outputText} = ts.transpileModule(context.body, { + fileName: context.path, + compilerOptions: { + experimentalDecorators: false, + target: ts.ScriptTarget.ES2020, + useDefineForClassFields: true, + module: ts.ModuleKind.ESNext + } + }) + return {body: outputText} + } +} + +export default { + ...config, + files: [...sharedFiles, 'test/standard/*.ts'], + plugins: [standardDecorators, ...config.plugins] +} diff --git a/web-test-runner.config.js b/web-test-runner.config.js index 85ac5668..a1bbe3d7 100644 --- a/web-test-runner.config.js +++ b/web-test-runner.config.js @@ -1,31 +1,10 @@ import {esbuildPlugin} from '@web/dev-server-esbuild' -import ts from 'typescript' - -// esbuild only lowers legacy decorators, so compile test/standard with TypeScript's standard decorators first. Emit -// ES2020 so esbuild has nothing left to lower: its class lowering renames classes, and Catalyst derives tag names from -// class names. -const standardDecorators = { - name: 'standard-decorators', - transform(context) { - if (!context.path.includes('/test/standard/')) return - const {outputText} = ts.transpileModule(context.body, { - fileName: context.path, - compilerOptions: { - experimentalDecorators: false, - target: ts.ScriptTarget.ES2020, - useDefineForClassFields: true, - module: ts.ModuleKind.ESNext - } - }) - return {body: outputText} - } -} export default { - files: ['test/*.ts', 'test/standard/*.ts'], + files: ['test/*.ts'], nodeResolve: true, concurrency: 1, testsFinishTimeout: 30000, - plugins: [standardDecorators, esbuildPlugin({ts: true, target: 'es2020'})], + plugins: [esbuildPlugin({ts: true, target: 'es2020'})], filterBrowserLogs: log => !log.args.some(arg => typeof arg === 'string' && arg.includes('Lit is in dev mode')) } From ff0350942e6f9d7ee26143142faf4985aba716aa Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:07:46 -0500 Subject: [PATCH 05/26] Support standard decorators in @register, document keeping class names @register threw under standard decorators because it received the context object as the element name. It now defines the element from a class initializer, like @controller. test/register.ts runs in both modes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 4 +++- src/register.ts | 17 ++++++++++++++++- test/standard/tsconfig.json | 2 +- web-test-runner-standard.config.js | 2 +- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index b023e6ca..cf7665cd 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -100,7 +100,9 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. - `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. -Catalyst's member decorators only support public, non-static members. `@controller` registers the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. +Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. + +Catalyst derives the element name from the class name, so keep class names intact through your build. For example, if TypeScript emits standard decorators as ES2022 and esbuild then lowers that output to an older target, esbuild renames the class unless you turn on [`keepNames`](https://esbuild.github.io/api/#keep-names). See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). ### Supporting `strictPropertyInitialization` diff --git a/src/register.ts b/src/register.ts index 6473ec5d..8dff7cc7 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,4 +1,6 @@ import type {CustomElementClass} from './custom-element.js' +import type {ClassContext} from './decorator-context.js' +import {isDecoratorContext} from './decorator-context.js' import {dasherize} from './dasherize.js' /** @@ -7,8 +9,21 @@ import {dasherize} from './dasherize.js' * The classname is converted to a appropriate tag name. * * Example: HelloController => hello-controller + * + * It can be used as a class decorator with both TypeScript's + * `experimentalDecorators` and standard decorators. */ -export function register(classObject: CustomElementClass, name?: string): CustomElementClass { +export function register(classObject: C, context: ClassContext): void +export function register(classObject: CustomElementClass, name?: string): CustomElementClass +export function register(classObject: CustomElementClass, nameOrContext?: unknown): CustomElementClass | void { + if (isDecoratorContext(nameOrContext)) { + // Like `@controller`, define the element once static fields are assigned. + ;(nameOrContext as ClassContext).addInitializer(function (this: CustomElementClass) { + register(this) + }) + return + } + const name = nameOrContext as string | undefined const tagName = name || dasherize(classObject.name).replace(/-element$/, '') try { diff --git a/test/standard/tsconfig.json b/test/standard/tsconfig.json index 0cc9707c..07a99134 100644 --- a/test/standard/tsconfig.json +++ b/test/standard/tsconfig.json @@ -1,6 +1,6 @@ { "extends": "../../tsconfig.json", - "include": ["*.ts", "../attr.ts", "../bind.ts", "../controller.ts", "../helpers/*.ts", "../types/*.ts"], + "include": ["*.ts", "../attr.ts", "../bind.ts", "../controller.ts", "../register.ts", "../helpers/*.ts", "../types/*.ts"], "exclude": [], "compilerOptions": { "experimentalDecorators": false, diff --git a/web-test-runner-standard.config.js b/web-test-runner-standard.config.js index e74cf9f2..1ca6e112 100644 --- a/web-test-runner-standard.config.js +++ b/web-test-runner-standard.config.js @@ -3,7 +3,7 @@ import config from './web-test-runner.config.js' // Tests that use Catalyst's decorators with the same syntax in both modes. They run here with standard decorators, // and in web-test-runner.config.js with legacy decorators. test/standard has tests that need standard-only syntax. -export const sharedFiles = ['test/attr.ts', 'test/bind.ts', 'test/controller.ts'] +export const sharedFiles = ['test/attr.ts', 'test/bind.ts', 'test/controller.ts', 'test/register.ts'] // esbuild only lowers legacy decorators, so compile tests with TypeScript's standard decorators first. Emit ES2020 so // esbuild has nothing left to lower: its class lowering renames classes, and Catalyst derives tag names from class From 2d292f5a0c68c5b35c79879688bc12a389e345a2 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:03:55 -0500 Subject: [PATCH 06/26] Docs: an explicit @controller tag name avoids class renaming Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index cf7665cd..d49d07bb 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -102,7 +102,7 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. -Catalyst derives the element name from the class name, so keep class names intact through your build. For example, if TypeScript emits standard decorators as ES2022 and esbuild then lowers that output to an older target, esbuild renames the class unless you turn on [`keepNames`](https://esbuild.github.io/api/#keep-names). See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). +Without an explicit name, `@controller` derives the element name from the class name, so the class name must survive your build. For example, if TypeScript emits standard decorators as ES2022 and esbuild then lowers that output to an older target, esbuild renames the class unless you turn on [`keepNames`](https://esbuild.github.io/api/#keep-names). Passing the tag name, as in `@controller('hello-world')`, avoids this. See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). ### Supporting `strictPropertyInitialization` From af8b130e9d6313ac1b4732ed056bf3f823ef344a Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:28:47 -0500 Subject: [PATCH 07/26] Register standard base attrs before legacy subclass attrs When a base class uses standard @attr and a subclass records attrs with legacy decorators or direct attr() calls, registerStandardAttrs appended the base attrs after the subclass's, and skipped them entirely when the base was registered after the subclass's meta snapshot was taken. Rebuild the set base-first whenever standard attrs are involved, seeded from the nearest registered ancestor. Pure legacy classes are unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 25 +++++++++++++++++-------- test/standard/attr.ts | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 7c6d5acb..4d869109 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -39,32 +39,41 @@ export function attr(proto: unknown, keyOrContext: unknown): void { else metadata[standardAttrs] = [name] } -const registeredStandardAttrs = new WeakSet() +// Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. +const registeredStandardAttrs = new WeakMap() /** * Registers the `@attr` members recorded in decorator metadata by standard * decorators, so `initializeAttrs` and `defineObservedAttributes` find them. * * Walks up the class chain to include undecorated base classes, stopping at a - * class already registered, whose attrs `meta` copies to subclasses. Reads each - * class's own metadata because a class without a class decorator may get - * metadata that doesn't inherit from its parent's. + * class already registered. Reads each class's own metadata because a class + * without a class decorator may get metadata that doesn't inherit from its + * parent's. */ export function registerStandardAttrs(classObject: CustomElementClass): void { if (registeredStandardAttrs.has(classObject)) return const levels: string[][] = [] + let current: unknown = classObject for ( - let current: unknown = classObject; + ; typeof current === 'function' && !registeredStandardAttrs.has(current); current = Object.getPrototypeOf(current) ) { const metadata = ownMetadata(current) if (metadata && hasOwn(metadata, standardAttrs)) levels.unshift(metadata[standardAttrs] as string[]) } - // Base class attrs first, matching the order legacy decorators register them in. const attrs = meta(classObject.prototype, attrKey) - for (const key of levels.flat()) attrs.add(key) - registeredStandardAttrs.add(classObject) + const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined + const hasStandard = levels.length > 0 || (ancestor !== undefined && registeredStandardAttrs.get(ancestor)!) + if (hasStandard) { + // Base class attrs first, matching the order legacy decorators register them in. `attrs` may hold this class's + // legacy attrs, and a copy of an ancestor's attrs taken before its standard attrs were registered. + const ordered = new Set([...(ancestor ? meta(ancestor.prototype, attrKey) : []), ...levels.flat(), ...attrs]) + attrs.clear() + for (const key of ordered) attrs.add(key) + } + registeredStandardAttrs.set(classObject, hasStandard) } /** diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 899c6a83..8289db53 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -1,6 +1,6 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../../src/controller.js' -import {attr} from '../../src/attr.js' +import {attr, defineObservedAttributes} from '../../src/attr.js' import type {CustomElementClass} from '../../src/custom-element.js' const symbolWithMetadata = Symbol as {metadata?: symbol} @@ -86,6 +86,41 @@ describe('Attr (standard decorators)', () => { }) } + // A base compiled with standard decorators, extended by a class that registers attrs with legacy-style calls. + describe('mixed with legacy attrs', () => { + it('initializes standard base attrs before legacy subclass attrs', async () => { + class MixedOrderBase extends HTMLElement { + @attr base = 'field' + } + class MixedOrderChild extends MixedOrderBase { + get derived() { + return this.base + } + } + attr(MixedOrderChild.prototype, 'derived') + controller(MixedOrderChild) + + expect(observed(MixedOrderChild)).to.deep.equal(['data-base', 'data-derived']) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-derived', 'attribute') + }) + + it('includes standard base attrs registered after a subclass recorded legacy attrs', async () => { + class MixedLateBase extends HTMLElement { + @attr base = '' + } + class MixedLateChild extends MixedLateBase { + child = '' + } + attr(MixedLateChild.prototype, 'child') + defineObservedAttributes(MixedLateBase) + controller(MixedLateChild) + + const instance = await fixture(html``) + expect(instance).to.have.property('base', 'attribute') + }) + }) + it('reads metadata stored under a Symbol.metadata defined after Catalyst loaded', async () => { const original = symbolWithMetadata.metadata symbolWithMetadata.metadata = Symbol('late metadata') From 846043e0deec8eee7aec333c52fac72097215118 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:12:53 -0500 Subject: [PATCH 08/26] Fix standard decorator edge cases found in ship-check - target/targets/register: list the legacy overloads first, so calls with untyped arguments keep their legacy return types. - decorator contexts: type metadata as `object | undefined`, so standard decorators type-check with exactOptionalPropertyTypes. - @attr: find a class's own metadata by Catalyst's attr lists instead of the current Symbol.metadata key, so base classes defined before another library redefined Symbol.metadata keep their attrs. - @attr: initialize fields and accessors before getters and setters in the same class. Standard decorators apply getter and setter decorators first, so a getter could read a field before it was attribute-backed. - @attr: reject setters whose type isn't a string, number or boolean in standard mode, as legacy mode already does. Type checks in test/types now also run with exactOptionalPropertyTypes and without Lit's Symbol.metadata declaration. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 2 +- package.json | 2 +- src/attr.ts | 34 +++++++++++++++++++++++++++------- src/decorator-context.ts | 14 ++------------ src/register.ts | 2 +- src/target.ts | 4 ++-- test/standard/attr.ts | 34 ++++++++++++++++++++++++++++++++++ test/types/decorators.ts | 21 ++++++++++++++++++--- test/types/tsconfig.json | 10 ++++++++++ 9 files changed, 96 insertions(+), 27 deletions(-) create mode 100644 test/types/tsconfig.json diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index d49d07bb..a40c1671 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -98,7 +98,7 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) ``` Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. -- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Within a class, fields and accessors are initialized before getters and setters, so a getter can read another `@attr` value from its HTML attribute. With legacy decorators they're initialized in source order. Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. diff --git a/package.json b/package.json index d785fd4e..c90d84bb 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "build:docs": "cd docs && JEKYLL_ENV=production bundle exec jekyll build", "clean": "tsc --build --clean tsconfig.build.json", "lint": "eslint . --ignore-path .gitignore", - "postlint": "tsc && tsc -p test/standard", + "postlint": "tsc && tsc -p test/standard && tsc -p test/types", "prepack": "npm run build", "presize": "npm run build", "size": "size-limit", diff --git a/src/attr.ts b/src/attr.ts index 4d869109..31baba47 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -2,12 +2,15 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' import {meta} from './core.js' import type {MemberContext} from './decorator-context.js' -import {hasOwn, isDecoratorContext, memberName, ownMetadata} from './decorator-context.js' +import {hasOwn, isDecoratorContext, memberName} from './decorator-context.js' const attrKey = 'attr' type attrValue = string | number | boolean +// Standard decorators apply getter and setter decorators before field decorators, so record them separately and +// register stored values first. A getter may read another attr while it initializes; a stored value can't. const standardAttrs = Symbol.for('catalyst:attr') +const standardComputedAttrs = Symbol.for('catalyst:attr:computed') /** * Attr is a decorator which tags a property as one to be initialized via @@ -21,9 +24,9 @@ const standardAttrs = Symbol.for('catalyst:attr') * getter or setter, and records the name in the class's decorator metadata * for `@controller` to register. */ -export function attr( +export function attr, Value extends attrValue>( value: unknown, - context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> + context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> & {readonly name: K} ): void export function attr(proto: Record, key: K): void export function attr(proto: unknown, keyOrContext: unknown): void { @@ -34,9 +37,26 @@ export function attr(proto: unknown, keyOrContext: unknown): void { const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) const metadata = keyOrContext.metadata as Record | undefined if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') + const key = keyOrContext.kind === 'getter' || keyOrContext.kind === 'setter' ? standardComputedAttrs : standardAttrs // Metadata inherits from the parent class's metadata, so only append to this class's own list. - if (hasOwn(metadata, standardAttrs)) metadata[standardAttrs]!.push(name) - else metadata[standardAttrs] = [name] + if (hasOwn(metadata, key)) metadata[key]!.push(name) + else metadata[key] = [name] +} + +/** + * Returns the `@attr` members recorded in the class's own decorator metadata. Finds the metadata by these lists rather + * than by `Symbol.metadata`, because another library may redefine `Symbol.metadata` after some classes are defined. + */ +function ownStandardAttrs(classObject: object): string[] { + for (const symbol of Object.getOwnPropertySymbols(classObject)) { + const metadata: unknown = Object.getOwnPropertyDescriptor(classObject, symbol)!.value + if (typeof metadata !== 'object' || metadata === null) continue + const attrs = [standardAttrs, standardComputedAttrs].flatMap(key => + hasOwn(metadata, key) ? (metadata as Record)[key]! : [] + ) + if (attrs.length) return attrs + } + return [] } // Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. @@ -60,8 +80,8 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { typeof current === 'function' && !registeredStandardAttrs.has(current); current = Object.getPrototypeOf(current) ) { - const metadata = ownMetadata(current) - if (metadata && hasOwn(metadata, standardAttrs)) levels.unshift(metadata[standardAttrs] as string[]) + const level = ownStandardAttrs(current) + if (level.length) levels.unshift(level) } const attrs = meta(classObject.prototype, attrKey) const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined diff --git a/src/decorator-context.ts b/src/decorator-context.ts index 5b069c2c..478384f0 100644 --- a/src/decorator-context.ts +++ b/src/decorator-context.ts @@ -6,7 +6,7 @@ export interface ClassContext { readonly kind: 'class' readonly name: string | undefined - readonly metadata?: object + readonly metadata?: object | undefined addInitializer(initializer: (this: C) => void): void } @@ -17,7 +17,7 @@ export interface MemberContext void): void } @@ -43,16 +43,6 @@ try { export const hasOwn = (object: object, key: PropertyKey): boolean => Object.prototype.hasOwnProperty.call(object, key) -/** - * Returns the decorator metadata of the class itself, ignoring metadata it inherits from its parent class. - */ -export function ownMetadata(classObject: object): Record | undefined { - // Look the key up on every call, like the SWC and Babel helpers: another library may define `Symbol.metadata` - // after this module loads. - const key = (Symbol as {metadata?: symbol}).metadata ?? Symbol.for('Symbol.metadata') - if (hasOwn(classObject, key)) return (classObject as Record>)[key] -} - // Standard decorators receive a context object as their second argument; legacy decorators receive the member name. export function isDecoratorContext(value: unknown): value is ClassContext | MemberContext { return typeof value === 'object' && value !== null && 'kind' in value && 'addInitializer' in value diff --git a/src/register.ts b/src/register.ts index 8dff7cc7..8386771c 100644 --- a/src/register.ts +++ b/src/register.ts @@ -13,8 +13,8 @@ import {dasherize} from './dasherize.js' * It can be used as a class decorator with both TypeScript's * `experimentalDecorators` and standard decorators. */ -export function register(classObject: C, context: ClassContext): void export function register(classObject: CustomElementClass, name?: string): CustomElementClass +export function register(classObject: C, context: ClassContext): void export function register(classObject: CustomElementClass, nameOrContext?: unknown): CustomElementClass | void { if (isDecoratorContext(nameOrContext)) { // Like `@controller`, define the element once static fields are assigned. diff --git a/src/target.ts b/src/target.ts index 20e19079..a8849144 100644 --- a/src/target.ts +++ b/src/target.ts @@ -13,11 +13,11 @@ import {isDecoratorContext, memberName} from './decorator-context.js' * With standard decorators it must decorate an accessor: * `@target accessor foo!: HTMLElement`. */ +export function target(proto: Record, key: K): void export function target( value: AccessorTarget, context: MemberContext<'accessor', This, Value> ): AccessorResult -export function target(proto: Record, key: K): void export function target(proto: unknown, keyOrContext: unknown): unknown { if (isDecoratorContext(keyOrContext)) return standardTarget('target', keyOrContext, findTarget) const key = keyOrContext as string @@ -40,11 +40,11 @@ export function target(proto: unknown, keyOrContext: unknown): unknown { * With standard decorators it must decorate an accessor: * `@targets accessor foos!: HTMLElement[]`. */ +export function targets(proto: Record, key: K): void export function targets( value: AccessorTarget, context: MemberContext<'accessor', This, Value> ): AccessorResult -export function targets(proto: Record, key: K): void export function targets(proto: unknown, keyOrContext: unknown): unknown { if (isDecoratorContext(keyOrContext)) return standardTarget('targets', keyOrContext, findTargets) const key = keyOrContext as string diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 8289db53..e1f44a34 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -86,6 +86,20 @@ describe('Attr (standard decorators)', () => { }) } + it('initializes stored attrs before getter attrs that read them', async () => { + @controller + class StandardDependentElement extends HTMLElement { + @attr base = 'field' + @attr get derived() { + return `${this.base}-derived` + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-derived', 'attribute-derived') + }) + // A base compiled with standard decorators, extended by a class that registers attrs with legacy-style calls. describe('mixed with legacy attrs', () => { it('initializes standard base attrs before legacy subclass attrs', async () => { @@ -138,6 +152,26 @@ describe('Attr (standard decorators)', () => { } }) + it('reads base class metadata stored before Symbol.metadata changed', async () => { + const original = symbolWithMetadata.metadata + class StandardLateBase extends HTMLElement { + @attr early = 'early' + } + symbolWithMetadata.metadata = Symbol('late metadata') + let instance: HTMLElement + try { + @controller + class StandardLateChildElement extends StandardLateBase { + @attr late = 'late' + } + instance = await fixture(html``) + } finally { + symbolWithMetadata.metadata = original + } + expect(instance.getAttribute('data-early')).to.equal('early') + expect(instance.getAttribute('data-late')).to.equal('late') + }) + it('throws a clear error without decorator metadata', () => { const original = symbolWithMetadata.metadata delete symbolWithMetadata.metadata diff --git a/test/types/decorators.ts b/test/types/decorators.ts index 2da87939..7c230bd4 100644 --- a/test/types/decorators.ts +++ b/test/types/decorators.ts @@ -1,8 +1,11 @@ -// Compile-time checks, run under both decorator modes: `tsc` (experimentalDecorators) and `tsc -p test/standard` -// (standard decorators). Nothing here runs. `@target` and `@targets` need `accessor` in standard mode and a plain -// field in legacy mode, so they're covered by test/target.ts and test/standard/target.ts instead. +// Compile-time checks, run under both decorator modes: `tsc` (experimentalDecorators), and `tsc -p test/standard` and +// `tsc -p test/types` (standard decorators). test/types adds `exactOptionalPropertyTypes` without the `Symbol.metadata` +// declaration Lit adds in test/standard. Nothing here runs. `@target` and `@targets` need `accessor` in standard mode +// and a plain field in legacy mode, so they're covered by test/target.ts and test/standard/target.ts instead. import {controller} from '../../src/controller.js' import {attr} from '../../src/attr.js' +import {register} from '../../src/register.js' +import {target, targets} from '../../src/target.js' import type {CustomElementClass} from '../../src/custom-element.js' @controller @@ -24,6 +27,11 @@ export class TypesElement extends HTMLElement { // @ts-expect-error attrs must be strings, numbers or booleans @attr date = new Date() + + // @ts-expect-error attrs must be strings, numbers or booleans + @attr set untypedSetter(value: unknown) { + this.text = String(value) + } } @controller('types-named-element') @@ -35,3 +43,10 @@ attr(TypesElement.prototype, 'text') // The decorator `controller(name)` returns is still assignable to the legacy class decorator type. export const named: (classObject: CustomElementClass) => void = controller('types-assigned-element') + +// Legacy-style calls with untyped arguments keep their legacy return types. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare const untyped: any +export const targetResult: void = target(untyped, untyped) +export const targetsResult: void = targets(untyped, untyped) +export const registerResult: CustomElementClass = register(untyped, untyped) diff --git a/test/types/tsconfig.json b/test/types/tsconfig.json new file mode 100644 index 00000000..39bdd72a --- /dev/null +++ b/test/types/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.json", + "include": ["*.ts"], + "exclude": [], + "compilerOptions": { + "experimentalDecorators": false, + "exactOptionalPropertyTypes": true, + "target": "ES2022" + } +} From f87a6e986367fe4421e90f60e786728fdb64ed00 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:23:19 -0500 Subject: [PATCH 09/26] Merge legacy and standard attrs per class, base first A standard subclass of an unregistered legacy base put its own attrs before the inherited legacy ones. Walk the chain base to derived and add each class's own legacy attrs, then its standard attrs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 20 ++++++++++++-------- src/core.ts | 7 +++++++ test/standard/attr.ts | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 31baba47..4880ccae 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -1,6 +1,6 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' -import {meta} from './core.js' +import {meta, ownMeta} from './core.js' import type {MemberContext} from './decorator-context.js' import {hasOwn, isDecoratorContext, memberName} from './decorator-context.js' @@ -73,23 +73,27 @@ const registeredStandardAttrs = new WeakMap() */ export function registerStandardAttrs(classObject: CustomElementClass): void { if (registeredStandardAttrs.has(classObject)) return - const levels: string[][] = [] + const levels: CustomElementClass[] = [] let current: unknown = classObject for ( ; typeof current === 'function' && !registeredStandardAttrs.has(current); current = Object.getPrototypeOf(current) ) { - const level = ownStandardAttrs(current) - if (level.length) levels.unshift(level) + levels.unshift(current as CustomElementClass) } const attrs = meta(classObject.prototype, attrKey) const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined - const hasStandard = levels.length > 0 || (ancestor !== undefined && registeredStandardAttrs.get(ancestor)!) + const standard = levels.map(ownStandardAttrs) + const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) if (hasStandard) { - // Base class attrs first, matching the order legacy decorators register them in. `attrs` may hold this class's - // legacy attrs, and a copy of an ancestor's attrs taken before its standard attrs were registered. - const ordered = new Set([...(ancestor ? meta(ancestor.prototype, attrKey) : []), ...levels.flat(), ...attrs]) + // Base class attrs first, matching the order legacy decorators register them in. Read each class's own legacy + // attrs, because a subclass's copy of them can predate standard attrs registered on its ancestors. + const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) + for (const [i, level] of levels.entries()) { + for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) + for (const key of standard[i]!) ordered.add(key) + } attrs.clear() for (const key of ordered) attrs.add(key) } diff --git a/src/core.ts b/src/core.ts index de10ee75..c9f9bc93 100644 --- a/src/core.ts +++ b/src/core.ts @@ -96,3 +96,10 @@ export function meta(proto: Record, name: string): Set()) return map.get(name)! } + +// Like `meta`, but only reads the prototype's own metadata, and doesn't create it. +export function ownMeta(proto: object | undefined, name: string): Set | undefined { + if (proto && Object.prototype.hasOwnProperty.call(proto, symbol)) { + return (proto as Record>>)[symbol].get(name) + } +} diff --git a/test/standard/attr.ts b/test/standard/attr.ts index e1f44a34..31099cc3 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -119,6 +119,24 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute') }) + it('initializes legacy base attrs before standard subclass attrs', async () => { + class MixedLegacyBase extends HTMLElement { + base = 'field' + } + attr(MixedLegacyBase.prototype, 'base') + @controller + class MixedLegacyChildElement extends MixedLegacyBase { + @attr get derived() { + return `${this.base}-derived` + } + } + + const instance = await fixture( + html`` + ) + expect(instance.getAttribute('data-derived')).to.equal('attribute-derived') + }) + it('includes standard base attrs registered after a subclass recorded legacy attrs', async () => { class MixedLateBase extends HTMLElement { @attr base = '' From 483d2fdfe165df95dcfe3a80745731ec36068257 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:03:42 -0500 Subject: [PATCH 10/26] Keep legacy types for ReturnType and Parameters of register and target Listing the legacy overload first fixed calls with untyped arguments, but ReturnType and Parameters read the last overload, which was then the standard one. List the legacy overload both first and last. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/register.ts | 3 +++ src/target.ts | 6 ++++++ test/types/decorators.ts | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/src/register.ts b/src/register.ts index 8386771c..26c044e5 100644 --- a/src/register.ts +++ b/src/register.ts @@ -13,8 +13,11 @@ import {dasherize} from './dasherize.js' * It can be used as a class decorator with both TypeScript's * `experimentalDecorators` and standard decorators. */ +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. export function register(classObject: CustomElementClass, name?: string): CustomElementClass export function register(classObject: C, context: ClassContext): void +export function register(classObject: CustomElementClass, name?: string): CustomElementClass export function register(classObject: CustomElementClass, nameOrContext?: unknown): CustomElementClass | void { if (isDecoratorContext(nameOrContext)) { // Like `@controller`, define the element once static fields are assigned. diff --git a/src/target.ts b/src/target.ts index a8849144..82cb1960 100644 --- a/src/target.ts +++ b/src/target.ts @@ -13,11 +13,14 @@ import {isDecoratorContext, memberName} from './decorator-context.js' * With standard decorators it must decorate an accessor: * `@target accessor foo!: HTMLElement`. */ +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. export function target(proto: Record, key: K): void export function target( value: AccessorTarget, context: MemberContext<'accessor', This, Value> ): AccessorResult +export function target(proto: Record, key: K): void export function target(proto: unknown, keyOrContext: unknown): unknown { if (isDecoratorContext(keyOrContext)) return standardTarget('target', keyOrContext, findTarget) const key = keyOrContext as string @@ -40,11 +43,14 @@ export function target(proto: unknown, keyOrContext: unknown): unknown { * With standard decorators it must decorate an accessor: * `@targets accessor foos!: HTMLElement[]`. */ +// The legacy overload comes first, so calls with untyped arguments resolve to it, and last, so `ReturnType` and +// `Parameters` read it. export function targets(proto: Record, key: K): void export function targets( value: AccessorTarget, context: MemberContext<'accessor', This, Value> ): AccessorResult +export function targets(proto: Record, key: K): void export function targets(proto: unknown, keyOrContext: unknown): unknown { if (isDecoratorContext(keyOrContext)) return standardTarget('targets', keyOrContext, findTargets) const key = keyOrContext as string diff --git a/test/types/decorators.ts b/test/types/decorators.ts index 7c230bd4..19c6963f 100644 --- a/test/types/decorators.ts +++ b/test/types/decorators.ts @@ -50,3 +50,8 @@ declare const untyped: any export const targetResult: void = target(untyped, untyped) export const targetsResult: void = targets(untyped, untyped) export const registerResult: CustomElementClass = register(untyped, untyped) + +// Types read from the last overload, such as `ReturnType`, also keep their legacy types. +export const registerReturn: CustomElementClass = null as unknown as ReturnType +export const targetParameters: [Record, string] = null as unknown as Parameters +export const targetsReturn: void = null as unknown as ReturnType From 7f9f09f265d96ef14002504f47ae60c49cf8ef38 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:03:13 -0500 Subject: [PATCH 11/26] Initialize overriding getter attrs after stored attrs, in both modes - Defer @defineObservedAttributes as a standard class decorator until the class's decorator metadata is attached, so @controller still registers attrs. - Order standard stored attrs before legacy attrs on the same class. - Move getter and setter attrs that override a base attr to the subclass's position, with both standard and legacy decorators. - Raise the lib/index.js size budget to 3.1kb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package.json | 2 +- src/attr.ts | 40 ++++++++++++++++++++++++++++++---------- test/attr.ts | 30 ++++++++++++++++++++++++++++++ test/standard/attr.ts | 14 ++++++++++++++ 4 files changed, 75 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index c90d84bb..55e6640c 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3kb" + "limit": "3.1kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index 4880ccae..8ec6a934 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -1,7 +1,7 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' import {meta, ownMeta} from './core.js' -import type {MemberContext} from './decorator-context.js' +import type {ClassContext, MemberContext} from './decorator-context.js' import {hasOwn, isDecoratorContext, memberName} from './decorator-context.js' const attrKey = 'attr' @@ -29,9 +29,13 @@ export function attr, Value context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> & {readonly name: K} ): void export function attr(proto: Record, key: K): void -export function attr(proto: unknown, keyOrContext: unknown): void { +export function attr(proto: unknown, keyOrContext: unknown, descriptor?: PropertyDescriptor): void { if (!isDecoratorContext(keyOrContext)) { - meta(proto as Record, attrKey).add(keyOrContext as string) + const attrs = meta(proto as Record, attrKey) + // Legacy decorators only pass a descriptor to getters and setters. Like standard ones, an overriding getter moves + // after the attrs its class declares before it, which it may read. + if (descriptor) attrs.delete(keyOrContext as string) + attrs.add(keyOrContext as string) return } const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) @@ -47,16 +51,17 @@ export function attr(proto: unknown, keyOrContext: unknown): void { * Returns the `@attr` members recorded in the class's own decorator metadata. Finds the metadata by these lists rather * than by `Symbol.metadata`, because another library may redefine `Symbol.metadata` after some classes are defined. */ -function ownStandardAttrs(classObject: object): string[] { +function ownStandardAttrs(classObject: object): string[][] { for (const symbol of Object.getOwnPropertySymbols(classObject)) { const metadata: unknown = Object.getOwnPropertyDescriptor(classObject, symbol)!.value if (typeof metadata !== 'object' || metadata === null) continue - const attrs = [standardAttrs, standardComputedAttrs].flatMap(key => + // Stored attrs, then computed attrs. + const lists = [standardAttrs, standardComputedAttrs].map(key => hasOwn(metadata, key) ? (metadata as Record)[key]! : [] ) - if (attrs.length) return attrs + if (lists.flat().length) return lists } - return [] + return [[], []] } // Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. @@ -85,14 +90,20 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { const attrs = meta(classObject.prototype, attrKey) const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined const standard = levels.map(ownStandardAttrs) - const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) + const hasStandard = !!standard.flat(2).length || !!registeredStandardAttrs.get(current as object) if (hasStandard) { // Base class attrs first, matching the order legacy decorators register them in. Read each class's own legacy // attrs, because a subclass's copy of them can predate standard attrs registered on its ancestors. const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) for (const [i, level] of levels.entries()) { + const [stored, computed] = standard[i] as [string[], string[]] + for (const key of stored) ordered.add(key) for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) - for (const key of standard[i]!) ordered.add(key) + // A getter that overrides a base attr may read this class's stored attrs, so move it after them. + for (const key of computed) { + ordered.delete(key) + ordered.add(key) + } } attrs.clear() for (const key of ordered) attrs.add(key) @@ -169,7 +180,16 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) } } -export function defineObservedAttributes(classObject: CustomElementClass): void { +export function defineObservedAttributes( + classObject: CustomElementClass, + context?: ClassContext +): void { + // Standard class decorators run before the class's decorator metadata is attached, so wait for it. + if (isDecoratorContext(context)) { + return context.addInitializer(function (this: CustomElementClass) { + defineObservedAttributes(this) + }) + } registerStandardAttrs(classObject) let observed = classObject.observedAttributes || [] diff --git a/test/attr.ts b/test/attr.ts index 48310d1e..dde16c10 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -232,6 +232,36 @@ describe('Attr', () => { expect(observed(FirstSiblingAttrTest)).to.eql(['data-shared', 'data-first']) expect(observed(SecondSiblingAttrTest)).to.eql(['data-shared', 'data-second']) }) + + it('initializes an overriding getter attr after the attrs it reads', async () => { + class OverrideBase extends HTMLElement { + @attr get label() { + return 'base' + } + } + @controller + class OverrideGetterAttrTest extends OverrideBase { + @attr input = 'field' + @attr get label() { + return `${this.input}-label` + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-label', 'attribute-label') + }) + }) + + it('registers attrs when defineObservedAttributes decorates the class', async () => { + @controller + @defineObservedAttributes + class DecoratedObservedAttrTest extends HTMLElement { + @attr foo = 'bar' + } + expect(observed(DecoratedObservedAttrTest)).to.include('data-foo') + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-foo', 'bar') }) describe('without @controller', () => { diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 31099cc3..a2856ceb 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -119,6 +119,20 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute') }) + it('initializes standard stored attrs before legacy attrs on the same class', async () => { + class MixedSameClass extends HTMLElement { + @attr base = 'field' + get derived() { + return this.base + } + } + attr(MixedSameClass.prototype, 'derived') + controller(MixedSameClass) + + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-derived', 'attribute') + }) + it('initializes legacy base attrs before standard subclass attrs', async () => { class MixedLegacyBase extends HTMLElement { base = 'field' From 23d4eeb68a9f19e41930fc6b0673f9cb4cc97a5a Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:13:45 -0500 Subject: [PATCH 12/26] Document declare for legacy targets with useDefineForClassFields Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index a40c1671..37149ae0 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -104,6 +104,22 @@ Catalyst's member decorators only support public, non-static members. `@controll Without an explicit name, `@controller` derives the element name from the class name, so the class name must survive your build. For example, if TypeScript emits standard decorators as ES2022 and esbuild then lowers that output to an older target, esbuild renames the class unless you turn on [`keepNames`](https://esbuild.github.io/api/#keep-names). Passing the tag name, as in `@controller('hello-world')`, avoids this. See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). +### Legacy decorators and `useDefineForClassFields` + +With legacy decorators, `@target` and `@targets` define a getter on the class prototype. When `useDefineForClassFields` is on, TypeScript defines each declared field on the instance, which hides that getter, so the target is always `undefined`. TypeScript turns `useDefineForClassFields` on by default when `target` is `ES2022` or later. + +Marking the field with `!` or `?`, or typing it as `| undefined`, still emits the field. Use `declare`, which emits nothing: + +```typescript +@controller +class HelloWorldElement extends HTMLElement { + @target declare output: HTMLElement | undefined + @targets declare items: HTMLElement[] +} +``` + +`@target` returns `undefined` when no element matches, so `| undefined` is the accurate type. `@attr` works either way, because Catalyst redefines `@attr` fields on each instance when it connects. Standard decorators avoid the problem by requiring an [accessor](#standard-decorators). + ### Supporting `strictPropertyInitialization` TypeScript comes with various "strict" mode settings, one of which is `strictPropertyInitialization` which lets TypeScript catch potential class properties which might not be assigned during construction of a class. This option conflicts with Catalyst's `@target`/`@targets` decorators, which safely do the assignment but TypeScript's simple heuristics cannot detect this. There are two ways to work around this: @@ -117,7 +133,7 @@ TypeScript comes with various "strict" mode settings, one of which is `strictPro } ``` - Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing. With [standard decorators](#standard-decorators), use the definite initialization operator on an accessor instead: `@target accessor something!: HTMLElement`. + Note that this only works on TypeScript 3.7+, so if you're on an older version, you can also use the [definite initialization operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions) to do the same thing, as long as `useDefineForClassFields` is off ([see above](#legacy-decorators-and-usedefineforclassfields)). With [standard decorators](#standard-decorators), use the definite initialization operator on an accessor instead: `@target accessor something!: HTMLElement`. 2. You can also disable the compiler option (other strict mode rules can still apply) in your `tsconfig.json` like so: From b86c9223d80f6e8e045c91af6f5438c7b8872df5 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:32:53 -0500 Subject: [PATCH 13/26] Order mixed legacy getters after stored attrs and keep legacy types - When standard and legacy attrs are merged, treat legacy attrs with a getter on their class as computed, so they initialize after stored attrs, including when they override a base attr. - Restore the one-argument defineObservedAttributes overload as the last signature, so callbacks and Parameters keep their legacy types. - Drop the redundant registerStandardAttrs call in controller, since defineObservedAttributes registers attrs before the element is defined. - Accept any Symbol.metadata symbol in the metadata test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 2 +- src/attr.ts | 21 ++++++++++++--------- src/controller.ts | 11 ++--------- test/standard/attr.ts | 29 +++++++++++++++++++++++++++++ test/standard/metadata.ts | 2 +- test/types/decorators.ts | 8 +++++++- 6 files changed, 52 insertions(+), 21 deletions(-) diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index 37149ae0..69f6cfb9 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -98,7 +98,7 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) ``` Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. -- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Within a class, fields and accessors are initialized before getters and setters, so a getter can read another `@attr` value from its HTML attribute. With legacy decorators they're initialized in source order. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Within a class, fields and accessors are initialized before getters and setters, so a getter can read another `@attr` value from its HTML attribute. With legacy decorators they're initialized in source order. In both modes, a getter or setter that overrides a base class `@attr` is initialized with its own class's attrs, not the base class's. Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. diff --git a/src/attr.ts b/src/attr.ts index 8ec6a934..f91fc247 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -97,10 +97,13 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) for (const [i, level] of levels.entries()) { const [stored, computed] = standard[i] as [string[], string[]] - for (const key of stored) ordered.add(key) - for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) - // A getter that overrides a base attr may read this class's stored attrs, so move it after them. - for (const key of computed) { + const proto = level.prototype + const legacy = [...(level === classObject ? attrs : ownMeta(proto, attrKey) ?? [])] + // Legacy registrations don't record the member kind, so look for a getter on this class. + const isComputed = (key: string) => !!Object.getOwnPropertyDescriptor(proto, key)?.get + for (const key of stored.concat(legacy.filter(name => !isComputed(name)))) ordered.add(key) + // Getters and setters may read the attrs before them, so they go last, even when they override a base attr. + for (const key of legacy.filter(isComputed).concat(computed)) { ordered.delete(key) ordered.add(key) } @@ -180,13 +183,13 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) } } -export function defineObservedAttributes( - classObject: CustomElementClass, - context?: ClassContext -): void { +// The legacy overload comes last, so `Parameters` reads it and callbacks such as `forEach` still accept the function. +export function defineObservedAttributes(classObject: C, context: ClassContext): void +export function defineObservedAttributes(classObject: CustomElementClass): void +export function defineObservedAttributes(classObject: CustomElementClass, context?: unknown): void { // Standard class decorators run before the class's decorator metadata is attached, so wait for it. if (isDecoratorContext(context)) { - return context.addInitializer(function (this: CustomElementClass) { + return (context as ClassContext).addInitializer(function (this: CustomElementClass) { defineObservedAttributes(this) }) } diff --git a/src/controller.ts b/src/controller.ts index dd719b02..1c4a6205 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -1,5 +1,4 @@ import {CatalystDelegate} from './core.js' -import {registerStandardAttrs} from './attr.js' import type {CustomElementClass} from './custom-element.js' import type {ClassContext} from './decorator-context.js' import {isDecoratorContext} from './decorator-context.js' @@ -37,17 +36,11 @@ export function controller( } function decorate(classObject: CustomElementClass, context: unknown, name?: string) { - if (!isDecoratorContext(context)) return defineController(classObject, name) + if (!isDecoratorContext(context)) return void new CatalystDelegate(classObject, name) // Standard class decorators run before static fields such as `observedAttributes` and `attrPrefix` are assigned. // Class initializers run after them, which is when legacy class decorators run. const classContext = context as ClassContext classContext.addInitializer(function (this: CustomElementClass) { - defineController(this, name) + new CatalystDelegate(this, name) }) } - -function defineController(classObject: CustomElementClass, name?: string) { - // Picks up `@attr` members compiled as standard decorators, including when `controller` is called directly. - registerStandardAttrs(classObject) - new CatalystDelegate(classObject, name) -} diff --git a/test/standard/attr.ts b/test/standard/attr.ts index a2856ceb..625782d8 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -133,6 +133,35 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute') }) + for (const registered of [false, true]) { + it(`initializes an overriding legacy getter after the attrs it reads${ + registered ? ', with a registered base' : '' + }`, async () => { + class Base extends HTMLElement { + @attr get label() { + return 'base' + } + } + class Child extends Base { + input = 'field' + get label() { + return `${this.input}-label` + } + } + if (registered) defineObservedAttributes(Base) + attr(Child.prototype, 'input') + attr(Child.prototype, 'label') + const name = registered ? 'mixed-override-registered' : 'mixed-override' + controller(name)(Child) + + const instance = document.createElement(name) + instance.setAttribute('data-input', 'attribute') + document.body.append(instance) + expect(instance).to.have.attribute('data-label', 'attribute-label') + instance.remove() + }) + } + it('initializes legacy base attrs before standard subclass attrs', async () => { class MixedLegacyBase extends HTMLElement { base = 'field' diff --git a/test/standard/metadata.ts b/test/standard/metadata.ts index f5d0fbea..89a4ec5e 100644 --- a/test/standard/metadata.ts +++ b/test/standard/metadata.ts @@ -9,7 +9,7 @@ function assert(condition: boolean, message: string) { describe('Symbol.metadata (standard decorators)', () => { it('is defined when Catalyst loads, so TypeScript output includes decorator metadata', () => { const metadata = (Symbol as {metadata?: symbol}).metadata - assert(metadata === Symbol.for('Symbol.metadata'), `expected Symbol.metadata, got ${String(metadata)}`) + assert(typeof metadata === 'symbol', `expected Symbol.metadata, got ${String(metadata)}`) }) it('registers attrs from TypeScript output', () => { diff --git a/test/types/decorators.ts b/test/types/decorators.ts index 19c6963f..d1971f25 100644 --- a/test/types/decorators.ts +++ b/test/types/decorators.ts @@ -3,7 +3,7 @@ // declaration Lit adds in test/standard. Nothing here runs. `@target` and `@targets` need `accessor` in standard mode // and a plain field in legacy mode, so they're covered by test/target.ts and test/standard/target.ts instead. import {controller} from '../../src/controller.js' -import {attr} from '../../src/attr.js' +import {attr, defineObservedAttributes} from '../../src/attr.js' import {register} from '../../src/register.js' import {target, targets} from '../../src/target.js' import type {CustomElementClass} from '../../src/custom-element.js' @@ -55,3 +55,9 @@ export const registerResult: CustomElementClass = register(untyped, untyped) export const registerReturn: CustomElementClass = null as unknown as ReturnType export const targetParameters: [Record, string] = null as unknown as Parameters export const targetsReturn: void = null as unknown as ReturnType +export const defineObservedAttributesParameters: [CustomElementClass] = null as unknown as Parameters< + typeof defineObservedAttributes +> +// Callbacks such as `map` pass extra arguments, which the legacy overload accepts. +export const defineObservedAttributesCallback: (classObject: CustomElementClass, index: number) => void = + defineObservedAttributes From 48bfee96fd841e711c9a9056e7e3c5b559a80b32 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:41:12 -0500 Subject: [PATCH 14/26] Initialize attrs with HTML attributes first instead of ordering by kind initializeAttrs now defines attrs that have a matching HTML attribute before the others. A getter attr that reads another attr then sees its attribute value whatever the registration order, and an attr without an attribute returns its default before and after initialization. This replaces the stored/computed split and the override-moving rules, which fixed some orderings by breaking others (an overridden attr read by a base getter, a decorated getter and setter pair). The bundle shrinks back under the original 3 kB budget. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/attrs.md | 1 + docs/_guide/decorators.md | 2 +- package.json | 2 +- src/attr.ts | 52 ++++++++++++++------------------------- test/attr.ts | 21 ++++++++++++++++ test/standard/attr.ts | 19 ++++++++++++++ 6 files changed, 61 insertions(+), 36 deletions(-) diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index 937b133d..b352dc42 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -150,6 +150,7 @@ When an element gets connected to the DOM, the attr is initialized. During this - If the class property has a value, that is the _default_ - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. - When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead. + - Attrs with a matching attribute are initialized first. A getter `@attr` whose default reads another attr gets that attr's attribute value, whatever order they're declared in. {% capture callout %} Remember! The values defined in the class field are the _default_. They won't be set if the element is created and its attribute set to a custom value! diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index 69f6cfb9..ecc7130e 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -98,7 +98,7 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) ``` Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. -- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Within a class, fields and accessors are initialized before getters and setters, so a getter can read another `@attr` value from its HTML attribute. With legacy decorators they're initialized in source order. In both modes, a getter or setter that overrides a base class `@attr` is initialized with its own class's attrs, not the base class's. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. diff --git a/package.json b/package.json index 55e6640c..c90d84bb 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3.1kb" + "limit": "3kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index f91fc247..99304b48 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -7,10 +7,7 @@ import {hasOwn, isDecoratorContext, memberName} from './decorator-context.js' const attrKey = 'attr' type attrValue = string | number | boolean -// Standard decorators apply getter and setter decorators before field decorators, so record them separately and -// register stored values first. A getter may read another attr while it initializes; a stored value can't. const standardAttrs = Symbol.for('catalyst:attr') -const standardComputedAttrs = Symbol.for('catalyst:attr:computed') /** * Attr is a decorator which tags a property as one to be initialized via @@ -29,39 +26,31 @@ export function attr, Value context: MemberContext<'field' | 'accessor' | 'getter' | 'setter', This, Value> & {readonly name: K} ): void export function attr(proto: Record, key: K): void -export function attr(proto: unknown, keyOrContext: unknown, descriptor?: PropertyDescriptor): void { +export function attr(proto: unknown, keyOrContext: unknown): void { if (!isDecoratorContext(keyOrContext)) { - const attrs = meta(proto as Record, attrKey) - // Legacy decorators only pass a descriptor to getters and setters. Like standard ones, an overriding getter moves - // after the attrs its class declares before it, which it may read. - if (descriptor) attrs.delete(keyOrContext as string) - attrs.add(keyOrContext as string) + meta(proto as Record, attrKey).add(keyOrContext as string) return } const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) const metadata = keyOrContext.metadata as Record | undefined if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') - const key = keyOrContext.kind === 'getter' || keyOrContext.kind === 'setter' ? standardComputedAttrs : standardAttrs // Metadata inherits from the parent class's metadata, so only append to this class's own list. - if (hasOwn(metadata, key)) metadata[key]!.push(name) - else metadata[key] = [name] + if (hasOwn(metadata, standardAttrs)) metadata[standardAttrs]!.push(name) + else metadata[standardAttrs] = [name] } /** * Returns the `@attr` members recorded in the class's own decorator metadata. Finds the metadata by these lists rather * than by `Symbol.metadata`, because another library may redefine `Symbol.metadata` after some classes are defined. */ -function ownStandardAttrs(classObject: object): string[][] { +function ownStandardAttrs(classObject: object): string[] { for (const symbol of Object.getOwnPropertySymbols(classObject)) { const metadata: unknown = Object.getOwnPropertyDescriptor(classObject, symbol)!.value - if (typeof metadata !== 'object' || metadata === null) continue - // Stored attrs, then computed attrs. - const lists = [standardAttrs, standardComputedAttrs].map(key => - hasOwn(metadata, key) ? (metadata as Record)[key]! : [] - ) - if (lists.flat().length) return lists + if (typeof metadata === 'object' && metadata !== null && hasOwn(metadata, standardAttrs)) { + return (metadata as Record)[standardAttrs]! + } } - return [[], []] + return [] } // Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. @@ -90,23 +79,14 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { const attrs = meta(classObject.prototype, attrKey) const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined const standard = levels.map(ownStandardAttrs) - const hasStandard = !!standard.flat(2).length || !!registeredStandardAttrs.get(current as object) + const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) if (hasStandard) { // Base class attrs first, matching the order legacy decorators register them in. Read each class's own legacy // attrs, because a subclass's copy of them can predate standard attrs registered on its ancestors. const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) for (const [i, level] of levels.entries()) { - const [stored, computed] = standard[i] as [string[], string[]] - const proto = level.prototype - const legacy = [...(level === classObject ? attrs : ownMeta(proto, attrKey) ?? [])] - // Legacy registrations don't record the member kind, so look for a getter on this class. - const isComputed = (key: string) => !!Object.getOwnPropertyDescriptor(proto, key)?.get - for (const key of stored.concat(legacy.filter(name => !isComputed(name)))) ordered.add(key) - // Getters and setters may read the attrs before them, so they go last, even when they override a base attr. - for (const key of legacy.filter(isComputed).concat(computed)) { - ordered.delete(key) - ordered.add(key) - } + for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) + for (const key of standard[i]!) ordered.add(key) } attrs.clear() for (const key of ordered) attrs.add(key) @@ -143,9 +123,13 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) names = meta(proto, attrKey) } - for (const key of names) { + const attrName = (key: string) => mustDasherize(`${prefix}${key}`) + // Attrs with an HTML attribute go first, so a getter that reads one while another attr initializes gets the attribute + // value. An attr without one returns its default before and after it's initialized, so the order doesn't matter. + const keys = [...names].sort((a, b) => +instance.hasAttribute(attrName(b)) - +instance.hasAttribute(attrName(a))) + for (const key of keys) { const value = (>(instance))[key] - const name = mustDasherize(`${prefix}${key}`) + const name = attrName(key) let descriptor: PropertyDescriptor = { configurable: true, get(this: HTMLElement): string { diff --git a/test/attr.ts b/test/attr.ts index dde16c10..e0b5a96b 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -233,6 +233,27 @@ describe('Attr', () => { expect(observed(SecondSiblingAttrTest)).to.eql(['data-shared', 'data-second']) }) + it('initializes getters that read an overridden attr from its HTML value', async () => { + class ReadOverrideBase extends HTMLElement { + @attr get label() { + return 'base' + } + @attr get derived() { + return `${this.label}-derived` + } + } + @controller + class ReadOverrideAttrTest extends ReadOverrideBase { + @attr get label() { + return 'sub' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-derived', 'attribute-derived') + }) + it('initializes an overriding getter attr after the attrs it reads', async () => { class OverrideBase extends HTMLElement { @attr get label() { diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 625782d8..cf88dbe9 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -100,6 +100,25 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute-derived') }) + it('initializes getters that read a decorated getter and setter pair from its HTML value', async () => { + @controller + class StandardPairElement extends HTMLElement { + #name = 'field' + @attr get name() { + return this.#name + } + @attr get greeting() { + return `hi ${this.name}` + } + // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures + @attr set name(value: string) { + this.#name = value + } + } + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-greeting', 'hi attribute') + }) + // A base compiled with standard decorators, extended by a class that registers attrs with legacy-style calls. describe('mixed with legacy attrs', () => { it('initializes standard base attrs before legacy subclass attrs', async () => { From 8bf25cba5d717091c758dc33d63cce5a6d58db02 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:55:26 -0500 Subject: [PATCH 15/26] Cache attribute names and partition attrs instead of sorting The attribute-first sort dasherized each name several times per element and made rendering 10,000 attr elements about 18% slower than main. Partition attrs by whether they have an HTML attribute, dasherizing each once, and cache the dasherized names across elements. Rendering 10,000 elements with innerHTML (median of 7 interleaved runs): legacy 37.1 ms (main 37.7 ms), standard 37.8 ms (41.1 ms before). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 99304b48..a903ac60 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -94,6 +94,11 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { registeredStandardAttrs.set(classObject, hasStandard) } +// Every element dasherizes the same few names, so cache them. +const attrNames = new Map() +const attrName = (prefixed: string): string => + attrNames.get(prefixed) ?? attrNames.set(prefixed, mustDasherize(prefixed)).get(prefixed)! + /** * initializeAttrs is called with a set of class property names (if omitted, it * will look for any properties tagged with the `@attr` decorator). With this @@ -123,13 +128,16 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) names = meta(proto, attrKey) } - const attrName = (key: string) => mustDasherize(`${prefix}${key}`) // Attrs with an HTML attribute go first, so a getter that reads one while another attr initializes gets the attribute // value. An attr without one returns its default before and after it's initialized, so the order doesn't matter. - const keys = [...names].sort((a, b) => +instance.hasAttribute(attrName(b)) - +instance.hasAttribute(attrName(a))) - for (const key of keys) { + const present: Array<[string, string]> = [] + const absent: Array<[string, string]> = [] + for (const key of names) { + const name = attrName(`${prefix}${key}`) + ;(instance.hasAttribute(name) ? present : absent).push([key, name]) + } + for (const [key, name] of present.concat(absent)) { const value = (>(instance))[key] - const name = attrName(key) let descriptor: PropertyDescriptor = { configurable: true, get(this: HTMLElement): string { @@ -181,7 +189,7 @@ export function defineObservedAttributes(classObject: CustomElementClass, contex let observed = classObject.observedAttributes || [] const prefix = classObject.attrPrefix ?? 'data-' - const attrToAttributeName = (name: string) => mustDasherize(`${prefix}${name}`) + const attrToAttributeName = (name: string) => attrName(`${prefix}${name}`) Object.defineProperty(classObject, 'observedAttributes', { configurable: true, From ad207986e1f3c17f6f8f94641064ea5ed93ddd97 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:03:46 -0500 Subject: [PATCH 16/26] Initialize field attrs first, in registration order Field attrs read nothing, so initialize them first in registration order, as legacy decorators always have. Getter, setter and accessor attrs follow, those with an HTML attribute first. This keeps legacy attributeChangedCallback ordering for fields, and lets a getter's default read fields that have HTML attributes or no initial value. Fields are detected as own instance properties, or names with no accessor on the prototype chain. Raises the lib/index.js size budget to 3.1kb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/attrs.md | 2 +- package.json | 2 +- src/attr.ts | 11 +++++++---- test/attr.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index b352dc42..634a139e 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -150,7 +150,7 @@ When an element gets connected to the DOM, the attr is initialized. During this - If the class property has a value, that is the _default_ - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. - When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead. - - Attrs with a matching attribute are initialized first. A getter `@attr` whose default reads another attr gets that attr's attribute value, whatever order they're declared in. + - Field attrs are initialized first, in the order they're declared. Getter, setter and `accessor` attrs come next, starting with those that have a matching attribute, so a getter's default can read the other attrs' values. {% capture callout %} Remember! The values defined in the class field are the _default_. They won't be set if the element is created and its attribute set to a custom value! diff --git a/package.json b/package.json index c90d84bb..55e6640c 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3kb" + "limit": "3.1kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index a903ac60..0650d4bd 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -128,15 +128,18 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) names = meta(proto, attrKey) } - // Attrs with an HTML attribute go first, so a getter that reads one while another attr initializes gets the attribute - // value. An attr without one returns its default before and after it's initialized, so the order doesn't matter. + // A getter attr may read other attrs, so it should see them initialized. Fields read nothing, so they go first, in + // registration order. They're own properties by now, or have no accessor at all. Getters, setters and accessors follow, + // those with an HTML attribute first; one without returns its default before and after it's initialized. + const fields: Array<[string, string]> = [] const present: Array<[string, string]> = [] const absent: Array<[string, string]> = [] for (const key of names) { const name = attrName(`${prefix}${key}`) - ;(instance.hasAttribute(name) ? present : absent).push([key, name]) + const list = hasOwn(instance, key) || !(key in instance) ? fields : instance.hasAttribute(name) ? present : absent + list.push([key, name]) } - for (const [key, name] of present.concat(absent)) { + for (const [key, name] of fields.concat(present, absent)) { const value = (>(instance))[key] let descriptor: PropertyDescriptor = { configurable: true, diff --git a/test/attr.ts b/test/attr.ts index e0b5a96b..3a1c86f5 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -181,6 +181,49 @@ describe('Attr', () => { }) }) + describe('initialization order', () => { + it('initializes field attrs in declaration order, so their callbacks keep HTML values', async () => { + @controller + class CallbackOrderAttrTest extends HTMLElement { + @attr ready = true + @attr status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-ready') this.status = 'updated' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-status', 'html') + }) + + it('initializes field attrs before getter attrs that read them, when both have HTML attributes', async () => { + @controller + class ParseOrderAttrTest extends HTMLElement { + @attr get count() { + return JSON.parse(this.payload).length + } + @attr payload = '' + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.property('count', 7) + }) + + it('initializes fields without a value before getter attrs that read them', async () => { + @controller + class UnsetOrderAttrTest extends HTMLElement { + @attr get greeting() { + return this.name.toUpperCase() + } + @attr name!: string + } + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-greeting', '') + }) + }) + describe('inheritance', () => { it('registers attrs from undecorated base classes, base class first', async () => { class Base extends HTMLElement { From af9c1b8d0cff0c62a9bacbd98efab10411f5eddb Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:19:56 -0500 Subject: [PATCH 17/26] Return nothing from @defineObservedAttributes and test native class fields - defineObservedAttributes returned addInitializer's result as a class decorator. esbuild's addInitializer returns a number, and esbuild throws when a class decorator returns anything but a function. Return nothing. - The standard test run now compiles tests and source with TypeScript to native ES2022 class fields with define semantics, the output of a modern TypeScript build, instead of lowering to ES2020 and passing through esbuild. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 3 ++- test/standard/attr.ts | 16 ++++++++++++++++ web-test-runner-standard.config.js | 15 +++++++++------ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 0650d4bd..fe40979c 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -184,9 +184,10 @@ export function defineObservedAttributes(classObject: CustomElementClass): void export function defineObservedAttributes(classObject: CustomElementClass, context?: unknown): void { // Standard class decorators run before the class's decorator metadata is attached, so wait for it. if (isDecoratorContext(context)) { - return (context as ClassContext).addInitializer(function (this: CustomElementClass) { + ;(context as ClassContext).addInitializer(function (this: CustomElementClass) { defineObservedAttributes(this) }) + return } registerStandardAttrs(classObject) let observed = classObject.observedAttributes || [] diff --git a/test/standard/attr.ts b/test/standard/attr.ts index cf88dbe9..24bc19f6 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -2,6 +2,8 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../../src/controller.js' import {attr, defineObservedAttributes} from '../../src/attr.js' import type {CustomElementClass} from '../../src/custom-element.js' +import type {ClassContext} from '../../src/decorator-context.js' +import {register} from '../../src/register.js' const symbolWithMetadata = Symbol as {metadata?: symbol} const observed = (classObject: CustomElementClass) => classObject.observedAttributes @@ -119,6 +121,20 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-greeting', 'hi attribute') }) + // esbuild's `addInitializer` returns a value, and it throws if a class decorator returns anything but a function. + it('returns nothing from class decorators, whatever addInitializer returns', () => { + class ReturnCheckElement extends HTMLElement {} + const context: ClassContext = { + kind: 'class', + name: 'ReturnCheckElement', + addInitializer: () => 1 + } + expect(defineObservedAttributes(ReturnCheckElement, context)).to.equal(undefined) + expect(controller(ReturnCheckElement, context)).to.equal(undefined) + expect(controller('return-check')(ReturnCheckElement, context)).to.equal(undefined) + expect(register(ReturnCheckElement, context)).to.equal(undefined) + }) + // A base compiled with standard decorators, extended by a class that registers attrs with legacy-style calls. describe('mixed with legacy attrs', () => { it('initializes standard base attrs before legacy subclass attrs', async () => { diff --git a/web-test-runner-standard.config.js b/web-test-runner-standard.config.js index 1ca6e112..cc641977 100644 --- a/web-test-runner-standard.config.js +++ b/web-test-runner-standard.config.js @@ -5,18 +5,21 @@ import config from './web-test-runner.config.js' // and in web-test-runner.config.js with legacy decorators. test/standard has tests that need standard-only syntax. export const sharedFiles = ['test/attr.ts', 'test/bind.ts', 'test/controller.ts', 'test/register.ts'] -// esbuild only lowers legacy decorators, so compile tests with TypeScript's standard decorators first. Emit ES2020 so -// esbuild has nothing left to lower: its class lowering renames classes, and Catalyst derives tag names from class -// names. +// Compile tests and source the way a modern TypeScript build does: standard decorators and native ES2022 class fields +// with define semantics. This replaces the esbuild plugin, which only lowers legacy decorators, and whose class lowering +// renames classes, which Catalyst derives tag names from. const standardDecorators = { name: 'standard-decorators', + resolveMimeType(context) { + if (context.path.endsWith('.ts')) return 'js' + }, transform(context) { - if (!context.path.startsWith('/test/') || !context.path.endsWith('.ts')) return + if (!/^\/(src|test)\/.*\.ts$/.test(context.path)) return const {outputText} = ts.transpileModule(context.body, { fileName: context.path, compilerOptions: { experimentalDecorators: false, - target: ts.ScriptTarget.ES2020, + target: ts.ScriptTarget.ES2022, useDefineForClassFields: true, module: ts.ModuleKind.ESNext } @@ -28,5 +31,5 @@ const standardDecorators = { export default { ...config, files: [...sharedFiles, 'test/standard/*.ts'], - plugins: [standardDecorators, ...config.plugins] + plugins: [standardDecorators] } From abdca2ee3a1861ece27fd99969e6201c5a6a8165 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:35:14 -0500 Subject: [PATCH 18/26] Initialize fields before checking getter attr presence; ignore built-in accessors - Fields named like built-in accessors, such as an uninitialized `title` in legacy assignment mode, stay in the field group, so their reflection and callbacks keep declaration order. Only accessors on classes extending HTMLElement count. - Check HTML attribute presence for getter, setter and accessor attrs after fields initialize, because field callbacks may add attributes. - Skip the accessor pass when a class has none. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 88 +++++++++++++++++++++++++++++----------------------- test/attr.ts | 37 ++++++++++++++++++++++ 2 files changed, 87 insertions(+), 38 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index fe40979c..62906aaf 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -128,53 +128,65 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) names = meta(proto, attrKey) } + const nameOf = (key: string) => attrName(`${prefix}${key}`) + // Only classes extending HTMLElement declare attr accessors. An attr named like a built-in one, such as `title`, is a field. + const isAccessor = (key: string) => { + for (let o = proto; o && o !== HTMLElement.prototype; o = Object.getPrototypeOf(o)) { + const descriptor = Object.getOwnPropertyDescriptor(o, key) + if (descriptor) return !('value' in descriptor) + } + return false + } // A getter attr may read other attrs, so it should see them initialized. Fields read nothing, so they go first, in - // registration order. They're own properties by now, or have no accessor at all. Getters, setters and accessors follow, - // those with an HTML attribute first; one without returns its default before and after it's initialized. - const fields: Array<[string, string]> = [] - const present: Array<[string, string]> = [] - const absent: Array<[string, string]> = [] - for (const key of names) { - const name = attrName(`${prefix}${key}`) - const list = hasOwn(instance, key) || !(key in instance) ? fields : instance.hasAttribute(name) ? present : absent - list.push([key, name]) + // registration order. They're own properties by now, or have no accessor at all. + const fields: string[] = [] + const accessors: string[] = [] + for (const key of names) (!hasOwn(instance, key) && isAccessor(key) ? accessors : fields).push(key) + for (const key of fields) initializeAttr(instance, key, nameOf(key)) + // Getters, setters and accessors follow, those with an HTML attribute first, checked now because field callbacks may + // add attributes. One without an HTML attribute returns its default before and after it's initialized. + if (!accessors.length) return + const has = (key: string) => instance.hasAttribute(nameOf(key)) + for (const key of accessors.filter(has).concat(accessors.filter(other => !has(other)))) { + initializeAttr(instance, key, nameOf(key)) } - for (const [key, name] of fields.concat(present, absent)) { - const value = (>(instance))[key] - let descriptor: PropertyDescriptor = { +} + +function initializeAttr(instance: HTMLElement, key: string, name: string) { + const value = (>(instance))[key] + let descriptor: PropertyDescriptor = { + configurable: true, + get(this: HTMLElement): string { + return this.getAttribute(name) || '' + }, + set(this: HTMLElement, newValue: string) { + this.setAttribute(name, newValue || '') + } + } + if (typeof value === 'number') { + descriptor = { configurable: true, - get(this: HTMLElement): string { - return this.getAttribute(name) || '' + get(this: HTMLElement): number { + return Number(this.getAttribute(name) || 0) }, set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue || '') + this.setAttribute(name, newValue) } } - if (typeof value === 'number') { - descriptor = { - configurable: true, - get(this: HTMLElement): number { - return Number(this.getAttribute(name) || 0) - }, - set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue) - } - } - } else if (typeof value === 'boolean') { - descriptor = { - configurable: true, - get(this: HTMLElement): boolean { - return this.hasAttribute(name) - }, - set(this: HTMLElement, newValue: boolean) { - this.toggleAttribute(name, newValue) - } + } else if (typeof value === 'boolean') { + descriptor = { + configurable: true, + get(this: HTMLElement): boolean { + return this.hasAttribute(name) + }, + set(this: HTMLElement, newValue: boolean) { + this.toggleAttribute(name, newValue) } } - Object.defineProperty(instance, key, descriptor) - if (key in instance && !instance.hasAttribute(name)) { - descriptor.set!.call(instance, value) - } + } + Object.defineProperty(instance, key, descriptor) + if (key in instance && !instance.hasAttribute(name)) { + descriptor.set!.call(instance, value) } } diff --git a/test/attr.ts b/test/attr.ts index 3a1c86f5..74adc29f 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -211,6 +211,43 @@ describe('Attr', () => { expect(instance).to.have.property('count', 7) }) + it('initializes fields named like built-in accessors in declaration order', async () => { + @controller + class BuiltinNameAttrTest extends HTMLElement { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore With define semantics TypeScript wants an initializer (TS2612). This tests a field without one. + @attr title!: string + @attr status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-title') this.status = 'updated' + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.attribute('data-status', 'html') + }) + + it('orders getter attrs by the HTML attributes present after fields initialize', async () => { + @controller + class LatePresenceAttrTest extends HTMLElement { + @attr trigger = true + @attr get payload() { + return '' + } + @attr get count() { + return JSON.parse(this.payload).length + } + attributeChangedCallback(name: string) { + if (name === 'data-trigger') this.setAttribute('data-payload', '[1,2]') + } + } + const instance = await fixture( + html`` + ) + expect(instance).to.have.property('count', 7) + }) + it('initializes fields without a value before getter attrs that read them', async () => { @controller class UnsetOrderAttrTest extends HTMLElement { From 92ed9d54500a8d1c7c5e8d3cb332206db1139b16 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:30:25 -0500 Subject: [PATCH 19/26] Register a class's standard attrs before its legacy attrs Standard decorators record attrs when the class is defined, and legacy attr() calls on that class can only follow, so merge them in that order. Otherwise a standard field's attributeChangedCallback could run after a later legacy field initialized, and overwrite its HTML value. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 7 ++++--- test/standard/attr.ts | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 62906aaf..f13eea56 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -81,12 +81,13 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { const standard = levels.map(ownStandardAttrs) const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) if (hasStandard) { - // Base class attrs first, matching the order legacy decorators register them in. Read each class's own legacy - // attrs, because a subclass's copy of them can predate standard attrs registered on its ancestors. + // Base class attrs first, matching the order legacy decorators register them in. Within a class, standard attrs + // come first, because they're recorded when the class is defined and legacy `attr()` calls can only follow. Read + // each class's own legacy attrs, because a subclass's copy of them can predate standard attrs on its ancestors. const ordered = new Set(ancestor ? meta(ancestor.prototype, attrKey) : []) for (const [i, level] of levels.entries()) { - for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) for (const key of standard[i]!) ordered.add(key) + for (const key of level === classObject ? attrs : ownMeta(level.prototype, attrKey) ?? []) ordered.add(key) } attrs.clear() for (const key of ordered) attrs.add(key) diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 24bc19f6..e76065f0 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -197,6 +197,21 @@ describe('Attr (standard decorators)', () => { }) } + it('initializes standard fields before legacy fields registered later on the same class', async () => { + class MixedCallbackOrder extends HTMLElement { + @attr ready = true + status = 'default' + attributeChangedCallback(name: string) { + if (name === 'data-ready') this.status = 'updated' + } + } + attr(MixedCallbackOrder.prototype, 'status') + controller(MixedCallbackOrder) + + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-status', 'html') + }) + it('initializes legacy base attrs before standard subclass attrs', async () => { class MixedLegacyBase extends HTMLElement { base = 'field' From 5a52b0bff9cca63e8f8ea7c5c539f2bc8717aa6c Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:43:44 -0500 Subject: [PATCH 20/26] Initialize @attr accessors with fields, in registration order An `@attr accessor` stores its value like a field, and replaces a legacy `@attr declare` field when code moves to standard decorators. Grouping it with getters initialized attrs that have HTML attributes first, which changed what connectedCallback sees when setting a missing attr's attribute runs it early. Tag auto-accessor getters so they initialize with fields, as the legacy fields they replace did. Raises the lib/index.js size budget to 3.2kb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package.json | 2 +- src/attr.ts | 7 ++++++- test/standard/attr.ts | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 55e6640c..ea0bbf36 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3.1kb" + "limit": "3.2kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index f13eea56..690b592b 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -9,6 +9,9 @@ type attrValue = string | number | boolean const standardAttrs = Symbol.for('catalyst:attr') +// Getters of `@attr accessor` members. Auto-accessors store a value like fields, so they initialize with fields. +const storedAccessorGetters = new WeakSet() + /** * Attr is a decorator which tags a property as one to be initialized via * `initializeAttrs`. @@ -32,6 +35,7 @@ export function attr(proto: unknown, keyOrContext: unknown): void { return } const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) + if (keyOrContext.kind === 'accessor') storedAccessorGetters.add((proto as {get: object}).get) const metadata = keyOrContext.metadata as Record | undefined if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') // Metadata inherits from the parent class's metadata, so only append to this class's own list. @@ -131,10 +135,11 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) } const nameOf = (key: string) => attrName(`${prefix}${key}`) // Only classes extending HTMLElement declare attr accessors. An attr named like a built-in one, such as `title`, is a field. + // So is an `@attr accessor`, which stores its value. const isAccessor = (key: string) => { for (let o = proto; o && o !== HTMLElement.prototype; o = Object.getPrototypeOf(o)) { const descriptor = Object.getOwnPropertyDescriptor(o, key) - if (descriptor) return !('value' in descriptor) + if (descriptor) return !('value' in descriptor || storedAccessorGetters.has(descriptor.get!)) } return false } diff --git a/test/standard/attr.ts b/test/standard/attr.ts index e76065f0..e14ed60c 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -102,6 +102,39 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute-derived') }) + // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. + it('initializes accessor attrs in registration order, like fields', async () => { + const seen: Record = {field: [], accessor: []} + @controller + class FieldOrderElement extends HTMLElement { + @attr first = '' + @attr second = '' + connectedCallback() { + seen.field!.push(this.second) + } + } + @controller + class AccessorOrderElement extends HTMLElement { + @attr accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.accessor!.push(this.second) + } + } + expect(FieldOrderElement).to.exist + expect(AccessorOrderElement).to.exist + const container = await fixture(html`
`) + // Elements from an inert document upgrade when inserted, with their attributes already set, as innerHTML does. + const inert = document.implementation.createHTMLDocument() + for (const tag of ['field-order', 'accessor-order']) { + const element = inert.createElement(tag) + element.setAttribute('data-second', 'html') + container.append(document.adoptNode(element)) + } + expect(seen.field).to.have.length(1) + expect(seen.accessor).to.eql(seen.field) + }) + it('initializes getters that read a decorated getter and setter pair from its HTML value', async () => { @controller class StandardPairElement extends HTMLElement { From bf5c10c0e3d6d2bb91c2128e0bff4173aa2381e3 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:48:51 -0500 Subject: [PATCH 21/26] Document that standard decorators register accessor attrs first Standard decorators apply accessor decorators before field decorators, so a class mixing `@attr` fields and accessors registers, and initializes, its accessors first. Document the order, recommend fields to keep declaration order as legacy decorators do, and test the order. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/attrs.md | 3 ++- docs/_guide/decorators.md | 2 +- test/standard/attr.ts | 10 ++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index 634a139e..e52a080b 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -150,7 +150,8 @@ When an element gets connected to the DOM, the attr is initialized. During this - If the class property has a value, that is the _default_ - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. - When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead. - - Field attrs are initialized first, in the order they're declared. Getter, setter and `accessor` attrs come next, starting with those that have a matching attribute, so a getter's default can read the other attrs' values. + - Field and `accessor` attrs are initialized first, in the order they're registered. Getter and setter attrs come next, starting with those that have a matching attribute, so a getter's default can read the other attrs' values. + - Standard decorators register `accessor` attrs before field attrs, whatever order they're declared in. To initialize attrs in declaration order, as legacy decorators do, decorate fields, not accessors: `@attr name!: string`. {% capture callout %} Remember! The values defined in the class field are the _default_. They won't be set if the element is created and its attribute set to a custom value! diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index ecc7130e..8ac9bcab 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -98,7 +98,7 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) ``` Assigning to the accessor throws a `TypeError`, just as assigning to the getter-only legacy property does. -- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. +- `@attr` records its fields in [decorator metadata](https://github.com/tc39/proposal-decorator-metadata), so with TypeScript you need version 5.2 or later. `@attr` can decorate a field, an `accessor`, a getter or a setter. Prefer a field, such as `@attr name!: string` in place of a legacy `@attr declare name: string`: standard decorators register accessors before fields, so mixing them changes the order attrs initialize in (see [attrs]({{ site.baseurl }}/guide/attrs#default-values)). Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. diff --git a/test/standard/attr.ts b/test/standard/attr.ts index e14ed60c..0fd5d6f4 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -103,6 +103,16 @@ describe('Attr (standard decorators)', () => { }) // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. + // Standard decorators apply accessor decorators before field decorators, so accessors register first. + it('registers accessor attrs before field attrs declared above them', () => { + @controller + class StandardRegistrationOrderElement extends HTMLElement { + @attr first = '' + @attr accessor second = '' + } + expect(observed(StandardRegistrationOrderElement)).to.eql(['data-second', 'data-first']) + }) + it('initializes accessor attrs in registration order, like fields', async () => { const seen: Record = {field: [], accessor: []} @controller From 196af1528905e154c6117a956c14ecc68b8da926 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:17:53 -0500 Subject: [PATCH 22/26] Classify attrs by recorded kind, and stop at built-in element prototypes initializeAttrs guessed whether an attr computes its value by finding an accessor on the prototype chain. That misclassified two cases: - An `@attr accessor` wrapped by another accessor decorator. Its getter was replaced, so it initialized after getter attrs that read it. - An attr named like an accessor of a built-in base element, such as `value` on an HTMLInputElement subclass. The walk only stopped at HTMLElement.prototype, so the attr moved after the others, changing callback order from v1.8.1. Standard decorators now record whether an attr is a getter or setter in the class's decorator metadata, unless a subclass redefines it. Legacy attrs keep the prototype walk, which now stops at the first native prototype. Raises the lib/index.js size budget to 3.3kb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package.json | 2 +- src/attr.ts | 53 +++++++++++++++++++++++++++++++------------ test/attr.ts | 31 +++++++++++++++++++++++++ test/standard/attr.ts | 50 ++++++++++++++++++++++++++++++++++++---- 4 files changed, 116 insertions(+), 20 deletions(-) diff --git a/package.json b/package.json index ea0bbf36..42fe4dc4 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3.2kb" + "limit": "3.3kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index 690b592b..fa754462 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -8,9 +8,8 @@ const attrKey = 'attr' type attrValue = string | number | boolean const standardAttrs = Symbol.for('catalyst:attr') - -// Getters of `@attr accessor` members. Auto-accessors store a value like fields, so they initialize with fields. -const storedAccessorGetters = new WeakSet() +// Names of standard `@attr` getters and setters, which compute their value rather than store it. +const standardComputedAttrs = Symbol.for('catalyst:attr:computed') /** * Attr is a decorator which tags a property as one to be initialized via @@ -35,30 +34,36 @@ export function attr(proto: unknown, keyOrContext: unknown): void { return } const name = memberName('attr', keyOrContext, ['field', 'accessor', 'getter', 'setter']) - if (keyOrContext.kind === 'accessor') storedAccessorGetters.add((proto as {get: object}).get) const metadata = keyOrContext.metadata as Record | undefined if (!metadata) throw new TypeError('@attr requires decorator metadata (`Symbol.metadata`) support') - // Metadata inherits from the parent class's metadata, so only append to this class's own list. - if (hasOwn(metadata, standardAttrs)) metadata[standardAttrs]!.push(name) - else metadata[standardAttrs] = [name] + // Metadata inherits from the parent class's metadata, so only append to this class's own lists. The kind is recorded + // now, because another decorator may replace the member's getter. + const record = (list: symbol) => { + if (hasOwn(metadata, list)) metadata[list]!.push(name) + else metadata[list] = [name] + } + record(standardAttrs) + if (keyOrContext.kind === 'getter' || keyOrContext.kind === 'setter') record(standardComputedAttrs) } /** * Returns the `@attr` members recorded in the class's own decorator metadata. Finds the metadata by these lists rather * than by `Symbol.metadata`, because another library may redefine `Symbol.metadata` after some classes are defined. */ -function ownStandardAttrs(classObject: object): string[] { +function ownStandardAttrs(classObject: object): Record { for (const symbol of Object.getOwnPropertySymbols(classObject)) { const metadata: unknown = Object.getOwnPropertyDescriptor(classObject, symbol)!.value if (typeof metadata === 'object' && metadata !== null && hasOwn(metadata, standardAttrs)) { - return (metadata as Record)[standardAttrs]! + return metadata as Record } } - return [] + return {} } // Classes whose attrs are registered, mapped to whether any of them came from standard decorator metadata. const registeredStandardAttrs = new WeakMap() +// Standard attrs of a registered class, including inherited ones, mapped to whether they're getters or setters. +const standardAttrKinds = new WeakMap>() /** * Registers the `@attr` members recorded in decorator metadata by standard @@ -82,8 +87,19 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { } const attrs = meta(classObject.prototype, attrKey) const ancestor = registeredStandardAttrs.has(current as object) ? (current as CustomElementClass) : undefined - const standard = levels.map(ownStandardAttrs) + const kinds = new Map(standardAttrKinds.get(current as object)) + const standard = levels.map(level => { + const metadata = ownStandardAttrs(level) + const own = metadata[standardAttrs] ?? [] + const computed = metadata[standardComputedAttrs] ?? [] + // A subclass that redefines an inherited standard attr without decorating it, such as a legacy getter, decides + // its kind from its own definition. + for (const key of kinds.keys()) if (hasOwn(level.prototype, key) && !own.includes(key)) kinds.delete(key) + for (const key of own) kinds.set(key, computed.includes(key)) + return own + }) const hasStandard = standard.some(level => level.length) || !!registeredStandardAttrs.get(current as object) + standardAttrKinds.set(classObject, kinds) if (hasStandard) { // Base class attrs first, matching the order legacy decorators register them in. Within a class, standard attrs // come first, because they're recorded when the class is defined and legacy `attr()` calls can only follow. Read @@ -124,6 +140,7 @@ const attrName = (prefixed: string): string => * `@controller` decorator it should not call this manually. */ const initialized = new WeakSet() +const nativeCode = /\{\s*\[native code\]\s*\}$/ export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { if (initialized.has(instance)) return initialized.add(instance) @@ -134,12 +151,18 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) names = meta(proto, attrKey) } const nameOf = (key: string) => attrName(`${prefix}${key}`) - // Only classes extending HTMLElement declare attr accessors. An attr named like a built-in one, such as `title`, is a field. - // So is an `@attr accessor`, which stores its value. + const kinds = standardAttrKinds.get(proto?.constructor) + // Standard decorators record whether an attr is a getter or setter. For legacy ones, look for an accessor on the + // classes above the built-in element they extend. An attr named like a built-in accessor, such as `title`, is a field. const isAccessor = (key: string) => { - for (let o = proto; o && o !== HTMLElement.prototype; o = Object.getPrototypeOf(o)) { + if (kinds?.has(key)) return kinds.get(key) + for ( + let o = proto; + o && !nativeCode.test(Function.prototype.toString.call(o.constructor)); + o = Object.getPrototypeOf(o) + ) { const descriptor = Object.getOwnPropertyDescriptor(o, key) - if (descriptor) return !('value' in descriptor || storedAccessorGetters.has(descriptor.get!)) + if (descriptor) return !('value' in descriptor) } return false } diff --git a/test/attr.ts b/test/attr.ts index 74adc29f..7d69d50b 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -387,5 +387,36 @@ describe('Attr', () => { const instance = await fixture(html``) expect(instance).to.have.attribute('data-foo', 'baz') }) + + // Customized built-ins inherit accessors such as `value` from interfaces like HTMLInputElement. An attr declared + // without a value has no own property, and the inherited accessor must not make it initialize like a getter attr. + it('initializes attrs named like accessors of a built-in base element in registration order', function (this: Mocha.Context) { + const changes: unknown[] = [] + class BuiltinAttrInput extends HTMLInputElement { + declare value: string + status = 'idle' + connectedCallback() { + initializeAttrs(this) + } + attributeChangedCallback(name: string) { + changes.push([name, this.status]) + } + } + attr(BuiltinAttrInput.prototype as unknown as Record<'value', string>, 'value') + attr(BuiltinAttrInput.prototype as unknown as Record<'status', string>, 'status') + defineObservedAttributes(BuiltinAttrInput) + customElements.define('builtin-attr-input', BuiltinAttrInput, {extends: 'input'}) + const element = document.createElement('input', {is: 'builtin-attr-input'}) + // Safari doesn't support customized built-in elements. + if (!(element instanceof BuiltinAttrInput)) this.skip() + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + // `value` registers first, so it initializes and reflects before `status` reads its HTML value. + expect(changes).to.eql([ + ['data-status', 'idle'], + ['data-value', 'idle'] + ]) + }) }) }) diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 0fd5d6f4..90512668 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -102,7 +102,6 @@ describe('Attr (standard decorators)', () => { expect(instance).to.have.attribute('data-derived', 'attribute-derived') }) - // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. // Standard decorators apply accessor decorators before field decorators, so accessors register first. it('registers accessor attrs before field attrs declared above them', () => { @controller @@ -113,8 +112,17 @@ describe('Attr (standard decorators)', () => { expect(observed(StandardRegistrationOrderElement)).to.eql(['data-second', 'data-first']) }) - it('initializes accessor attrs in registration order, like fields', async () => { - const seen: Record = {field: [], accessor: []} + // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. + it('initializes accessor attrs in registration order, like fields, even when another decorator wraps them', async () => { + const seen: Record = {field: [], accessor: [], wrapped: []} + const wrap = (value: ClassAccessorDecoratorTarget) => ({ + get(this: This) { + return value.get.call(this) + }, + set(this: This, newValue: Value) { + value.set.call(this, newValue) + } + }) @controller class FieldOrderElement extends HTMLElement { @attr first = '' @@ -131,18 +139,28 @@ describe('Attr (standard decorators)', () => { seen.accessor!.push(this.second) } } + @controller + class WrappedOrderElement extends HTMLElement { + @wrap @attr accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.wrapped!.push(this.second) + } + } expect(FieldOrderElement).to.exist expect(AccessorOrderElement).to.exist + expect(WrappedOrderElement).to.exist const container = await fixture(html`
`) // Elements from an inert document upgrade when inserted, with their attributes already set, as innerHTML does. const inert = document.implementation.createHTMLDocument() - for (const tag of ['field-order', 'accessor-order']) { + for (const tag of ['field-order', 'accessor-order', 'wrapped-order']) { const element = inert.createElement(tag) element.setAttribute('data-second', 'html') container.append(document.adoptNode(element)) } expect(seen.field).to.have.length(1) expect(seen.accessor).to.eql(seen.field) + expect(seen.wrapped).to.eql(seen.field) }) it('initializes getters that read a decorated getter and setter pair from its HTML value', async () => { @@ -240,6 +258,30 @@ describe('Attr (standard decorators)', () => { }) } + it('initializes a legacy getter overriding a standard accessor attr after the attrs it reads', async () => { + class Base extends HTMLElement { + @attr accessor label = 'base' + } + class Child extends Base { + input = 'field' + override get label() { + return `${this.input}-label` + } + override set label(value: string) { + super.label = value + } + } + attr(Child.prototype, 'input') + attr(Child.prototype, 'label') + controller('mixed-accessor-override')(Child) + + const instance = document.createElement('mixed-accessor-override') + instance.setAttribute('data-input', 'attribute') + document.body.append(instance) + expect(instance).to.have.attribute('data-label', 'attribute-label') + instance.remove() + }) + it('initializes standard fields before legacy fields registered later on the same class', async () => { class MixedCallbackOrder extends HTMLElement { @attr ready = true From 0c45f0458f4d281ecda506b331a3b8e3a5a7c354 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:09:15 -0500 Subject: [PATCH 23/26] Fix attr classification edge cases and check class decorator targets From a ship-check of 196af15: - initializeAttrs with explicit names now registers standard attrs first, so it knows an `@attr accessor` stores its value. - A class's list of standard getter and setter attrs is read only from its own metadata. Metadata inherits from the parent class's, so a subclass overriding an `@attr` getter with an accessor was treated as a getter. - Whether a prototype belongs to a built-in class is cached per prototype. Reading the class source for every element made legacy getter attrs slower as the class grew. - `@controller`, `@register` and `@defineObservedAttributes` throw a TypeError when they decorate anything but a class, as `@attr` and `@target` do for unsupported members. Raises the lib/index.js size budget to 3.4kb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- package.json | 2 +- src/attr.ts | 24 ++++++++-------- src/controller.ts | 3 +- src/decorator-context.ts | 4 +++ src/register.ts | 3 +- test/standard/attr.ts | 60 +++++++++++++++++++++++++++++++++++++--- 6 files changed, 78 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 42fe4dc4..ff1712df 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ { "path": "lib/index.js", "import": "{controller, attr, target, targets}", - "limit": "3.3kb" + "limit": "3.4kb" }, { "path": "lib/abilities.js", diff --git a/src/attr.ts b/src/attr.ts index fa754462..53bc3f94 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -2,7 +2,7 @@ import type {CustomElementClass} from './custom-element.js' import {mustDasherize} from './dasherize.js' import {meta, ownMeta} from './core.js' import type {ClassContext, MemberContext} from './decorator-context.js' -import {hasOwn, isDecoratorContext, memberName} from './decorator-context.js' +import {assertClass, hasOwn, isDecoratorContext, memberName} from './decorator-context.js' const attrKey = 'attr' type attrValue = string | number | boolean @@ -91,7 +91,8 @@ export function registerStandardAttrs(classObject: CustomElementClass): void { const standard = levels.map(level => { const metadata = ownStandardAttrs(level) const own = metadata[standardAttrs] ?? [] - const computed = metadata[standardComputedAttrs] ?? [] + // Metadata inherits from the parent class's, so ignore a computed list this class doesn't own. + const computed = (hasOwn(metadata, standardComputedAttrs) && metadata[standardComputedAttrs]) || [] // A subclass that redefines an inherited standard attr without decorating it, such as a legacy getter, decides // its kind from its own definition. for (const key of kinds.keys()) if (hasOwn(level.prototype, key) && !own.includes(key)) kinds.delete(key) @@ -141,26 +142,26 @@ const attrName = (prefixed: string): string => */ const initialized = new WeakSet() const nativeCode = /\{\s*\[native code\]\s*\}$/ +// Prototypes mapped to whether they belong to a built-in class. Reading a class's source is slow, so do it once. +const nativePrototypes = new WeakMap() +const isNative = (proto: object): boolean => + nativePrototypes.get(proto) ?? + nativePrototypes.set(proto, nativeCode.test(Function.prototype.toString.call(proto.constructor))).get(proto)! export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { if (initialized.has(instance)) return initialized.add(instance) const proto = Object.getPrototypeOf(instance) const prefix = proto?.constructor?.attrPrefix ?? 'data-' - if (!names) { - if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) - names = meta(proto, attrKey) - } + // Registering also records the kinds of standard attrs, which explicitly named attrs need too. + if (typeof proto?.constructor === 'function') registerStandardAttrs(proto.constructor) + if (!names) names = meta(proto, attrKey) const nameOf = (key: string) => attrName(`${prefix}${key}`) const kinds = standardAttrKinds.get(proto?.constructor) // Standard decorators record whether an attr is a getter or setter. For legacy ones, look for an accessor on the // classes above the built-in element they extend. An attr named like a built-in accessor, such as `title`, is a field. const isAccessor = (key: string) => { if (kinds?.has(key)) return kinds.get(key) - for ( - let o = proto; - o && !nativeCode.test(Function.prototype.toString.call(o.constructor)); - o = Object.getPrototypeOf(o) - ) { + for (let o = proto; o && !isNative(o); o = Object.getPrototypeOf(o)) { const descriptor = Object.getOwnPropertyDescriptor(o, key) if (descriptor) return !('value' in descriptor) } @@ -225,6 +226,7 @@ export function defineObservedAttributes(classObject: CustomElementClass): void export function defineObservedAttributes(classObject: CustomElementClass, context?: unknown): void { // Standard class decorators run before the class's decorator metadata is attached, so wait for it. if (isDecoratorContext(context)) { + assertClass('defineObservedAttributes', context) ;(context as ClassContext).addInitializer(function (this: CustomElementClass) { defineObservedAttributes(this) }) diff --git a/src/controller.ts b/src/controller.ts index 1c4a6205..57927cb5 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -1,7 +1,7 @@ import {CatalystDelegate} from './core.js' import type {CustomElementClass} from './custom-element.js' import type {ClassContext} from './decorator-context.js' -import {isDecoratorContext} from './decorator-context.js' +import {assertClass, isDecoratorContext} from './decorator-context.js' /** * The decorator returned by `controller(name)`. It accepts both TypeScript's @@ -37,6 +37,7 @@ export function controller( function decorate(classObject: CustomElementClass, context: unknown, name?: string) { if (!isDecoratorContext(context)) return void new CatalystDelegate(classObject, name) + assertClass('controller', context) // Standard class decorators run before static fields such as `observedAttributes` and `attrPrefix` are assigned. // Class initializers run after them, which is when legacy class decorators run. const classContext = context as ClassContext diff --git a/src/decorator-context.ts b/src/decorator-context.ts index 478384f0..d0d8b71d 100644 --- a/src/decorator-context.ts +++ b/src/decorator-context.ts @@ -48,6 +48,10 @@ export function isDecoratorContext(value: unknown): value is ClassContext | Memb return typeof value === 'object' && value !== null && 'kind' in value && 'addInitializer' in value } +export function assertClass(decorator: string, context: ClassContext | MemberContext): void { + if (context.kind !== 'class') throw new TypeError(`@${decorator} must decorate a class`) +} + export function memberName(decorator: string, context: ClassContext | MemberContext, kinds: string[]): string { // `kinds` never includes 'class', so class contexts fail the first check. const member = context as MemberContext diff --git a/src/register.ts b/src/register.ts index 26c044e5..9c49adda 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,6 +1,6 @@ import type {CustomElementClass} from './custom-element.js' import type {ClassContext} from './decorator-context.js' -import {isDecoratorContext} from './decorator-context.js' +import {assertClass, isDecoratorContext} from './decorator-context.js' import {dasherize} from './dasherize.js' /** @@ -20,6 +20,7 @@ export function register(classObject: C, context: export function register(classObject: CustomElementClass, name?: string): CustomElementClass export function register(classObject: CustomElementClass, nameOrContext?: unknown): CustomElementClass | void { if (isDecoratorContext(nameOrContext)) { + assertClass('register', nameOrContext) // Like `@controller`, define the element once static fields are assigned. ;(nameOrContext as ClassContext).addInitializer(function (this: CustomElementClass) { register(this) diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 90512668..e4f4fcc0 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -1,6 +1,6 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../../src/controller.js' -import {attr, defineObservedAttributes} from '../../src/attr.js' +import {attr, defineObservedAttributes, initializeAttrs} from '../../src/attr.js' import type {CustomElementClass} from '../../src/custom-element.js' import type {ClassContext} from '../../src/decorator-context.js' import {register} from '../../src/register.js' @@ -113,8 +113,8 @@ describe('Attr (standard decorators)', () => { }) // Setting a missing attr's attribute can run connectedCallback before the rest initialize, so the order is observable. - it('initializes accessor attrs in registration order, like fields, even when another decorator wraps them', async () => { - const seen: Record = {field: [], accessor: [], wrapped: []} + it('initializes accessor attrs in registration order, like fields, even when wrapped or overriding a getter', async () => { + const seen: Record = {field: [], accessor: [], wrapped: [], override: []} const wrap = (value: ClassAccessorDecoratorTarget) => ({ get(this: This) { return value.get.call(this) @@ -147,13 +147,27 @@ describe('Attr (standard decorators)', () => { seen.wrapped!.push(this.second) } } + class GetterBase extends HTMLElement { + @attr get first() { + return '' + } + } + @controller + class OverrideOrderElement extends GetterBase { + @attr override accessor first = '' + @attr accessor second = '' + connectedCallback() { + seen.override!.push(this.second) + } + } expect(FieldOrderElement).to.exist expect(AccessorOrderElement).to.exist expect(WrappedOrderElement).to.exist + expect(OverrideOrderElement).to.exist const container = await fixture(html`
`) // Elements from an inert document upgrade when inserted, with their attributes already set, as innerHTML does. const inert = document.implementation.createHTMLDocument() - for (const tag of ['field-order', 'accessor-order', 'wrapped-order']) { + for (const tag of ['field-order', 'accessor-order', 'wrapped-order', 'override-order']) { const element = inert.createElement(tag) element.setAttribute('data-second', 'html') container.append(document.adoptNode(element)) @@ -161,6 +175,28 @@ describe('Attr (standard decorators)', () => { expect(seen.field).to.have.length(1) expect(seen.accessor).to.eql(seen.field) expect(seen.wrapped).to.eql(seen.field) + expect(seen.override).to.eql(seen.field) + }) + + it('initializes explicitly named accessor attrs in the order given, like fields', () => { + class ExplicitNamesElement extends HTMLElement { + static observedAttributes = ['data-ready'] + @attr accessor ready = true + @attr accessor status = 'default' + connectedCallback() { + initializeAttrs(this, ['ready', 'status']) + } + attributeChangedCallback() { + this.status = 'updated' + } + } + customElements.define('explicit-names-element', ExplicitNamesElement) + const element = document.createElement('explicit-names-element') as ExplicitNamesElement + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + // `ready` initializes first, so its callback runs before `status` reads its HTML value. + expect(element.status).to.equal('html') }) it('initializes getters that read a decorated getter and setter pair from its HTML value', async () => { @@ -409,4 +445,20 @@ describe('Attr (standard decorators)', () => { } ).to.throw(TypeError, message) }) + + it('throws when a class decorator decorates a member', () => { + for (const [decorator, name] of [ + [controller, 'controller'], + [register, 'register'], + [defineObservedAttributes, 'defineObservedAttributes'] + ] as const) { + expect( + () => + class extends HTMLElement { + // @ts-expect-error class decorators can't decorate methods + @decorator foo() {} + } + ).to.throw(TypeError, `@${name} must decorate a class`) + } + }) }) From bbb9318e7716f3317bd7e7d2050354e07b9aa798 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:50:02 -0500 Subject: [PATCH 24/26] Document that esbuild renames classes in standard decorator output TypeScript's standard decorator output declares the class twice under one name, and esbuild renames one of them in any transform or bundle, not only when lowering. Without a tag name, `@controller` then defines `hello-world-element2` silently. `keepNames` only prevents this from esbuild 0.18.2. Recommend passing a tag name with standard decorators. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/decorators.md | 4 +++- docs/_guide/you-will-need.md | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/_guide/decorators.md b/docs/_guide/decorators.md index 8ac9bcab..56c085e9 100644 --- a/docs/_guide/decorators.md +++ b/docs/_guide/decorators.md @@ -102,7 +102,9 @@ TypeScript 5.0+ and SWC (`decoratorVersion: "2023-11"`) compile standard (TC39) Catalyst's member decorators only support public, non-static members. `@controller` (and `@register`) define the element once static fields such as `observedAttributes` and `attrPrefix` are assigned, the same as with legacy decorators. -Without an explicit name, `@controller` derives the element name from the class name, so the class name must survive your build. For example, if TypeScript emits standard decorators as ES2022 and esbuild then lowers that output to an older target, esbuild renames the class unless you turn on [`keepNames`](https://esbuild.github.io/api/#keep-names). Passing the tag name, as in `@controller('hello-world')`, avoids this. See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). +Without an explicit name, `@controller` derives the element name from the class name, so the class name must survive your build. With standard decorators, TypeScript's output declares the class twice under the same name, and esbuild renames one of them in any transform or bundle, even at the same target. `HelloWorldElement` then becomes `HelloWorldElement2`, and the element is defined as `hello-world-element2` without an error. esbuild's [`keepNames`](https://esbuild.github.io/api/#keep-names) keeps the name from version 0.18.2. Before that, `@controller` sees an empty or internal name, such as `_this`, and defining the element throws. Minifiers rename classes too. + +Passing the tag name, as in `@controller('hello-world')`, avoids all of this, and we recommend it with standard decorators. See [build considerations]({{ site.baseurl }}/guide/you-will-need#build-considerations). ### Legacy decorators and `useDefineForClassFields` diff --git a/docs/_guide/you-will-need.md b/docs/_guide/you-will-need.md index 3fe986cc..0f3ca29c 100644 --- a/docs/_guide/you-will-need.md +++ b/docs/_guide/you-will-need.md @@ -32,6 +32,8 @@ The preferred way to handle this is to disable renaming class names in your buil When using ESBuild you can turn off all class and function name minification with the [`keep_names`](https://esbuild.github.io/api/#keep-names) option. Setting this to `true` in your build will opt-out all classes and all functions from minification. +With [standard decorators]({{ site.baseurl }}/guide/decorators#standard-decorators), esbuild renames classes in TypeScript's output even without minification, and `keep_names` only prevents it from esbuild 0.18.2. Passing a tag name to `@controller` works with every build tool. + ```ts { keep_names: true } From 739e30d69df3f34e658e968607e094c3a0ff0709 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:04:46 -0500 Subject: [PATCH 25/26] Keep registration order for legacy attrs with a setter Without standard decorator metadata, an auto-accessor and a getter and setter pair look the same on the prototype. Treating both as getter attrs reordered undecorated accessors registered by `attr()` calls or explicit `initializeAttrs` names, unlike v1.8.1. Only a getter without a setter now counts as a getter attr; anything with a setter keeps registration order. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_guide/attrs.md | 1 + src/attr.ts | 8 +++++--- test/standard/attr.ts | 34 +++++++++++++++++++++++++++++++--- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/_guide/attrs.md b/docs/_guide/attrs.md index e52a080b..e17d2e2a 100644 --- a/docs/_guide/attrs.md +++ b/docs/_guide/attrs.md @@ -151,6 +151,7 @@ When an element gets connected to the DOM, the attr is initialized. During this - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. - When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead. - Field and `accessor` attrs are initialized first, in the order they're registered. Getter and setter attrs come next, starting with those that have a matching attribute, so a getter's default can read the other attrs' values. + - With legacy decorators, Catalyst can't tell an `accessor` from a getter and setter you wrote, so only a getter without a setter counts as a getter attr. Any attr with a setter initializes in registration order, as in earlier versions. - Standard decorators register `accessor` attrs before field attrs, whatever order they're declared in. To initialize attrs in declaration order, as legacy decorators do, decorate fields, not accessors: `@attr name!: string`. {% capture callout %} diff --git a/src/attr.ts b/src/attr.ts index 53bc3f94..7e65bb61 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -157,13 +157,15 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) if (!names) names = meta(proto, attrKey) const nameOf = (key: string) => attrName(`${prefix}${key}`) const kinds = standardAttrKinds.get(proto?.constructor) - // Standard decorators record whether an attr is a getter or setter. For legacy ones, look for an accessor on the - // classes above the built-in element they extend. An attr named like a built-in accessor, such as `title`, is a field. + // Standard decorators record whether an attr is a getter or setter. For others, look for a getter without a setter + // on the classes above the built-in element they extend. One with a setter, such as an auto-accessor or a getter and + // setter pair, stores a value as far as Catalyst can tell, so it keeps registration order, as in v1.8.1. An attr + // named like a built-in accessor, such as `title`, is a field. const isAccessor = (key: string) => { if (kinds?.has(key)) return kinds.get(key) for (let o = proto; o && !isNative(o); o = Object.getPrototypeOf(o)) { const descriptor = Object.getOwnPropertyDescriptor(o, key) - if (descriptor) return !('value' in descriptor) + if (descriptor) return !!descriptor.get && !descriptor.set } return false } diff --git a/test/standard/attr.ts b/test/standard/attr.ts index e4f4fcc0..2a8466a8 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -178,6 +178,36 @@ describe('Attr (standard decorators)', () => { expect(seen.override).to.eql(seen.field) }) + // Undecorated auto-accessors have no metadata recording that they store a value, but they have a setter, which + // computed getter attrs don't, so they initialize in registration order as in v1.8.1. + for (const registration of ['attr calls', 'explicit names'] as const) { + it(`initializes undecorated accessors registered by ${registration} in registration order`, () => { + class UndecoratedAccessorElement extends HTMLElement { + static observedAttributes = ['data-ready'] + accessor ready = true + accessor status = 'default' + connectedCallback() { + if (registration === 'explicit names') initializeAttrs(this, ['ready', 'status']) + else initializeAttrs(this) + } + attributeChangedCallback() { + this.status = 'updated' + } + } + if (registration === 'attr calls') { + attr(UndecoratedAccessorElement.prototype, 'ready') + attr(UndecoratedAccessorElement.prototype, 'status') + } + const tag = `undecorated-accessor-${registration.replace(' ', '-')}` + customElements.define(tag, UndecoratedAccessorElement) + const element = document.createElement(tag) as UndecoratedAccessorElement + element.setAttribute('data-status', 'html') + document.body.append(element) + element.remove() + expect(element.status).to.equal('html') + }) + } + it('initializes explicitly named accessor attrs in the order given, like fields', () => { class ExplicitNamesElement extends HTMLElement { static observedAttributes = ['data-ready'] @@ -300,12 +330,10 @@ describe('Attr (standard decorators)', () => { } class Child extends Base { input = 'field' + // A getter without a setter computes its value, so it initializes after the attrs it reads. override get label() { return `${this.input}-label` } - override set label(value: string) { - super.label = value - } } attr(Child.prototype, 'input') attr(Child.prototype, 'label') From 746788afbef479ec852aaf55d33d5567b714f925 Mon Sep 17 00:00:00 2001 From: Matthew Costabile <8616962+mattcosta7@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:28:45 -0500 Subject: [PATCH 26/26] Handle frozen parent metadata and an attr named constructor - `@attr` defines a class's own list of attrs in its decorator metadata instead of assigning it. Metadata inherits from the parent class's, and assigning fails when the parent's metadata is frozen. - The built-in prototype check only reads `constructor` when it's a function, so an attr named `constructor` initializes as in v1.8.1. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/attr.ts | 10 ++++++++-- test/attr.ts | 14 ++++++++++++++ test/standard/attr.ts | 16 ++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 7e65bb61..ddfff5ba 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -40,7 +40,8 @@ export function attr(proto: unknown, keyOrContext: unknown): void { // now, because another decorator may replace the member's getter. const record = (list: symbol) => { if (hasOwn(metadata, list)) metadata[list]!.push(name) - else metadata[list] = [name] + // Define the list rather than assign it, which fails if the parent class's metadata is frozen. + else Object.defineProperty(metadata, list, {value: [name], enumerable: true}) } record(standardAttrs) if (keyOrContext.kind === 'getter' || keyOrContext.kind === 'setter') record(standardComputedAttrs) @@ -146,7 +147,12 @@ const nativeCode = /\{\s*\[native code\]\s*\}$/ const nativePrototypes = new WeakMap() const isNative = (proto: object): boolean => nativePrototypes.get(proto) ?? - nativePrototypes.set(proto, nativeCode.test(Function.prototype.toString.call(proto.constructor))).get(proto)! + nativePrototypes + .set( + proto, + typeof proto.constructor === 'function' && nativeCode.test(Function.prototype.toString.call(proto.constructor)) + ) + .get(proto)! export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { if (initialized.has(instance)) return initialized.add(instance) diff --git a/test/attr.ts b/test/attr.ts index 7d69d50b..2a480797 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -388,6 +388,20 @@ describe('Attr', () => { expect(instance).to.have.attribute('data-foo', 'baz') }) + it('initializes an attr named constructor', () => { + class ConstructorAttrTest extends HTMLElement { + connectedCallback() { + initializeAttrs(this, ['constructor']) + } + } + Object.defineProperty(ConstructorAttrTest.prototype, 'constructor', {configurable: true, get: () => 'default'}) + customElements.define('constructor-attr-test', ConstructorAttrTest) + const instance = document.createElement('constructor-attr-test') + document.body.append(instance) + instance.remove() + expect(instance).to.have.attribute('data-constructor', 'default') + }) + // Customized built-ins inherit accessors such as `value` from interfaces like HTMLInputElement. An attr declared // without a value has no own property, and the inherited accessor must not make it initialize like a getter attr. it('initializes attrs named like accessors of a built-in base element in registration order', function (this: Mocha.Context) { diff --git a/test/standard/attr.ts b/test/standard/attr.ts index 2a8466a8..af0258e2 100644 --- a/test/standard/attr.ts +++ b/test/standard/attr.ts @@ -432,6 +432,22 @@ describe('Attr (standard decorators)', () => { expect(instance.getAttribute('data-late')).to.equal('late') }) + it('records subclass attrs when the base class metadata is frozen', async () => { + const freeze = (_: unknown, context: ClassDecoratorContext) => void Object.freeze(context.metadata) + @freeze + class FrozenMetadataBase extends HTMLElement { + @attr base = 'base' + } + @controller + class FrozenMetadataChildElement extends FrozenMetadataBase { + @attr child = 'child' + } + expect(observed(FrozenMetadataChildElement)).to.eql(['data-base', 'data-child']) + const instance = await fixture(html``) + expect(instance).to.have.attribute('data-base', 'base') + expect(instance).to.have.attribute('data-child', 'child') + }) + it('throws a clear error without decorator metadata', () => { const original = symbolWithMetadata.metadata delete symbolWithMetadata.metadata