Skip to content

feat: extend createDecorator with typed method support - #63

Draft
WhiteKiwi wants to merge 11 commits into
mainfrom
feat/typed-method-decorators-42
Draft

WhiteKiwi wants to merge 11 commits into
mainfrom
feat/typed-method-decorators-42

Conversation

@WhiteKiwi

@WhiteKiwi WhiteKiwi commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Overview

Closes #42.

Extend the existing createDecorator with opt-in method type support. There is no separate createTypedDecorator API.

  • Existing createDecorator(key, metadata?) calls keep returning the unrestricted MethodDecorator
  • createDecorator<F>(key, metadata?) returns TypedMethodDecorator<F> for a shared method contract
  • Generic factories can connect their options to F and infer the original arguments / awaited return type directly at @Retry(...)

Implementation

The original runtime function body is unchanged. The overload order is unrestricted / typed / unrestricted: the first preserves ordinary calls, and the last preserves existing ReturnType<typeof createDecorator>-annotated factories. Arbitrary metadata, including functions and unions, remains supported.

The former separate helper/export and its method-only runtime guard were removed. Type arguments are erased, so the unified API preserves existing accessor behavior. The typed overload describes method contracts; TypeScript cannot distinguish a function-valued getter from a method, so that misuse cannot be automatically rejected.

The English and Korean typed-decorator guides include a generic Retry-options example and a generic aspect wrap<F> pattern. The example's retryify is an explicitly declared user-provided signature-preserving helper, not a retry implementation added by this PR. A shared aspect instance does not automatically acquire one concrete method's type from its metadata key.

Type checks and limitations

  • Positive/negative fixtures cover arguments, returns, async methods, overloads, generics, explicit this, and this: void
  • New inference fixtures use IsAny guards and expected compiler errors to verify concrete callback tuple/result types without hiding gaps behind assertions
  • Precreated decorators lack the target's contextual type; explicitly typed precreation is tested as a workaround
  • Returning plain MethodDecorator erases the inference link; returning TypedMethodDecorator<F> preserves it
  • Preserve F whole for overloaded/generic signatures; Parameters<F> / ReturnType<F> expose the last overload or unknown for generic identity. An overload callback is not a sound view of all calls
  • These are TypeScript structural compatibility checks, not full wrapper substitutability or exact equality. Method bivariance, any, and assertions retain their usual limitations. A shared contract must cover every input the public method accepts
  • Legacy experimentalDecorators only; this does not introduce standard-decorator support

Type-check configuration and package contents

Type fixtures use the root tsconfig.json; tsconfig.type-tests.json is removed. test:types runs tsc -p tsconfig.json --noEmit over production sources and type-tests. Runtime tests remain with Jest. tsconfig.build.json inherits the shared compiler options and exclusions, overriding only include with src to keep its production-only input and existing dist layout.

The npm package preserves production src and dist files, including source/declaration-map targets, while excluding src/__test__. The root type-tests directory is outside the package allowlist. CI runs test:package after the build to create an actual archive and reject test/fixture entries.

