@anvil-di/anvil-unplugin 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -0
- package/dist/decorator-strip.d.ts +102 -0
- package/dist/decorator-strip.d.ts.map +1 -0
- package/dist/decorator-strip.js +225 -0
- package/dist/decorator-strip.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -0
- package/dist/index.js.map +1 -1
- package/package.json +9 -2
- package/src/decorator-strip.integration.test.ts +144 -0
- package/src/decorator-strip.test.ts +164 -0
- package/src/decorator-strip.ts +268 -0
- package/src/index.ts +61 -0
package/README.md
CHANGED
|
@@ -58,9 +58,79 @@ anvil({
|
|
|
58
58
|
// - "native" (default): spawn the anvil Rust binary
|
|
59
59
|
// - "wasm": run in-process via @anvil-di/anvil-codegen-wasm (no spawn overhead)
|
|
60
60
|
mode: "native",
|
|
61
|
+
|
|
62
|
+
// Delete anvil's no-op decorators before the bundler transforms them.
|
|
63
|
+
// Defaults to true; see "Decorator stripping" below.
|
|
64
|
+
stripDecorators: true,
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Decorator stripping
|
|
69
|
+
|
|
70
|
+
anvil is [standard-decorators-only](../../docs/adr/0002-stage3-decorators-only.md). oxc — which **Rolldown, Vite 6+, and Rspack** transform with — implements only the *legacy* convention, which leaves an anvil project with two broken options:
|
|
71
|
+
|
|
72
|
+
| oxc setting | result |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| default (`decorator.legacy: false`) | Decorators reach the output verbatim: `var C = @Controller("/x") class {...}`. Importing the bundle throws `SyntaxError`. |
|
|
75
|
+
| `decorator.legacy: true` | Method decorators are called `(target, key, descriptor)`, but anvil's are `(target, context) => target`. `__decorate` then does `Object.defineProperty(target, key, theClass)` and corrupts the class. |
|
|
76
|
+
|
|
77
|
+
The usual escape is routing those files through `tsc`, whose standard-decorator emit is correct — at the cost of a dependency on TypeScript's JS compiler API, which TypeScript 7 does not ship.
|
|
78
|
+
|
|
79
|
+
So the plugin takes a third option: it **deletes** the decorators before the bundler sees one. This is on by default, and it is what lets an anvil project bundle correctly on an oxc-based toolchain at all.
|
|
80
|
+
|
|
81
|
+
### Why deleting is correct
|
|
82
|
+
|
|
83
|
+
Every decorator in `@anvil-di/anvil` and `@anvil-di/bellows` is an identity function — `return target`. They exist so your code typechecks; the wiring they describe is read out of the **source** by the Rust toolchain during `anvil build` / `anvil-bellows`, before a bundler is involved. This is invariant #1: *"No runtime reflection. Decorators are no-ops at runtime."*
|
|
84
|
+
|
|
85
|
+
Applying them is therefore observably identical to not applying them, minus the `__esDecorate`/`__runInitializers` helpers a real emit inlines into every module that uses one.
|
|
86
|
+
|
|
87
|
+
### Safety
|
|
88
|
+
|
|
89
|
+
Only decorators whose binding resolves to a **known no-op module** are removed. Matching is by import binding, not by name, so a local helper that happens to be called `Get` is untouched; aliases (`import { Inject as I }`) and namespace imports (`@anvil.Inject`) resolve correctly.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
@Controller("/x") // removed
|
|
93
|
+
export class C {
|
|
94
|
+
@observable count = 1; // kept — not ours, might do something
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
A decorator with real behaviour therefore survives into the output and fails loudly, rather than being silently dropped.
|
|
99
|
+
|
|
100
|
+
### Options
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// Also strip your own compile-time-only markers — a `@Public(reason)` that
|
|
104
|
+
// only anvil-bellows reads, say. A string matches a specifier exactly; a
|
|
105
|
+
// RegExp is tested against it. Relative specifiers match as written in the
|
|
106
|
+
// importing file, so prefer a RegExp.
|
|
107
|
+
anvil({
|
|
108
|
+
stripDecorators: { additionalModules: [/(?:^|\/)http\/public-route(?:\.js)?$/] },
|
|
61
109
|
});
|
|
110
|
+
|
|
111
|
+
// Or turn it off, if something else in your pipeline already handles
|
|
112
|
+
// standard decorators correctly (a ts-loader / tsc pre-pass, say).
|
|
113
|
+
anvil({ stripDecorators: false });
|
|
62
114
|
```
|
|
63
115
|
|
|
116
|
+
> Adding a module to `additionalModules` asserts that none of its decorators do anything at runtime. That claim is not verified.
|
|
117
|
+
|
|
118
|
+
### Without the codegen hooks
|
|
119
|
+
|
|
120
|
+
A project that already runs `anvil build` / `anvil-bellows` its own way (a `gen` npm script, say) and only needs its bundle to come out runnable can take the transform alone:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
// rolldown.config.ts
|
|
124
|
+
import { stripDecoratorsUnplugin } from "@anvil-di/anvil-unplugin/strip";
|
|
125
|
+
|
|
126
|
+
export default {
|
|
127
|
+
input: "src/index.ts",
|
|
128
|
+
plugins: [stripDecoratorsUnplugin.rolldown()],
|
|
129
|
+
};
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`.vite()`, `.rollup()`, `.webpack()`, `.rspack()` and `.esbuild()` are available the same way. The underlying functions — `stripNoopDecorators(code, id, options)` and the cheap pre-filter `mayContainNoopDecorators(code, options)` — are exported from the same entry point for hand-written transforms. `stripNoopDecorators` returns `null` when there is nothing to do, so callers can pass the original source and its existing source map straight through.
|
|
133
|
+
|
|
64
134
|
## How it works
|
|
65
135
|
|
|
66
136
|
The plugin invokes the `anvil` CLI as a child process (native mode) or runs the WASM pipeline in-process (wasm mode):
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import MagicString from "magic-string";
|
|
2
|
+
import { type UnpluginInstance } from "unplugin";
|
|
3
|
+
/** Options for {@link stripNoopDecorators}. */
|
|
4
|
+
export interface StripOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Additional modules whose decorators are known to be no-ops, beyond
|
|
7
|
+
* `@anvil-di/anvil` and `@anvil-di/bellows`.
|
|
8
|
+
*
|
|
9
|
+
* A string matches a module specifier exactly; a RegExp is tested against
|
|
10
|
+
* it. Use this for a project's own marker decorators — a `@Public(reason)`
|
|
11
|
+
* that exists only so `anvil-bellows` can read it at codegen time, for
|
|
12
|
+
* instance. Relative specifiers are matched as written in the importing
|
|
13
|
+
* file, so prefer a RegExp: `/(?:^|\/)http\/public-route(?:\.js)?$/`.
|
|
14
|
+
*
|
|
15
|
+
* Adding a module here asserts that none of its decorators do anything at
|
|
16
|
+
* runtime. That claim is not checked; get it wrong and behaviour is
|
|
17
|
+
* silently dropped.
|
|
18
|
+
*/
|
|
19
|
+
additionalModules?: readonly (string | RegExp)[];
|
|
20
|
+
}
|
|
21
|
+
/** The result of a successful strip. */
|
|
22
|
+
export interface StripResult {
|
|
23
|
+
/** Source with the no-op decorators removed. */
|
|
24
|
+
code: string;
|
|
25
|
+
/** Source map for the removals, as returned by magic-string. */
|
|
26
|
+
map: ReturnType<MagicString["generateMap"]>;
|
|
27
|
+
/** How many decorators were removed. */
|
|
28
|
+
removed: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Delete every decorator that resolves to a no-op decorator module.
|
|
32
|
+
*
|
|
33
|
+
* Returns `null` when there is nothing to do — no such import, or no such
|
|
34
|
+
* decorator — so callers can hand the original source and its existing
|
|
35
|
+
* source map straight through.
|
|
36
|
+
*
|
|
37
|
+
* ## Why deleting is correct
|
|
38
|
+
*
|
|
39
|
+
* anvil's and bellows' decorators are identity functions: `@Provides`,
|
|
40
|
+
* `@Controller`, `@Get` and the rest all `return target`. They exist so user
|
|
41
|
+
* code typechecks and so the Rust toolchain can read the wiring out of the
|
|
42
|
+
* source during `anvil build` / `anvil-bellows`, which happens before any
|
|
43
|
+
* bundler runs. Nothing observable happens when they are applied, so
|
|
44
|
+
* removing them produces the same program without the
|
|
45
|
+
* `__esDecorate`/`__runInitializers` machinery a real emit would inline.
|
|
46
|
+
*
|
|
47
|
+
* ## Why it is needed
|
|
48
|
+
*
|
|
49
|
+
* oxc's decorator transform implements only the legacy
|
|
50
|
+
* (`experimentalDecorators`) convention, which anvil forbids. Left alone,
|
|
51
|
+
* standard decorators pass through a bundle verbatim and no JS engine can
|
|
52
|
+
* parse them; transformed as legacy, method decorators are called with the
|
|
53
|
+
* wrong signature and corrupt the class. Routing the affected files through
|
|
54
|
+
* `tsc` sidesteps both, at the cost of a dependency on TypeScript's JS
|
|
55
|
+
* compiler API — which TypeScript 7 does not ship.
|
|
56
|
+
*
|
|
57
|
+
* ## Safety
|
|
58
|
+
*
|
|
59
|
+
* Only decorators whose binding comes from a listed module are removed.
|
|
60
|
+
* Anything else is left exactly where it is, so a decorator with real
|
|
61
|
+
* behaviour survives into the output and fails loudly rather than being
|
|
62
|
+
* silently dropped.
|
|
63
|
+
*
|
|
64
|
+
* @param code source text of a `.ts` / `.tsx` file
|
|
65
|
+
* @param id file path, used for parser mode selection and diagnostics
|
|
66
|
+
*/
|
|
67
|
+
export declare function stripNoopDecorators(code: string, id: string, options?: StripOptions): StripResult | null;
|
|
68
|
+
/**
|
|
69
|
+
* Cheap pre-filter, so a bundler can skip parsing files that cannot possibly
|
|
70
|
+
* contain a strippable decorator.
|
|
71
|
+
*
|
|
72
|
+
* Conservative by construction: never a false negative, and a false positive
|
|
73
|
+
* costs only a wasted parse. A `RegExp` in `additionalModules` is written to
|
|
74
|
+
* match a module specifier, so it cannot be tested against whole source text
|
|
75
|
+
* — any file with decorator syntax counts as a candidate when one is set.
|
|
76
|
+
*/
|
|
77
|
+
export declare function mayContainNoopDecorators(code: string, options?: StripOptions): boolean;
|
|
78
|
+
/** Options for the standalone decorator-strip plugin. */
|
|
79
|
+
export interface StripDecoratorsPluginOptions extends StripOptions {
|
|
80
|
+
/**
|
|
81
|
+
* File extensions the transform applies to. Defaults to `.ts` and `.tsx`.
|
|
82
|
+
*/
|
|
83
|
+
extensions?: readonly string[];
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The decorator strip on its own, without anvil's codegen hooks — for a
|
|
87
|
+
* project that already runs `anvil build` / `anvil-bellows` its own way
|
|
88
|
+
* (a `gen` npm script, say) and only needs its bundle to come out
|
|
89
|
+
* runnable.
|
|
90
|
+
*
|
|
91
|
+
* ```ts
|
|
92
|
+
* // rolldown.config.ts
|
|
93
|
+
* import { stripDecoratorsUnplugin } from "@anvil-di/anvil-unplugin/strip";
|
|
94
|
+
*
|
|
95
|
+
* export default { plugins: [stripDecoratorsUnplugin.rolldown()] };
|
|
96
|
+
* ```
|
|
97
|
+
*
|
|
98
|
+
* Projects using the main `anvilUnplugin` get this already; see its
|
|
99
|
+
* `stripDecorators` option.
|
|
100
|
+
*/
|
|
101
|
+
export declare const stripDecoratorsUnplugin: UnpluginInstance<StripDecoratorsPluginOptions | undefined, false>;
|
|
102
|
+
//# sourceMappingURL=decorator-strip.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decorator-strip.d.ts","sourceRoot":"","sources":["../src/decorator-strip.ts"],"names":[],"mappings":"AACA,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAmBjE,+CAA+C;AAC/C,MAAM,WAAW,YAAY;IAC3B;;;;;;;;;;;;;OAaG;IACH,iBAAiB,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;CAClD;AAED,wCAAwC;AACxC,MAAM,WAAW,WAAW;IAC1B,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,gEAAgE;IAChE,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC;IAC5C,wCAAwC;IACxC,OAAO,EAAE,MAAM,CAAC;CACjB;AAoED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,OAAO,GAAE,YAAiB,GACzB,WAAW,GAAG,IAAI,CAgCpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAY1F;AAED,yDAAyD;AACzD,MAAM,WAAW,4BAA6B,SAAQ,YAAY;IAChE;;OAEG;IACH,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAID;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,uBAAuB,EAAE,gBAAgB,CACpD,4BAA4B,GAAG,SAAS,EACxC,KAAK,CAyBL,CAAC"}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { parseSync } from "oxc-parser";
|
|
2
|
+
import MagicString from "magic-string";
|
|
3
|
+
import { createUnplugin } from "unplugin";
|
|
4
|
+
/**
|
|
5
|
+
* Modules whose every export is a decorator with no runtime behaviour.
|
|
6
|
+
*
|
|
7
|
+
* Both anvil packages qualify by construction: their decorators are stubs
|
|
8
|
+
* that `return target`, and all semantics are read out of the source by the
|
|
9
|
+
* Rust toolchain during codegen. This is invariant #1 of the project —
|
|
10
|
+
* "No runtime reflection. Decorators are no-ops at runtime."
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_NOOP_MODULES = [/^@anvil-di\/(anvil|bellows)$/];
|
|
13
|
+
/**
|
|
14
|
+
* A decorator-shaped token: `@Name` at a position where one can legally
|
|
15
|
+
* appear. Used only by {@link mayContainNoopDecorators}; a JSDoc `@param`
|
|
16
|
+
* can match, which costs a parse and nothing else.
|
|
17
|
+
*/
|
|
18
|
+
const DECORATOR_TOKEN_RE = /(?:^|[\s{;(])@[A-Za-z_$][\w$]*/;
|
|
19
|
+
function matches(specifier, patterns) {
|
|
20
|
+
return patterns.some((p) => (typeof p === "string" ? p === specifier : p.test(specifier)));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Local names introduced by imports from a no-op decorator module, honouring
|
|
24
|
+
* aliases (`import { Inject as I }`). Namespace imports are tracked apart so
|
|
25
|
+
* `@anvil.Inject` resolves through its object rather than its property.
|
|
26
|
+
*/
|
|
27
|
+
function noopBindings(program, patterns) {
|
|
28
|
+
const named = new Set();
|
|
29
|
+
const namespaces = new Set();
|
|
30
|
+
for (const node of program["body"] ?? []) {
|
|
31
|
+
if (node.type !== "ImportDeclaration")
|
|
32
|
+
continue;
|
|
33
|
+
// `import type { ... }` contributes no runtime binding, so it can never
|
|
34
|
+
// be the callee of a decorator.
|
|
35
|
+
if (node["importKind"] === "type")
|
|
36
|
+
continue;
|
|
37
|
+
const source = node["source"];
|
|
38
|
+
if (source?.value === undefined || !matches(source.value, patterns))
|
|
39
|
+
continue;
|
|
40
|
+
for (const spec of node["specifiers"] ?? []) {
|
|
41
|
+
if (spec["importKind"] === "type")
|
|
42
|
+
continue;
|
|
43
|
+
const local = spec["local"]?.name;
|
|
44
|
+
if (local === undefined)
|
|
45
|
+
continue;
|
|
46
|
+
if (spec.type === "ImportNamespaceSpecifier")
|
|
47
|
+
namespaces.add(local);
|
|
48
|
+
else
|
|
49
|
+
named.add(local);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { named, namespaces };
|
|
53
|
+
}
|
|
54
|
+
/** The identifier a decorator dispatches on: `@A`, `@A(x)`, `@ns.A`, `@ns.A(x)`. */
|
|
55
|
+
function decoratorRoot(expression) {
|
|
56
|
+
let expr = expression;
|
|
57
|
+
if (expr.type === "CallExpression")
|
|
58
|
+
expr = expr["callee"];
|
|
59
|
+
if (expr.type === "Identifier")
|
|
60
|
+
return { kind: "named", name: expr["name"] };
|
|
61
|
+
if (expr.type === "MemberExpression" && expr["computed"] !== true) {
|
|
62
|
+
const object = expr["object"];
|
|
63
|
+
if (object.type === "Identifier")
|
|
64
|
+
return { kind: "member", name: object["name"] };
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
function walk(node, visit) {
|
|
69
|
+
if (node === null || typeof node !== "object")
|
|
70
|
+
return;
|
|
71
|
+
if (Array.isArray(node)) {
|
|
72
|
+
for (const child of node)
|
|
73
|
+
walk(child, visit);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const candidate = node;
|
|
77
|
+
if (typeof candidate.type === "string")
|
|
78
|
+
visit(candidate);
|
|
79
|
+
for (const key of Object.keys(candidate)) {
|
|
80
|
+
if (key === "type")
|
|
81
|
+
continue;
|
|
82
|
+
walk(candidate[key], visit);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Delete every decorator that resolves to a no-op decorator module.
|
|
87
|
+
*
|
|
88
|
+
* Returns `null` when there is nothing to do — no such import, or no such
|
|
89
|
+
* decorator — so callers can hand the original source and its existing
|
|
90
|
+
* source map straight through.
|
|
91
|
+
*
|
|
92
|
+
* ## Why deleting is correct
|
|
93
|
+
*
|
|
94
|
+
* anvil's and bellows' decorators are identity functions: `@Provides`,
|
|
95
|
+
* `@Controller`, `@Get` and the rest all `return target`. They exist so user
|
|
96
|
+
* code typechecks and so the Rust toolchain can read the wiring out of the
|
|
97
|
+
* source during `anvil build` / `anvil-bellows`, which happens before any
|
|
98
|
+
* bundler runs. Nothing observable happens when they are applied, so
|
|
99
|
+
* removing them produces the same program without the
|
|
100
|
+
* `__esDecorate`/`__runInitializers` machinery a real emit would inline.
|
|
101
|
+
*
|
|
102
|
+
* ## Why it is needed
|
|
103
|
+
*
|
|
104
|
+
* oxc's decorator transform implements only the legacy
|
|
105
|
+
* (`experimentalDecorators`) convention, which anvil forbids. Left alone,
|
|
106
|
+
* standard decorators pass through a bundle verbatim and no JS engine can
|
|
107
|
+
* parse them; transformed as legacy, method decorators are called with the
|
|
108
|
+
* wrong signature and corrupt the class. Routing the affected files through
|
|
109
|
+
* `tsc` sidesteps both, at the cost of a dependency on TypeScript's JS
|
|
110
|
+
* compiler API — which TypeScript 7 does not ship.
|
|
111
|
+
*
|
|
112
|
+
* ## Safety
|
|
113
|
+
*
|
|
114
|
+
* Only decorators whose binding comes from a listed module are removed.
|
|
115
|
+
* Anything else is left exactly where it is, so a decorator with real
|
|
116
|
+
* behaviour survives into the output and fails loudly rather than being
|
|
117
|
+
* silently dropped.
|
|
118
|
+
*
|
|
119
|
+
* @param code source text of a `.ts` / `.tsx` file
|
|
120
|
+
* @param id file path, used for parser mode selection and diagnostics
|
|
121
|
+
*/
|
|
122
|
+
export function stripNoopDecorators(code, id, options = {}) {
|
|
123
|
+
const patterns = [
|
|
124
|
+
...DEFAULT_NOOP_MODULES,
|
|
125
|
+
...(options.additionalModules ?? []),
|
|
126
|
+
];
|
|
127
|
+
const parsed = parseSync(id, code, { lang: id.endsWith(".tsx") ? "tsx" : "ts" });
|
|
128
|
+
if (parsed.errors.length > 0) {
|
|
129
|
+
throw new Error(`strip-decorators: cannot parse ${id}: ${parsed.errors[0]?.message ?? ""}`);
|
|
130
|
+
}
|
|
131
|
+
const program = parsed.program;
|
|
132
|
+
const { named, namespaces } = noopBindings(program, patterns);
|
|
133
|
+
if (named.size === 0 && namespaces.size === 0)
|
|
134
|
+
return null;
|
|
135
|
+
const ranges = [];
|
|
136
|
+
walk(program, (node) => {
|
|
137
|
+
if (node.type !== "Decorator")
|
|
138
|
+
return;
|
|
139
|
+
const root = decoratorRoot(node["expression"]);
|
|
140
|
+
if (root === null)
|
|
141
|
+
return;
|
|
142
|
+
const owned = root.kind === "named" ? named.has(root.name) : namespaces.has(root.name);
|
|
143
|
+
if (owned)
|
|
144
|
+
ranges.push([node["start"], node["end"]]);
|
|
145
|
+
});
|
|
146
|
+
if (ranges.length === 0)
|
|
147
|
+
return null;
|
|
148
|
+
const s = new MagicString(code);
|
|
149
|
+
for (const [start, end] of ranges)
|
|
150
|
+
s.remove(start, end);
|
|
151
|
+
return {
|
|
152
|
+
code: s.toString(),
|
|
153
|
+
map: s.generateMap({ source: id, hires: true }),
|
|
154
|
+
removed: ranges.length,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Cheap pre-filter, so a bundler can skip parsing files that cannot possibly
|
|
159
|
+
* contain a strippable decorator.
|
|
160
|
+
*
|
|
161
|
+
* Conservative by construction: never a false negative, and a false positive
|
|
162
|
+
* costs only a wasted parse. A `RegExp` in `additionalModules` is written to
|
|
163
|
+
* match a module specifier, so it cannot be tested against whole source text
|
|
164
|
+
* — any file with decorator syntax counts as a candidate when one is set.
|
|
165
|
+
*/
|
|
166
|
+
export function mayContainNoopDecorators(code, options = {}) {
|
|
167
|
+
if (!DECORATOR_TOKEN_RE.test(code))
|
|
168
|
+
return false;
|
|
169
|
+
if (code.includes("@anvil-di/anvil") || code.includes("@anvil-di/bellows"))
|
|
170
|
+
return true;
|
|
171
|
+
for (const pattern of options.additionalModules ?? []) {
|
|
172
|
+
if (typeof pattern === "string") {
|
|
173
|
+
if (code.includes(pattern))
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
// A specifier pattern cannot be matched against whole source text.
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
const DEFAULT_EXTENSIONS = [".ts", ".tsx"];
|
|
184
|
+
/**
|
|
185
|
+
* The decorator strip on its own, without anvil's codegen hooks — for a
|
|
186
|
+
* project that already runs `anvil build` / `anvil-bellows` its own way
|
|
187
|
+
* (a `gen` npm script, say) and only needs its bundle to come out
|
|
188
|
+
* runnable.
|
|
189
|
+
*
|
|
190
|
+
* ```ts
|
|
191
|
+
* // rolldown.config.ts
|
|
192
|
+
* import { stripDecoratorsUnplugin } from "@anvil-di/anvil-unplugin/strip";
|
|
193
|
+
*
|
|
194
|
+
* export default { plugins: [stripDecoratorsUnplugin.rolldown()] };
|
|
195
|
+
* ```
|
|
196
|
+
*
|
|
197
|
+
* Projects using the main `anvilUnplugin` get this already; see its
|
|
198
|
+
* `stripDecorators` option.
|
|
199
|
+
*/
|
|
200
|
+
export const stripDecoratorsUnplugin = createUnplugin((rawOptions) => {
|
|
201
|
+
const extensions = rawOptions?.extensions ?? DEFAULT_EXTENSIONS;
|
|
202
|
+
const stripOptions = rawOptions?.additionalModules === undefined
|
|
203
|
+
? {}
|
|
204
|
+
: { additionalModules: rawOptions.additionalModules };
|
|
205
|
+
return {
|
|
206
|
+
name: "anvil-strip-decorators",
|
|
207
|
+
// `id` carries a query suffix in some bundlers (`?used`, `?vue&type=...`);
|
|
208
|
+
// compare against the path portion only.
|
|
209
|
+
transformInclude(id) {
|
|
210
|
+
const file = id.split("?")[0] ?? id;
|
|
211
|
+
return extensions.some((ext) => file.endsWith(ext));
|
|
212
|
+
},
|
|
213
|
+
transform(code, id) {
|
|
214
|
+
if (!mayContainNoopDecorators(code, stripOptions))
|
|
215
|
+
return null;
|
|
216
|
+
const result = stripNoopDecorators(code, id.split("?")[0] ?? id, stripOptions);
|
|
217
|
+
if (result === null)
|
|
218
|
+
return null;
|
|
219
|
+
// Serialized: magic-string types `sourcesContent` as
|
|
220
|
+
// `(string | null)[]`, which rollup's map type rejects.
|
|
221
|
+
return { code: result.code, map: result.map.toString() };
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
//# sourceMappingURL=decorator-strip.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decorator-strip.js","sourceRoot":"","sources":["../src/decorator-strip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAyB,MAAM,UAAU,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,oBAAoB,GAAsB,CAAC,8BAA8B,CAAC,CAAC;AAEjF;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,gCAAgC,CAAC;AAoC5D,SAAS,OAAO,CAAC,SAAiB,EAAE,QAAsC;IACxE,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAA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|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
24
|
import { type UnpluginInstance } from "unplugin";
|
|
25
|
+
import { type StripOptions } from "./decorator-strip.js";
|
|
25
26
|
/**
|
|
26
27
|
* A hook that runs before `anvil build` in the plugin lifecycle.
|
|
27
28
|
*
|
|
@@ -120,6 +121,30 @@ export interface AnvilPluginOptions {
|
|
|
120
121
|
* than the entry's own subtree.
|
|
121
122
|
*/
|
|
122
123
|
rootDir?: string;
|
|
124
|
+
/**
|
|
125
|
+
* Remove anvil's and bellows' no-op decorators from source before the
|
|
126
|
+
* bundler transforms it. **On by default**, and you almost certainly want
|
|
127
|
+
* it on.
|
|
128
|
+
*
|
|
129
|
+
* anvil is standard-decorators-only, but oxc — which Rolldown, Vite 6+ and
|
|
130
|
+
* Rspack transform with — implements only the legacy convention. Left to
|
|
131
|
+
* it, a standard decorator either survives into the output, where no JS
|
|
132
|
+
* engine can parse it, or is applied with the legacy calling convention,
|
|
133
|
+
* which corrupts the class. Because anvil's decorators do nothing at
|
|
134
|
+
* runtime, deleting them before the bundler ever sees one sidesteps both.
|
|
135
|
+
*
|
|
136
|
+
* Pass an object to also strip a project's own marker decorators:
|
|
137
|
+
*
|
|
138
|
+
* ```ts
|
|
139
|
+
* anvil({ stripDecorators: { additionalModules: [/\/public-route$/] } })
|
|
140
|
+
* ```
|
|
141
|
+
*
|
|
142
|
+
* Set `false` only if something else in your pipeline already handles
|
|
143
|
+
* standard decorators correctly (a `ts-loader` / `tsc` pre-pass, say).
|
|
144
|
+
*
|
|
145
|
+
* @default true
|
|
146
|
+
*/
|
|
147
|
+
stripDecorators?: boolean | StripOptions;
|
|
123
148
|
/**
|
|
124
149
|
* Hooks that run **before** `anvil build` on every `buildStart`.
|
|
125
150
|
*
|
|
@@ -150,4 +175,5 @@ export interface AnvilPluginOptions {
|
|
|
150
175
|
*/
|
|
151
176
|
export declare const anvilUnplugin: UnpluginInstance<AnvilPluginOptions | undefined, false>;
|
|
152
177
|
export default anvilUnplugin;
|
|
178
|
+
export { stripNoopDecorators, mayContainNoopDecorators, stripDecoratorsUnplugin, type StripOptions, type StripResult, type StripDecoratorsPluginOptions, } from "./decorator-strip.js";
|
|
153
179
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAaH,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAaH,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEjE,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,sBAAsB,CAAC;AAI9B;;;;;;GAMG;AACH,MAAM,WAAW,YAAY;IAC3B,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,8EAA8E;IAC9E,WAAW,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC7C,iDAAiD;IACjD,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,8EAA8E;IAC9E,WAAW,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC7C,iDAAiD;IACjD,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACtB;AAED,gFAAgF;AAChF,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;OAQG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;;;;;;;;;;;;;;;OAgBG;IACH,IAAI,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC;IACzB;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,eAAe,CAAC,EAAE,OAAO,GAAG,YAAY,CAAC;IACzC;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,YAAY,EAAE,CAAC;IAC1B;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;CAC7B;AAED;;;;GAIG;AACH,eAAO,MAAM,aAAa,EAAE,gBAAgB,CAAC,kBAAkB,GAAG,SAAS,EAAE,KAAK,CAiJ9E,CAAC;AAoLL,eAAe,aAAa,CAAC;AAE7B,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,4BAA4B,GAClC,MAAM,sBAAsB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -27,6 +27,7 @@ import path from "node:path";
|
|
|
27
27
|
import { readdirSync, readFileSync, statSync, writeFileSync, existsSync, mkdirSync, } from "node:fs";
|
|
28
28
|
import { createUnplugin } from "unplugin";
|
|
29
29
|
import { resolveBinaryPath, unresolvableBinaryError } from "@anvil-di/anvil-cli";
|
|
30
|
+
import { mayContainNoopDecorators, stripNoopDecorators, } from "./decorator-strip.js";
|
|
30
31
|
const execFileAsync = promisify(execFile);
|
|
31
32
|
/**
|
|
32
33
|
* The unplugin factory. Each per-bundler entry point (`/vite`,
|
|
@@ -46,12 +47,17 @@ export const anvilUnplugin = createUnplugin((rawOptions) => {
|
|
|
46
47
|
debounceMs: rawOptions?.debounceMs ?? 100,
|
|
47
48
|
include: rawOptions?.include ?? ["**/*.ts"],
|
|
48
49
|
mode,
|
|
50
|
+
stripDecorators: rawOptions?.stripDecorators ?? true,
|
|
49
51
|
entries: rawOptions?.entries,
|
|
50
52
|
tsconfig: rawOptions?.tsconfig,
|
|
51
53
|
rootDir: rawOptions?.rootDir,
|
|
52
54
|
preBuild: rawOptions?.preBuild,
|
|
53
55
|
postBuild: rawOptions?.postBuild,
|
|
54
56
|
};
|
|
57
|
+
// `false` disables the transform entirely; `true` means defaults; an
|
|
58
|
+
// object carries the caller's extra no-op modules.
|
|
59
|
+
const stripEnabled = options.stripDecorators !== false;
|
|
60
|
+
const stripOptions = typeof options.stripDecorators === "object" ? options.stripDecorators : {};
|
|
55
61
|
let pending;
|
|
56
62
|
let inFlight;
|
|
57
63
|
// Files that changed during the current debounce window.
|
|
@@ -139,6 +145,25 @@ export const anvilUnplugin = createUnplugin((rawOptions) => {
|
|
|
139
145
|
}
|
|
140
146
|
scheduleRebuild(id);
|
|
141
147
|
},
|
|
148
|
+
// Delete anvil's no-op decorators before the bundler's own TypeScript
|
|
149
|
+
// handling runs. See `stripDecorators` in AnvilPluginOptions for why
|
|
150
|
+
// this is on by default.
|
|
151
|
+
transformInclude(id) {
|
|
152
|
+
if (!stripEnabled)
|
|
153
|
+
return false;
|
|
154
|
+
const file = id.split("?")[0] ?? id;
|
|
155
|
+
return file.endsWith(".ts") || file.endsWith(".tsx");
|
|
156
|
+
},
|
|
157
|
+
transform(code, id) {
|
|
158
|
+
if (!stripEnabled || !mayContainNoopDecorators(code, stripOptions))
|
|
159
|
+
return null;
|
|
160
|
+
const result = stripNoopDecorators(code, id.split("?")[0] ?? id, stripOptions);
|
|
161
|
+
if (result === null)
|
|
162
|
+
return null;
|
|
163
|
+
// Serialized: magic-string types `sourcesContent` as
|
|
164
|
+
// `(string | null)[]`, which rollup's map type rejects.
|
|
165
|
+
return { code: result.code, map: result.map.toString() };
|
|
166
|
+
},
|
|
142
167
|
};
|
|
143
168
|
});
|
|
144
169
|
async function invokeBuild(options) {
|
|
@@ -290,4 +315,5 @@ function tsconfigPathsFrom(tsconfigPath) {
|
|
|
290
315
|
}
|
|
291
316
|
}
|
|
292
317
|
export default anvilUnplugin;
|
|
318
|
+
export { stripNoopDecorators, mayContainNoopDecorators, stripDecoratorsUnplugin, } from "./decorator-strip.js";
|
|
293
319
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,SAAS,GACV,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAyB,MAAM,UAAU,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,SAAS,GACV,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAyB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B,uBAAuB,GAIxB,MAAM,sBAAsB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anvil-di/anvil-unplugin",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
4
4
|
"description": "Run anvil codegen as part of your bundler's normal pipeline. One plugin, every bundler (Vite, Rollup, Webpack, Rspack, esbuild) via unplugin.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.js"
|
|
14
14
|
},
|
|
15
|
+
"./strip": {
|
|
16
|
+
"types": "./dist/decorator-strip.d.ts",
|
|
17
|
+
"import": "./dist/decorator-strip.js"
|
|
18
|
+
},
|
|
15
19
|
"./vite": {
|
|
16
20
|
"types": "./dist/vite.d.ts",
|
|
17
21
|
"import": "./dist/vite.js"
|
|
@@ -38,12 +42,15 @@
|
|
|
38
42
|
"src"
|
|
39
43
|
],
|
|
40
44
|
"dependencies": {
|
|
45
|
+
"magic-string": "^1.1.0",
|
|
46
|
+
"oxc-parser": "^0.143.0",
|
|
41
47
|
"unplugin": "^1.16.0",
|
|
42
|
-
"@anvil-di/anvil-cli": "0.0.
|
|
48
|
+
"@anvil-di/anvil-cli": "0.0.9",
|
|
43
49
|
"@anvil-di/anvil-codegen-wasm": "0.0.4"
|
|
44
50
|
},
|
|
45
51
|
"devDependencies": {
|
|
46
52
|
"@types/node": "^22.10.0",
|
|
53
|
+
"rolldown": "^1.2.0",
|
|
47
54
|
"typescript": "^5.7.2",
|
|
48
55
|
"vitest": "^2.1.8"
|
|
49
56
|
},
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
2
|
+
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { rolldown } from "rolldown";
|
|
7
|
+
import { stripDecoratorsUnplugin } from "./decorator-strip.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The end-to-end claim: a Rolldown bundle of decorated anvil source RUNS.
|
|
11
|
+
*
|
|
12
|
+
* A unit test on the transform cannot show this. oxc's decorator support is
|
|
13
|
+
* legacy-only, so without the plugin the decorators reach the output
|
|
14
|
+
* verbatim and no JS engine will parse them — which is exactly the failure
|
|
15
|
+
* this transform exists to prevent, and exactly what the negative case
|
|
16
|
+
* below pins.
|
|
17
|
+
*
|
|
18
|
+
* The bundle is executed by spawning a real `node`, not by `import()`ing it
|
|
19
|
+
* from the test. That is both a more faithful check of "this ships and
|
|
20
|
+
* runs" and the only portable one: vitest resolves a dynamic import through
|
|
21
|
+
* Vite's module loader, and on Windows the runner's temp directory is an
|
|
22
|
+
* 8.3 short path (`C:\Users\RUNNER~1\...`) whose `~` `pathToFileURL`
|
|
23
|
+
* percent-encodes to `%7E` and the loader never decodes.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
let dir: string;
|
|
27
|
+
|
|
28
|
+
/** Decorator stubs shaped like anvil's: identity, no runtime effect. */
|
|
29
|
+
const STUBS = `export function Controller(_p: string) {
|
|
30
|
+
return <T extends abstract new (...a: never[]) => unknown>(t: T, _c: ClassDecoratorContext<T>): T => t;
|
|
31
|
+
}
|
|
32
|
+
export function Get(_p: string) {
|
|
33
|
+
return <This, A extends readonly unknown[], R>(
|
|
34
|
+
t: (this: This, ...a: A) => R,
|
|
35
|
+
_c: ClassMethodDecoratorContext<This, (this: This, ...a: A) => R>,
|
|
36
|
+
) => t;
|
|
37
|
+
}
|
|
38
|
+
export function Inject<T extends abstract new (...a: never[]) => unknown>(
|
|
39
|
+
t: T,
|
|
40
|
+
_c: ClassDecoratorContext<T>,
|
|
41
|
+
): T {
|
|
42
|
+
return t;
|
|
43
|
+
}
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Self-executing on purpose: the bundle's own top-level statement is what
|
|
48
|
+
* proves the decorated classes survived and still behave, so `node
|
|
49
|
+
* index.mjs` is the whole assertion.
|
|
50
|
+
*/
|
|
51
|
+
const SOURCE = `import { Controller, Get, Inject } from "@anvil-di/bellows";
|
|
52
|
+
|
|
53
|
+
@Inject
|
|
54
|
+
export class Greeter {
|
|
55
|
+
greet(name: string): string {
|
|
56
|
+
return "hello " + name;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
@Controller("/calls")
|
|
61
|
+
export class CallsController {
|
|
62
|
+
constructor(private readonly greeter: Greeter) {}
|
|
63
|
+
|
|
64
|
+
@Get("/:id")
|
|
65
|
+
findOne(id: string): string {
|
|
66
|
+
return this.greeter.greet(id);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
console.log(new CallsController(new Greeter()).findOne("world"));
|
|
71
|
+
`;
|
|
72
|
+
|
|
73
|
+
beforeAll(() => {
|
|
74
|
+
dir = mkdtempSync(path.join(tmpdir(), "anvil-strip-"));
|
|
75
|
+
mkdirSync(path.join(dir, "src"), { recursive: true });
|
|
76
|
+
writeFileSync(path.join(dir, "src", "stubs.ts"), STUBS, "utf8");
|
|
77
|
+
writeFileSync(path.join(dir, "src", "index.ts"), SOURCE, "utf8");
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
afterAll(() => {
|
|
81
|
+
rmSync(dir, { recursive: true, force: true });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Bundle `src/index.ts`, resolving the bare `@anvil-di/bellows` specifier to
|
|
86
|
+
* the local stub file so the fixture needs no installed dependency.
|
|
87
|
+
*
|
|
88
|
+
* Emitted as `.mjs` so Node reads it as ESM without a package.json marker.
|
|
89
|
+
*/
|
|
90
|
+
async function bundle(withPlugin: boolean, outName: string): Promise<string> {
|
|
91
|
+
const aliasStubs = {
|
|
92
|
+
name: "alias-stubs",
|
|
93
|
+
resolveId(source: string) {
|
|
94
|
+
return source === "@anvil-di/bellows" ? path.join(dir, "src", "stubs.ts") : null;
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
const plugins = withPlugin ? [aliasStubs, stripDecoratorsUnplugin.rolldown()] : [aliasStubs];
|
|
98
|
+
const build = await rolldown({
|
|
99
|
+
input: path.join(dir, "src", "index.ts"),
|
|
100
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
101
|
+
plugins: plugins as any,
|
|
102
|
+
logLevel: "silent",
|
|
103
|
+
});
|
|
104
|
+
const outDir = path.join(dir, outName);
|
|
105
|
+
await build.write({ dir: outDir, format: "esm", entryFileNames: "index.mjs" });
|
|
106
|
+
await build.close();
|
|
107
|
+
return path.join(outDir, "index.mjs");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Execute a bundle with the same Node that is running the tests. */
|
|
111
|
+
function runInNode(entry: string): { status: number | null; stdout: string; stderr: string } {
|
|
112
|
+
const result = spawnSync(process.execPath, [entry], { encoding: "utf8" });
|
|
113
|
+
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
describe("stripDecoratorsUnplugin (rolldown, end to end)", () => {
|
|
117
|
+
it("produces a bundle that node runs", async () => {
|
|
118
|
+
const out = await bundle(true, "dist-stripped");
|
|
119
|
+
const { status, stdout, stderr } = runInNode(out);
|
|
120
|
+
// stderr rides along as the failure message rather than as its own
|
|
121
|
+
// assertion, so an unrelated node warning cannot fail the test but a
|
|
122
|
+
// real crash still shows its stack.
|
|
123
|
+
expect(status, stderr).toBe(0);
|
|
124
|
+
expect(stdout.trim()).toBe("hello world");
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("emits no decorator syntax and no decorator helpers", async () => {
|
|
128
|
+
const out = await bundle(true, "dist-clean");
|
|
129
|
+
const code = readFileSync(out, "utf8");
|
|
130
|
+
expect(code).not.toMatch(/(?:^|[\s{;(])@[A-Za-z_$]/m);
|
|
131
|
+
expect(code).not.toContain("__esDecorate");
|
|
132
|
+
expect(code).not.toContain("__runInitializers");
|
|
133
|
+
expect(code).not.toContain("__decorate");
|
|
134
|
+
// The stubs are dead once nothing references them.
|
|
135
|
+
expect(code).not.toContain("function Controller");
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("WITHOUT the plugin, node cannot even parse the same bundle", async () => {
|
|
139
|
+
const out = await bundle(false, "dist-raw");
|
|
140
|
+
const { status, stderr } = runInNode(out);
|
|
141
|
+
expect(status).not.toBe(0);
|
|
142
|
+
expect(stderr).toMatch(/SyntaxError/);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { mayContainNoopDecorators, stripNoopDecorators } from "./decorator-strip.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The load-bearing property of this package is not "decorators disappear" —
|
|
6
|
+
* it is "*only anvil's* decorators disappear". A blanket strip would be a
|
|
7
|
+
* silent correctness bug in any project that also uses a decorator with real
|
|
8
|
+
* runtime behaviour, so most of what follows pins the boundary rather than
|
|
9
|
+
* the happy path.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const strip = (code: string, id = "input.ts"): ReturnType<typeof stripNoopDecorators> =>
|
|
13
|
+
stripNoopDecorators(code, id);
|
|
14
|
+
|
|
15
|
+
describe("stripNoopDecorators", () => {
|
|
16
|
+
it("removes class and method decorators imported from bellows", () => {
|
|
17
|
+
const result = strip(`import { Controller, Get } from "@anvil-di/bellows";
|
|
18
|
+
@Controller("/calls")
|
|
19
|
+
export class CallsController {
|
|
20
|
+
@Get("/:id") async findOne(id: string): Promise<string> { return id; }
|
|
21
|
+
}`);
|
|
22
|
+
expect(result?.removed).toBe(2);
|
|
23
|
+
expect(result?.code).not.toContain("@Controller");
|
|
24
|
+
expect(result?.code).not.toContain("@Get");
|
|
25
|
+
// The class itself, and everything in it, must survive verbatim.
|
|
26
|
+
expect(result?.code).toContain("export class CallsController");
|
|
27
|
+
expect(result?.code).toContain("async findOne(id: string): Promise<string> { return id; }");
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("removes anvil's module/provider decorators", () => {
|
|
31
|
+
const result = strip(`import { Module, Provides, Singleton } from "@anvil-di/anvil";
|
|
32
|
+
@Module
|
|
33
|
+
export class CoffeeModule {
|
|
34
|
+
@Singleton @Provides static providePump(): Pump { return new Pump(); }
|
|
35
|
+
}`);
|
|
36
|
+
expect(result?.removed).toBe(3);
|
|
37
|
+
expect(result?.code).toContain("static providePump(): Pump");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("resolves aliased imports", () => {
|
|
41
|
+
const result = strip(`import { Inject as I } from "@anvil-di/anvil";
|
|
42
|
+
@I export class Pump {}`);
|
|
43
|
+
expect(result?.removed).toBe(1);
|
|
44
|
+
expect(result?.code).toContain("export class Pump {}");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("resolves namespace imports through the object, not the property", () => {
|
|
48
|
+
const result = strip(`import * as anvil from "@anvil-di/anvil";
|
|
49
|
+
@anvil.Inject export class Pump {}`);
|
|
50
|
+
expect(result?.removed).toBe(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("leaves a decorator from any other package alone", () => {
|
|
54
|
+
const result = strip(`import { Controller } from "@anvil-di/bellows";
|
|
55
|
+
import { observable } from "mobx";
|
|
56
|
+
@Controller("/x") export class C { @observable count = 1; }`);
|
|
57
|
+
expect(result?.removed).toBe(1);
|
|
58
|
+
expect(result?.code).not.toContain("@Controller");
|
|
59
|
+
// The whole point: a decorator with real behaviour survives.
|
|
60
|
+
expect(result?.code).toContain("@observable count = 1");
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("leaves a same-named decorator that came from somewhere else", () => {
|
|
64
|
+
// `Get` here is a local helper, not bellows'. Name-based matching would
|
|
65
|
+
// delete it; binding-based matching must not.
|
|
66
|
+
const result = strip(`import { Get } from "./my-own-decorators.js";
|
|
67
|
+
@Get("/x") export class C {}`);
|
|
68
|
+
expect(result).toBeNull();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("ignores a type-only import", () => {
|
|
72
|
+
const result = strip(`import type { Validator } from "@anvil-di/bellows";
|
|
73
|
+
export type V = Validator<string>;`);
|
|
74
|
+
expect(result).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("returns null when there is nothing to strip", () => {
|
|
78
|
+
expect(strip(`export const x = 1;`)).toBeNull();
|
|
79
|
+
expect(strip(`import { Token } from "@anvil-di/anvil";\nexport const t = Token;`)).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("throws with the file name when the source does not parse", () => {
|
|
83
|
+
expect(() => strip(`@Controller( export class {`, "broken.ts")).toThrow(/broken\.ts/);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("parses tsx by extension", () => {
|
|
87
|
+
const result = strip(
|
|
88
|
+
`import { Inject } from "@anvil-di/anvil";
|
|
89
|
+
@Inject export class W { render() { return <div className="x" />; } }`,
|
|
90
|
+
"widget.tsx",
|
|
91
|
+
);
|
|
92
|
+
expect(result?.removed).toBe(1);
|
|
93
|
+
expect(result?.code).toContain("<div className=\"x\" />");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("accepts additional no-op modules for a project's own markers", () => {
|
|
97
|
+
const code = `import { Public } from "../http/public-route.js";
|
|
98
|
+
import { Controller } from "@anvil-di/bellows";
|
|
99
|
+
@Controller("/auth") export class AuthController {
|
|
100
|
+
@Public("login runs before a session exists") login() {}
|
|
101
|
+
}`;
|
|
102
|
+
// Without the opt-in, the project's own marker is left in place...
|
|
103
|
+
expect(stripNoopDecorators(code, "auth.ts")?.removed).toBe(1);
|
|
104
|
+
// ...and with it, both go.
|
|
105
|
+
const opted = stripNoopDecorators(code, "auth.ts", {
|
|
106
|
+
additionalModules: [/(?:^|\/)http\/public-route(?:\.js)?$/],
|
|
107
|
+
});
|
|
108
|
+
expect(opted?.removed).toBe(2);
|
|
109
|
+
expect(opted?.code).not.toContain("@Public");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("matches an additional module given as an exact string", () => {
|
|
113
|
+
const result = stripNoopDecorators(
|
|
114
|
+
`import { Marker } from "#markers";\n@Marker export class C {}`,
|
|
115
|
+
"a.ts",
|
|
116
|
+
{ additionalModules: ["#markers"] },
|
|
117
|
+
);
|
|
118
|
+
expect(result?.removed).toBe(1);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("produces a source map covering the removals", () => {
|
|
122
|
+
const result = strip(`import { Inject } from "@anvil-di/anvil";
|
|
123
|
+
@Inject
|
|
124
|
+
export class Pump {}`);
|
|
125
|
+
expect(result?.map.mappings).toBeTruthy();
|
|
126
|
+
expect(result?.map.sources).toContain("input.ts");
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("mayContainNoopDecorators", () => {
|
|
131
|
+
it("rejects files with no decorator syntax at all", () => {
|
|
132
|
+
expect(mayContainNoopDecorators(`import { x } from "@anvil-di/anvil";`)).toBe(false);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("rejects decorator files that never mention a no-op module", () => {
|
|
136
|
+
expect(mayContainNoopDecorators(`import { o } from "mobx";\n@o class C {}`)).toBe(false);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("accepts a file importing anvil and using a decorator", () => {
|
|
140
|
+
expect(mayContainNoopDecorators(`import { Inject } from "@anvil-di/anvil";\n@Inject class C {}`)).toBe(
|
|
141
|
+
true,
|
|
142
|
+
);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("never gives a false negative for anything the stripper would strip", () => {
|
|
146
|
+
const cases = [
|
|
147
|
+
`import { Controller } from "@anvil-di/bellows";\n@Controller("/x") class C {}`,
|
|
148
|
+
`import { Inject as I } from "@anvil-di/anvil";\n@I class C {}`,
|
|
149
|
+
`import * as a from "@anvil-di/anvil";\n@a.Inject class C {}`,
|
|
150
|
+
`class C { @Get("/x") f() {} }\nimport { Get } from "@anvil-di/bellows";`,
|
|
151
|
+
];
|
|
152
|
+
for (const code of cases) {
|
|
153
|
+
if (stripNoopDecorators(code, "c.ts") !== null) {
|
|
154
|
+
expect(mayContainNoopDecorators(code)).toBe(true);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("treats any decorator file as a candidate once a RegExp module is configured", () => {
|
|
160
|
+
const code = `import { Marker } from "./m.js";\n@Marker class C {}`;
|
|
161
|
+
expect(mayContainNoopDecorators(code)).toBe(false);
|
|
162
|
+
expect(mayContainNoopDecorators(code, { additionalModules: [/m\.js$/] })).toBe(true);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { parseSync } from "oxc-parser";
|
|
2
|
+
import MagicString from "magic-string";
|
|
3
|
+
import { createUnplugin, type UnpluginInstance } from "unplugin";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Modules whose every export is a decorator with no runtime behaviour.
|
|
7
|
+
*
|
|
8
|
+
* Both anvil packages qualify by construction: their decorators are stubs
|
|
9
|
+
* that `return target`, and all semantics are read out of the source by the
|
|
10
|
+
* Rust toolchain during codegen. This is invariant #1 of the project —
|
|
11
|
+
* "No runtime reflection. Decorators are no-ops at runtime."
|
|
12
|
+
*/
|
|
13
|
+
const DEFAULT_NOOP_MODULES: readonly RegExp[] = [/^@anvil-di\/(anvil|bellows)$/];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A decorator-shaped token: `@Name` at a position where one can legally
|
|
17
|
+
* appear. Used only by {@link mayContainNoopDecorators}; a JSDoc `@param`
|
|
18
|
+
* can match, which costs a parse and nothing else.
|
|
19
|
+
*/
|
|
20
|
+
const DECORATOR_TOKEN_RE = /(?:^|[\s{;(])@[A-Za-z_$][\w$]*/;
|
|
21
|
+
|
|
22
|
+
/** Options for {@link stripNoopDecorators}. */
|
|
23
|
+
export interface StripOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Additional modules whose decorators are known to be no-ops, beyond
|
|
26
|
+
* `@anvil-di/anvil` and `@anvil-di/bellows`.
|
|
27
|
+
*
|
|
28
|
+
* A string matches a module specifier exactly; a RegExp is tested against
|
|
29
|
+
* it. Use this for a project's own marker decorators — a `@Public(reason)`
|
|
30
|
+
* that exists only so `anvil-bellows` can read it at codegen time, for
|
|
31
|
+
* instance. Relative specifiers are matched as written in the importing
|
|
32
|
+
* file, so prefer a RegExp: `/(?:^|\/)http\/public-route(?:\.js)?$/`.
|
|
33
|
+
*
|
|
34
|
+
* Adding a module here asserts that none of its decorators do anything at
|
|
35
|
+
* runtime. That claim is not checked; get it wrong and behaviour is
|
|
36
|
+
* silently dropped.
|
|
37
|
+
*/
|
|
38
|
+
additionalModules?: readonly (string | RegExp)[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The result of a successful strip. */
|
|
42
|
+
export interface StripResult {
|
|
43
|
+
/** Source with the no-op decorators removed. */
|
|
44
|
+
code: string;
|
|
45
|
+
/** Source map for the removals, as returned by magic-string. */
|
|
46
|
+
map: ReturnType<MagicString["generateMap"]>;
|
|
47
|
+
/** How many decorators were removed. */
|
|
48
|
+
removed: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface EstreeNode {
|
|
52
|
+
type?: string;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function matches(specifier: string, patterns: readonly (string | RegExp)[]): boolean {
|
|
57
|
+
return patterns.some((p) => (typeof p === "string" ? p === specifier : p.test(specifier)));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Local names introduced by imports from a no-op decorator module, honouring
|
|
62
|
+
* aliases (`import { Inject as I }`). Namespace imports are tracked apart so
|
|
63
|
+
* `@anvil.Inject` resolves through its object rather than its property.
|
|
64
|
+
*/
|
|
65
|
+
function noopBindings(
|
|
66
|
+
program: EstreeNode,
|
|
67
|
+
patterns: readonly (string | RegExp)[],
|
|
68
|
+
): { named: Set<string>; namespaces: Set<string> } {
|
|
69
|
+
const named = new Set<string>();
|
|
70
|
+
const namespaces = new Set<string>();
|
|
71
|
+
for (const node of (program["body"] as EstreeNode[] | undefined) ?? []) {
|
|
72
|
+
if (node.type !== "ImportDeclaration") continue;
|
|
73
|
+
// `import type { ... }` contributes no runtime binding, so it can never
|
|
74
|
+
// be the callee of a decorator.
|
|
75
|
+
if (node["importKind"] === "type") continue;
|
|
76
|
+
const source = node["source"] as { value?: string } | undefined;
|
|
77
|
+
if (source?.value === undefined || !matches(source.value, patterns)) continue;
|
|
78
|
+
for (const spec of (node["specifiers"] as EstreeNode[] | undefined) ?? []) {
|
|
79
|
+
if (spec["importKind"] === "type") continue;
|
|
80
|
+
const local = (spec["local"] as { name?: string } | undefined)?.name;
|
|
81
|
+
if (local === undefined) continue;
|
|
82
|
+
if (spec.type === "ImportNamespaceSpecifier") namespaces.add(local);
|
|
83
|
+
else named.add(local);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { named, namespaces };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The identifier a decorator dispatches on: `@A`, `@A(x)`, `@ns.A`, `@ns.A(x)`. */
|
|
90
|
+
function decoratorRoot(
|
|
91
|
+
expression: EstreeNode,
|
|
92
|
+
): { kind: "named" | "member"; name: string } | null {
|
|
93
|
+
let expr = expression;
|
|
94
|
+
if (expr.type === "CallExpression") expr = expr["callee"] as EstreeNode;
|
|
95
|
+
if (expr.type === "Identifier") return { kind: "named", name: expr["name"] as string };
|
|
96
|
+
if (expr.type === "MemberExpression" && expr["computed"] !== true) {
|
|
97
|
+
const object = expr["object"] as EstreeNode;
|
|
98
|
+
if (object.type === "Identifier") return { kind: "member", name: object["name"] as string };
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function walk(node: unknown, visit: (node: EstreeNode) => void): void {
|
|
104
|
+
if (node === null || typeof node !== "object") return;
|
|
105
|
+
if (Array.isArray(node)) {
|
|
106
|
+
for (const child of node) walk(child, visit);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const candidate = node as EstreeNode;
|
|
110
|
+
if (typeof candidate.type === "string") visit(candidate);
|
|
111
|
+
for (const key of Object.keys(candidate)) {
|
|
112
|
+
if (key === "type") continue;
|
|
113
|
+
walk(candidate[key], visit);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Delete every decorator that resolves to a no-op decorator module.
|
|
119
|
+
*
|
|
120
|
+
* Returns `null` when there is nothing to do — no such import, or no such
|
|
121
|
+
* decorator — so callers can hand the original source and its existing
|
|
122
|
+
* source map straight through.
|
|
123
|
+
*
|
|
124
|
+
* ## Why deleting is correct
|
|
125
|
+
*
|
|
126
|
+
* anvil's and bellows' decorators are identity functions: `@Provides`,
|
|
127
|
+
* `@Controller`, `@Get` and the rest all `return target`. They exist so user
|
|
128
|
+
* code typechecks and so the Rust toolchain can read the wiring out of the
|
|
129
|
+
* source during `anvil build` / `anvil-bellows`, which happens before any
|
|
130
|
+
* bundler runs. Nothing observable happens when they are applied, so
|
|
131
|
+
* removing them produces the same program without the
|
|
132
|
+
* `__esDecorate`/`__runInitializers` machinery a real emit would inline.
|
|
133
|
+
*
|
|
134
|
+
* ## Why it is needed
|
|
135
|
+
*
|
|
136
|
+
* oxc's decorator transform implements only the legacy
|
|
137
|
+
* (`experimentalDecorators`) convention, which anvil forbids. Left alone,
|
|
138
|
+
* standard decorators pass through a bundle verbatim and no JS engine can
|
|
139
|
+
* parse them; transformed as legacy, method decorators are called with the
|
|
140
|
+
* wrong signature and corrupt the class. Routing the affected files through
|
|
141
|
+
* `tsc` sidesteps both, at the cost of a dependency on TypeScript's JS
|
|
142
|
+
* compiler API — which TypeScript 7 does not ship.
|
|
143
|
+
*
|
|
144
|
+
* ## Safety
|
|
145
|
+
*
|
|
146
|
+
* Only decorators whose binding comes from a listed module are removed.
|
|
147
|
+
* Anything else is left exactly where it is, so a decorator with real
|
|
148
|
+
* behaviour survives into the output and fails loudly rather than being
|
|
149
|
+
* silently dropped.
|
|
150
|
+
*
|
|
151
|
+
* @param code source text of a `.ts` / `.tsx` file
|
|
152
|
+
* @param id file path, used for parser mode selection and diagnostics
|
|
153
|
+
*/
|
|
154
|
+
export function stripNoopDecorators(
|
|
155
|
+
code: string,
|
|
156
|
+
id: string,
|
|
157
|
+
options: StripOptions = {},
|
|
158
|
+
): StripResult | null {
|
|
159
|
+
const patterns: readonly (string | RegExp)[] = [
|
|
160
|
+
...DEFAULT_NOOP_MODULES,
|
|
161
|
+
...(options.additionalModules ?? []),
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
const parsed = parseSync(id, code, { lang: id.endsWith(".tsx") ? "tsx" : "ts" });
|
|
165
|
+
if (parsed.errors.length > 0) {
|
|
166
|
+
throw new Error(`strip-decorators: cannot parse ${id}: ${parsed.errors[0]?.message ?? ""}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const program = parsed.program as unknown as EstreeNode;
|
|
170
|
+
const { named, namespaces } = noopBindings(program, patterns);
|
|
171
|
+
if (named.size === 0 && namespaces.size === 0) return null;
|
|
172
|
+
|
|
173
|
+
const ranges: Array<[number, number]> = [];
|
|
174
|
+
walk(program, (node) => {
|
|
175
|
+
if (node.type !== "Decorator") return;
|
|
176
|
+
const root = decoratorRoot(node["expression"] as EstreeNode);
|
|
177
|
+
if (root === null) return;
|
|
178
|
+
const owned = root.kind === "named" ? named.has(root.name) : namespaces.has(root.name);
|
|
179
|
+
if (owned) ranges.push([node["start"] as number, node["end"] as number]);
|
|
180
|
+
});
|
|
181
|
+
if (ranges.length === 0) return null;
|
|
182
|
+
|
|
183
|
+
const s = new MagicString(code);
|
|
184
|
+
for (const [start, end] of ranges) s.remove(start, end);
|
|
185
|
+
return {
|
|
186
|
+
code: s.toString(),
|
|
187
|
+
map: s.generateMap({ source: id, hires: true }),
|
|
188
|
+
removed: ranges.length,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Cheap pre-filter, so a bundler can skip parsing files that cannot possibly
|
|
194
|
+
* contain a strippable decorator.
|
|
195
|
+
*
|
|
196
|
+
* Conservative by construction: never a false negative, and a false positive
|
|
197
|
+
* costs only a wasted parse. A `RegExp` in `additionalModules` is written to
|
|
198
|
+
* match a module specifier, so it cannot be tested against whole source text
|
|
199
|
+
* — any file with decorator syntax counts as a candidate when one is set.
|
|
200
|
+
*/
|
|
201
|
+
export function mayContainNoopDecorators(code: string, options: StripOptions = {}): boolean {
|
|
202
|
+
if (!DECORATOR_TOKEN_RE.test(code)) return false;
|
|
203
|
+
if (code.includes("@anvil-di/anvil") || code.includes("@anvil-di/bellows")) return true;
|
|
204
|
+
for (const pattern of options.additionalModules ?? []) {
|
|
205
|
+
if (typeof pattern === "string") {
|
|
206
|
+
if (code.includes(pattern)) return true;
|
|
207
|
+
} else {
|
|
208
|
+
// A specifier pattern cannot be matched against whole source text.
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Options for the standalone decorator-strip plugin. */
|
|
216
|
+
export interface StripDecoratorsPluginOptions extends StripOptions {
|
|
217
|
+
/**
|
|
218
|
+
* File extensions the transform applies to. Defaults to `.ts` and `.tsx`.
|
|
219
|
+
*/
|
|
220
|
+
extensions?: readonly string[];
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const DEFAULT_EXTENSIONS = [".ts", ".tsx"] as const;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The decorator strip on its own, without anvil's codegen hooks — for a
|
|
227
|
+
* project that already runs `anvil build` / `anvil-bellows` its own way
|
|
228
|
+
* (a `gen` npm script, say) and only needs its bundle to come out
|
|
229
|
+
* runnable.
|
|
230
|
+
*
|
|
231
|
+
* ```ts
|
|
232
|
+
* // rolldown.config.ts
|
|
233
|
+
* import { stripDecoratorsUnplugin } from "@anvil-di/anvil-unplugin/strip";
|
|
234
|
+
*
|
|
235
|
+
* export default { plugins: [stripDecoratorsUnplugin.rolldown()] };
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* Projects using the main `anvilUnplugin` get this already; see its
|
|
239
|
+
* `stripDecorators` option.
|
|
240
|
+
*/
|
|
241
|
+
export const stripDecoratorsUnplugin: UnpluginInstance<
|
|
242
|
+
StripDecoratorsPluginOptions | undefined,
|
|
243
|
+
false
|
|
244
|
+
> = createUnplugin<StripDecoratorsPluginOptions | undefined>((rawOptions) => {
|
|
245
|
+
const extensions = rawOptions?.extensions ?? DEFAULT_EXTENSIONS;
|
|
246
|
+
const stripOptions: StripOptions =
|
|
247
|
+
rawOptions?.additionalModules === undefined
|
|
248
|
+
? {}
|
|
249
|
+
: { additionalModules: rawOptions.additionalModules };
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
name: "anvil-strip-decorators",
|
|
253
|
+
// `id` carries a query suffix in some bundlers (`?used`, `?vue&type=...`);
|
|
254
|
+
// compare against the path portion only.
|
|
255
|
+
transformInclude(id: string) {
|
|
256
|
+
const file = id.split("?")[0] ?? id;
|
|
257
|
+
return extensions.some((ext) => file.endsWith(ext));
|
|
258
|
+
},
|
|
259
|
+
transform(code: string, id: string) {
|
|
260
|
+
if (!mayContainNoopDecorators(code, stripOptions)) return null;
|
|
261
|
+
const result = stripNoopDecorators(code, id.split("?")[0] ?? id, stripOptions);
|
|
262
|
+
if (result === null) return null;
|
|
263
|
+
// Serialized: magic-string types `sourcesContent` as
|
|
264
|
+
// `(string | null)[]`, which rollup's map type rejects.
|
|
265
|
+
return { code: result.code, map: result.map.toString() };
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -35,6 +35,11 @@ import {
|
|
|
35
35
|
} from "node:fs";
|
|
36
36
|
import { createUnplugin, type UnpluginInstance } from "unplugin";
|
|
37
37
|
import { resolveBinaryPath, unresolvableBinaryError } from "@anvil-di/anvil-cli";
|
|
38
|
+
import {
|
|
39
|
+
mayContainNoopDecorators,
|
|
40
|
+
stripNoopDecorators,
|
|
41
|
+
type StripOptions,
|
|
42
|
+
} from "./decorator-strip.js";
|
|
38
43
|
|
|
39
44
|
const execFileAsync = promisify(execFile);
|
|
40
45
|
|
|
@@ -138,6 +143,30 @@ export interface AnvilPluginOptions {
|
|
|
138
143
|
* than the entry's own subtree.
|
|
139
144
|
*/
|
|
140
145
|
rootDir?: string;
|
|
146
|
+
/**
|
|
147
|
+
* Remove anvil's and bellows' no-op decorators from source before the
|
|
148
|
+
* bundler transforms it. **On by default**, and you almost certainly want
|
|
149
|
+
* it on.
|
|
150
|
+
*
|
|
151
|
+
* anvil is standard-decorators-only, but oxc — which Rolldown, Vite 6+ and
|
|
152
|
+
* Rspack transform with — implements only the legacy convention. Left to
|
|
153
|
+
* it, a standard decorator either survives into the output, where no JS
|
|
154
|
+
* engine can parse it, or is applied with the legacy calling convention,
|
|
155
|
+
* which corrupts the class. Because anvil's decorators do nothing at
|
|
156
|
+
* runtime, deleting them before the bundler ever sees one sidesteps both.
|
|
157
|
+
*
|
|
158
|
+
* Pass an object to also strip a project's own marker decorators:
|
|
159
|
+
*
|
|
160
|
+
* ```ts
|
|
161
|
+
* anvil({ stripDecorators: { additionalModules: [/\/public-route$/] } })
|
|
162
|
+
* ```
|
|
163
|
+
*
|
|
164
|
+
* Set `false` only if something else in your pipeline already handles
|
|
165
|
+
* standard decorators correctly (a `ts-loader` / `tsc` pre-pass, say).
|
|
166
|
+
*
|
|
167
|
+
* @default true
|
|
168
|
+
*/
|
|
169
|
+
stripDecorators?: boolean | StripOptions;
|
|
141
170
|
/**
|
|
142
171
|
* Hooks that run **before** `anvil build` on every `buildStart`.
|
|
143
172
|
*
|
|
@@ -186,6 +215,7 @@ export const anvilUnplugin: UnpluginInstance<AnvilPluginOptions | undefined, fal
|
|
|
186
215
|
debounceMs: rawOptions?.debounceMs ?? 100,
|
|
187
216
|
include: rawOptions?.include ?? ["**/*.ts"],
|
|
188
217
|
mode,
|
|
218
|
+
stripDecorators: rawOptions?.stripDecorators ?? true,
|
|
189
219
|
entries: rawOptions?.entries,
|
|
190
220
|
tsconfig: rawOptions?.tsconfig,
|
|
191
221
|
rootDir: rawOptions?.rootDir,
|
|
@@ -193,6 +223,12 @@ export const anvilUnplugin: UnpluginInstance<AnvilPluginOptions | undefined, fal
|
|
|
193
223
|
postBuild: rawOptions?.postBuild,
|
|
194
224
|
};
|
|
195
225
|
|
|
226
|
+
// `false` disables the transform entirely; `true` means defaults; an
|
|
227
|
+
// object carries the caller's extra no-op modules.
|
|
228
|
+
const stripEnabled = options.stripDecorators !== false;
|
|
229
|
+
const stripOptions: StripOptions =
|
|
230
|
+
typeof options.stripDecorators === "object" ? options.stripDecorators : {};
|
|
231
|
+
|
|
196
232
|
let pending: NodeJS.Timeout | undefined;
|
|
197
233
|
let inFlight: Promise<void> | undefined;
|
|
198
234
|
// Files that changed during the current debounce window.
|
|
@@ -288,6 +324,22 @@ export const anvilUnplugin: UnpluginInstance<AnvilPluginOptions | undefined, fal
|
|
|
288
324
|
}
|
|
289
325
|
scheduleRebuild(id);
|
|
290
326
|
},
|
|
327
|
+
// Delete anvil's no-op decorators before the bundler's own TypeScript
|
|
328
|
+
// handling runs. See `stripDecorators` in AnvilPluginOptions for why
|
|
329
|
+
// this is on by default.
|
|
330
|
+
transformInclude(id: string) {
|
|
331
|
+
if (!stripEnabled) return false;
|
|
332
|
+
const file = id.split("?")[0] ?? id;
|
|
333
|
+
return file.endsWith(".ts") || file.endsWith(".tsx");
|
|
334
|
+
},
|
|
335
|
+
transform(code: string, id: string) {
|
|
336
|
+
if (!stripEnabled || !mayContainNoopDecorators(code, stripOptions)) return null;
|
|
337
|
+
const result = stripNoopDecorators(code, id.split("?")[0] ?? id, stripOptions);
|
|
338
|
+
if (result === null) return null;
|
|
339
|
+
// Serialized: magic-string types `sourcesContent` as
|
|
340
|
+
// `(string | null)[]`, which rollup's map type rejects.
|
|
341
|
+
return { code: result.code, map: result.map.toString() };
|
|
342
|
+
},
|
|
291
343
|
};
|
|
292
344
|
});
|
|
293
345
|
|
|
@@ -470,3 +522,12 @@ function tsconfigPathsFrom(tsconfigPath: string): {
|
|
|
470
522
|
}
|
|
471
523
|
|
|
472
524
|
export default anvilUnplugin;
|
|
525
|
+
|
|
526
|
+
export {
|
|
527
|
+
stripNoopDecorators,
|
|
528
|
+
mayContainNoopDecorators,
|
|
529
|
+
stripDecoratorsUnplugin,
|
|
530
|
+
type StripOptions,
|
|
531
|
+
type StripResult,
|
|
532
|
+
type StripDecoratorsPluginOptions,
|
|
533
|
+
} from "./decorator-strip.js";
|