Documentation

  • Reworked both READMEs into 130-line landing pages (previously 332 lines) with the existing Toss artwork, three focused badges, short navigation, install requirements, and one complete logging example.
  • Moved detailed usage into docs/en/usage.md / docs/ko/usage.md, covering metadata, dependency injection, accessors, inheritance, and testing.
  • Moved the full typed-method examples and limitations into docs/en/typed-decorators.md / docs/ko/typed-decorators.md. All previously documented inference and soundness caveats remain.
  • Organized guides under docs/en/ and docs/ko/ with matching filenames. Root README.md remains the English entry point; renamed readme_kr.md to README.ko.md and updated every repository reference. The legacy docs/migration-guide-v2.md URL is unchanged.
  • Use language identifiers for translations, following the root README pattern used by Nano ID and language-folder documentation used by VitePress. Only existing English and Korean content is included.
  • Clarified in both READMEs and typed-decorator guides that strict is recommended for more thorough method checking, not required to use the library. Legacy experimentalDecorators remains required.
  • The README rename adds README.ko.md to npm's automatic README inclusion: 49 packaged files instead of 48, with both language READMEs. Production src and dist contents are unchanged. External main-branch links to the old readme_kr.md path will need updating; no redirect or duplicate file is provided.
  • Kept the current NestJS 8–12 / NestJS 12 Node requirements, legacy decorator configuration, and existing v2 migration guide. This documentation change is independent of feat!: prepare ESM-only v3 and drop NestJS 8/9 support #65's proposed ESM/v3 migration.
  • Guides remain repository-only. Published README links use maintained main-branch URLs; the four new guide URLs and renamed Korean README URL become available on main when this PR merges. Relative navigation within the guides was checked on the PR commit.
  • Reviewed the current Hono, Zod, Zustand, ofetch, and p-limit READMEs for a clear first example, restrained identity, and easy documentation navigation.

Preview: English README · Korean README

Validation

Latest local verification on TypeScript 5.8.3 / Node 24.19.0 / NestJS 12.1.0:

  • npm run test:types
  • npm run build
  • npm run lint (no warnings)
  • npm run test:package: 49 files, no tests or fixtures; actual tar listing checked
  • Package regression check fails against the original archive containing test sources
  • All 45 production source/output files are byte-identical to the previous PR head
  • npm test: 5 suites, 22 tests, 12 snapshots passed
  • git diff --check
  • Original runtime function body compared byte-for-byte
  • All TypeScript blocks across six documentation files compile with strict checking and skipLibCheck: false
  • Both README examples run and produce the documented output
  • Usage examples exercise injected services, metadata, repeated calls, inherited getters, and typed uppercase wrapping
  • English/Korean code parity; all 20 original typed limitation bullets retained; 49 candidate-tree file/anchor links checked
  • Actual npm archive: 49 files, both READMEs included, no docs tree
  • Prettier, independent content review, and actual GitHub-rendered English/Korean README inspection
  • Final README rename: all five old-path references updated; 49 repository-local file/anchor links rechecked across 15 Markdown files; all code fences unchanged; other prose changes are limited to the approved strict-mode recommendations

CI passed on 98ac9e93b378ce0f7b2f5b9f090cc43130254663: the main job and all NestJS 8–12 jobs succeeded, including consolidated type tests and the package-content check in the main job. The remote commit tree matches the locally tested files.

PR Checklist

  • Read the contributing guide
  • Add English/Korean documentation, type tests, and runtime tests
  • Add a minor changeset

Kept in draft for API review. No merge, release, or support-policy changes are included.

@WhiteKiwi WhiteKiwi changed the title feat: add opt-in typed method decorators feat: extend createDecorator with typed method support Oct 1, 2026

@dleo9307 dleo9307 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

The API design looks solid to me: the unrestricted overload comes first, the typed overload is opt-in, and a trailing legacy overload keeps ReturnType<typeof createDecorator> working. The runtime body is unchanged; the only change is from a const arrow function to a function declaration. Nothing here blocks the feature. I'd fix two things before merging, and there's one coordination point with #65.

What I verified locally (Node 24.19.0, pnpm 11.23.0, head a7592cc):

  • lint, build, test:types and test:package pass, as do 5 suites / 22 tests / 12 snapshots.
  • pnpm pack (the actual publish path through Changesets) also yields 48 files, with no __test__ / type-tests / docs entries.
  • The emitted dist/create-decorator.d.ts has the three overloads as intended.
  • The branch merges cleanly with the current main.
  • In a consumer project (Nest 10.4.22), I compiled legacy-API-only usage, including a ReturnType<typeof createDecorator>-annotated factory, with TS 4.7.4 / 4.9.5 / 5.0.4 / 5.2.2 / 5.4.5 / 5.7.3 / 5.8.3. Every version reports 0 errors, so existing users see no regression.

Should fix before merge

1. The generic-factory inference pattern needs TypeScript 5.0+, and the guide doesn't say so

I ran both type-test files against the packed tarball across the same TS versions:

TS type-tests/create-decorator.ts (explicit shared contract) type-tests/original-method-inference.ts (generic-factory inference)
4.7.4 ✅ 0 errors ❌ 23 errors
4.9.5 ✅ 0 errors ❌ 23 errors
5.0.4 – 5.8.3 ✅ ✅

The guide's headline @Retry(...) example from docs/en/typed-decorators.md fails on TS 4.9.5 at the decorator itself:

error TS1270: Decorator function return type 'void | TypedPropertyDescriptor<AsyncMethod>' is not assignable to type 'void | TypedPropertyDescriptor<(id: number) => Promise<{ name: string; }>>'.
error TS2345: Argument of type 'TypedPropertyDescriptor<(id: number) => Promise<{ name: string; }>>' is not assignable to parameter of type 'TypedPropertyDescriptor<AsyncMethod>'.

So on 4.x, F falls back to its constraint, and the decorator can't be applied at all. This is a v2 minor, and v2 still supports NestJS 8/9, so TS 4.x consumers are in scope. I'd state the following in both docs/en/typed-decorators.md and docs/ko/typed-decorators.md, and briefly in the changeset:

  • The explicit shared-contract form (createDecorator<TextMethod>) works on TS 4.7+.
  • Inferring F from the decorated method requires TS 5.0+.

2. Test files are no longer part of any tsconfig project (regression from main)

ffad3b0 added **/__test__ to the root exclude, and a4ddc9d made tsconfig.build.json inherit it:

$ tsc -p tsconfig.json --listFilesOnly | grep -c __test__
0        # on main this includes the test files

The consequences:

  • Editors: tsserver treats test files as an inferred project without experimentalDecorators. Emulating that gives TS1238: Unable to resolve signature of class decorator and TS1241 ... method decorator across the test files.
  • test:types scope: test:types no longer covers the tests. CI still type-checks them through ts-jest diagnostics, so this isn't a CI gap. The impact is editor DX and the scope of test:types.

The exclusion doesn't seem necessary. With **/__test__ removed from the root exclude, tsc -p tsconfig.json --noEmit still exits 0 and covers all 9 test files. The fix I'd suggest:

  • Drop **/__test__ from the root exclude.
  • Restore "exclude": ["node_modules", "**/__test__"] in tsconfig.build.json. Otherwise, re-including the tests at the root would compile them into dist.

Coordination with #65

These two PRs touch the same files, so whichever lands second will need deliberate reconciliation. Merging both locally conflicts in README.md, readme_kr.md, package.json and tsconfig.json. Beyond the text conflicts:

  • scripts/check-package.mjs asserts that main and src/index.ts are in the tarball. #65 removes both: there is no main field, and the package becomes dist-only. So the script fails outright after a rebase (paths.has(undefined)).
  • type-tests/*.ts import '../src' without an extension, which breaks under #65's NodeNext resolution.
  • #63's root exclude: ["**/__test__"] would silently defeat the pnpm typecheck step that #65 added to type-check tests under NodeNext.
  • Docs layout: this PR introduces docs/en/ + docs/ko/, while #65 adds docs/migrations/v3.md (English only). It would be good to settle on one convention, e.g. docs/{en,ko}/migration-v3.md.
  • Packaging checks: both PRs add one (check-package.mjs here, the assertions in #65's verify-packed.mjs). They could probably be consolidated into one.

Nits / follow-ups (optional)

  • The README and guide examples stack @Injectable() on top of @Aspect(...). Since #66 (2.2.1), @Aspect already applies Injectable(), so this is redundant but harmless.
  • check-package.mjs calls execFileSync('npm', ...), which won't work on Windows without the .cmd shim or a shell. CI is Linux-only, so this is low impact.
  • The typed overload keeps metadata?: unknown, so it isn't linked to LazyDecorator<T, M>'s M. Something like createDecorator<T, M>(key, metadata: M) could be a natural follow-up, since #42 is mainly about the method type.

Thanks for the thorough type-test fixtures. The positive/negative cases, IsAny guards and documented limitations made this easy to verify.

Copy link
Copy Markdown
Member Author

@dleo9307 Addressed both in e10e4c3.

  • Both guides and the changeset now distinguish TypeScript 4.7+ explicit contracts from TypeScript 5.0+ contextual method inference, with an explicit-type fallback for 4.x.
  • Restored all nine runtime-test/fixture files to the root TypeScript project while keeping them excluded from the production build. The controller fixture uses property injection to avoid NestJS 8's constructor-decorator typing issue, without assertions or suppressions.

I also reproduced a semantic-check gap: the current ESM Jest path accepted a deliberately invalid assignment in a test, while the restored root TypeScript check rejected it. This fixes CI coverage as well as editor project membership.

CI passed for this head, including all NestJS 8–12 jobs. The exact branch passed 22 tests / 12 snapshots locally; CI's merge ref includes main's additional aspect tests and passed 25 tests / 12 snapshots. The fresh package still contains 49 files with no tests or fixtures.

Keeping #65's NodeNext, dist-only packaging, and docs reconciliation separate for whichever PR lands second. The examples retain @Injectable() until #66 is incorporated into this branch.

WhiteKiwi added a commit that referenced this pull request Oct 6, 2026
## Summary

Prepare the next **major** release on top of the 2.2.1 main-branch
baseline. NestJS 12 support was introduced in 2.2.0. Related to #59;
independent of the typed-decorator work in #63.

- Drop NestJS 8/9 peers; retain NestJS 10/11/12.
- Ship one ESM build with `type: module`, explicit types/default root
export (no legacy main), NodeNext build resolution and .js relative
specifiers.
- Propose Node.js >=22.12.0 as the new runtime floor.
- Keep decorator runtime behavior intact; make erased imports explicit.
- Use native ESM Jest/Prettier configuration files and a NodeNext root
TypeScript config.
- Keep the [migration
guide](https://github.com/toss/nestjs-aop/blob/2e1b7f486d69d3e7152013e708b94adc3ac2a93d/docs/migrations/v3.md)
under docs/migrations/v3.md in the repository only, with maintained
main-branch README/changelog links. Publish only dist, retain top-level
types, build in prepack, and embed sources in JS source maps without
shipping the source tree or declaration maps.
- Add packed-tarball consumer CI for Nest 10.4.22/11.2.6/12.1.0 × Node
22.12.0/24.19.0/26.10.0, plus baseline and latest-per-major Nest cases
on Node 24.19.0.

## Release boundary

**Draft only: do not merge or publish until the support policy below is
reviewed.** The package version remains 2.2.1; `changeset status`
reports one major release to 3.0.0. No version command or publish was
run.

Includes main `be825e60e62351dbc222030d57c623349317d0db` (2.2.1,
including #66 and #67), integrated without rewriting the reviewed branch
history. PR #63 is not included. If it merges first, rebase and rerun
the consumer matrix; do not inadvertently combine an intended separate
minor release into the major.

## Published 2.2.0 baseline (fresh npm consumer)

On Node 24.19.0, independently installed `@toss/nestjs-aop@2.2.0` + Nest
12.1.0 peers, with no workspace symlinks:

- Native CJS and ESM applications pass actual Nest bootstrap/aspect
wrapping, before/original/after order, return values, undecorated
method, lifecycle completion and repeated-call checks.
- Jest 30.4.2 CJS passes with `--experimental-vm-modules`; default Jest
without the flag fails on Nest's ESM.
- Static ESM imports hit Jest's mixed CJS/ESM concurrent-loader error.
Sequentially awaiting Nest common/core imports before dynamically
importing the consumer passes.
- The v3 candidate passes that static-import ESM Jest fixture directly.

## Candidate verification

Current head: `2e1b7f486d69d3e7152013e708b94adc3ac2a93d`.

- Frozen-lockfile install, lint, root NodeNext typecheck (including
tests), build and pack pass. Four focused source-map regression tests
also pass.
- Repository Jest suite: 5 suites / 22 tests / 12 snapshots pass.
- [CI #129](https://github.com/toss/nestjs-aop/actions/runs/36974513302)
passes all 16 jobs: the base job, all 9 pinned Node/Nest pairs and 6
baseline/latest packed-consumer jobs.
- Every packed-consumer job verifies native CJS/ESM runtime, plain-JS
ESM Jest, the migration guide's exact ts-jest ESM configuration with
Jest 29.7.0 and 30.4.2, compiler compatibility boundaries, and the
dist-only/source-map packaging contract.
- TypeScript 5.8.3 NodeNext .mts/.cts, TypeScript 5.7.3 NodeNext .mts,
and both versions in CommonJS/node10 mode pass. Expected TS1479 failures
are asserted for TypeScript 5.7.3 CJS/NodeNext and TypeScript 5.8.3
CJS/node16.
- CJS Jest 30.4.2 with the VM flag passes on Node 24.19/26.10. Node 22
CJS Jest remains explicitly migration-required and visibly skipped after
validating ESM tests; it is not claimed as a pass.
- The new TypeScript fixture checks actual Nest bootstrap, constructor
injection, aspect order, return values, lifecycle and repeated calls.
The guide/config comparison works with LF and CRLF checkouts.
- Local Node 24.19 checks cover root NodeNext typechecking and all 22
tests on Nest 10.4.22, 11.2.6 and 12.1.0, plus the four map regressions
and packed Nest 12.1 consumer. The full pinned and baseline/latest
matrices pass in CI.

## Review follow-up

- Document the conditional TS 5.8 floor for CJS/NodeNext, node16/node18
limitations and the existing CommonJS/node10 path. Jest 29 remains
supported in ESM mode; upgrading to Jest 30 is not universally required.
- Keep ESM-only packaging, Nest 10/11/12 peers and Node >=22.12.
Document the Node 22.12 require(esm) warning rather than changing the
runtime floor.
- Replace stale commit-pinned published documentation links with
maintained main-branch links and remove PR-process notes from the
migration guide.
- Keep reproducible pins and add baseline/current-major checks. The
baseline pairs are 10.0.0, 11.0.0 and 12.0.1. Nest 12.0.0 has
inconsistent upstream peers (core requires common ^11), so 12.0.1 is
used without bypassing peer validation.
- The Nest 10.0.0 baseline explicitly uses skipLibCheck:true for its
upstream file-validator TS2416 errors. Application
import/compiler-boundary checks still run; the other pinned/latest cases
retain skipLibCheck:false.
- Pack under the matrix Node version. The verifier can invoke npm's JS
entry point through `npm run test:packed`, avoiding Windows .cmd
execution. Windows itself was not run locally.
- Remove unused Babel configuration/devDependencies, stale esm
exclusions and the Nest 8 comment. Lockfile pruning removes 116 unused
entries without changing retained dependency versions.
- Keep the root-only export contract, existing v2 guide path and
npm-based prepack build. No dual build, package.json subpath export or
unrelated runtime change is introduced. The existing Aspect/Injectable
defect was fixed separately in #66 and is now included through the main
integration.

## Second review follow-up

- Integrate main's 2.2.1 release and resolve package.json while
retaining the ESM root exports and no legacy main field.
- Update the imported Aspect regression test's four relative imports to
.js, make LazyDecorator/WrapParams type-only, and use
@nestjs/common/constants.js for NodeNext compatibility with Nest 10/11
as well as 12.
- Add root source/test typechecking and packaging-regression gates to
the base job and all nine pinned compatibility jobs. These cover test
files excluded from the package build.
- Scan source maps recursively, including dist/core and dist/utils. The
packed verifier reports all nine JavaScript maps checked. Four red/green
tests cover traversal, nested missing embedded source, nested absolute
paths and nested declaration maps.

## Proposed support contract — maintainer decision

Keep Node >=22.12 runtime support and require Node 22 users to migrate
Jest tests to ESM mode. Modern Node 24.9+ / recent Jest may use
synchronous ESM loading with the VM flag, but old CJS test/mocking
workflows are not universally compatible.

This policy is a **proposal in this draft**, not a final approval of the
migration cost. No dual build is introduced. The migration guide also
records the exports/deep-import break and ESM mock differences.

### Why this draft uses one ESM artifact

A dual build is a viable alternative for preserving Nest 10/11's default
CommonJS toolchain. This draft favors one implementation artifact for
both import and supported require consumers, avoiding separate CJS/ESM
module copies and parallel build/export/declaration outputs. The cost is
the explicitly documented compiler and Jest migration.

With the current ASPECT = Symbol('ASPECT'), independently loaded CJS and
ESM builds would not share the aspect metadata key. A dual-build
implementation would need a namespaced shared key such as Symbol.for,
plus mixed-loader regression tests; the hazard is manageable, not a
claim that dual publishing is impossible. Maintainers still need to
decide whether this single-artifact tradeoff is appropriate before
merging.

## Pure-ESM packaging references

Reviewed current
[p-queue](https://github.com/sindresorhus/p-queue/blob/main/package.json)
(TypeScript),
[p-limit](https://github.com/sindresorhus/p-limit/blob/main/package.json),
[p-retry](https://github.com/sindresorhus/p-retry/blob/main/package.json)
and [Sindre Sorhus's
guide](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).

Adopted type:module, types/default exports in that order, no legacy
main, dist-only allowlist, a top-level types pointer, Node-aware
compiler resolution and prepack build. Keep the tested Node floor and
Nest legacy decorator metadata rather than copying unrelated
compiler/test presets. ES2022 output retains the previous class-field
semantics explicitly. No blanket sideEffects:false assertion is added to
this decorator/metadata library.

Local build, lint, 22 tests and fresh packed Nest 12 consumer pass.
Packed artifact has 30 files, no source/doc trees or declaration maps,
and all 9 JS maps contain embedded source without absolute source paths.
The CI consumer test now also enforces this packaging contract.

## CI

[CI #129](https://github.com/toss/nestjs-aop/actions/runs/36974513302)
passed on exact head `2e1b7f486d69d3e7152013e708b94adc3ac2a93d`: all 16
jobs, including 15 packed-consumer jobs with the expanded compiler/Jest
and packaging checks.

The PR remains draft and has not been merged into main. No version
command or publish was run for this proposal. The support-policy
decision above is still required before release.

@WhiteKiwi WhiteKiwi left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f2b3dc9907c3352b4609c9e47b5543c7eb6b98f5 기준으로 overload 순서/기존 호출 호환성, 공개 export, 타입 추론·this·overload/generic 음성 fixture, 런타임 테스트, CI/패키징 검사와 한·영 가이드를 정적으로 재검토했습니다. 기존 리뷰의 TypeScript 버전 안내 및 루트 테스트 프로젝트 포함 문제는 현재 변경에서 반영되어 있어 중복 지적하지 않습니다. 추가로 보고할 근거 있는 코드 결함은 찾지 못했습니다.

참고: PR 본문은 아직 src+dist 패키징/NestJS 8–12/ESM 변경 별도라고 설명하지만 현재 diff는 dist-only와 v3 ESM 요구사항을 반영합니다. 최종 검토자가 이전 검증과 현재 head를 혼동하지 않도록 본문도 현재 상태에 맞춰 갱신하면 좋겠습니다.

이번 검토에서는 의존성 설치, TypeScript/Jest/pack 실행 또는 CI 재실행은 하지 않았습니다. 기존 실행 기록은 독립 재실행 결과가 아니며 이 COMMENT는 병합 승인이 아닙니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: support typed decorator

2 participants