@macroforge/mcp-server 0.1.40 → 0.1.49

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.
Files changed (71) hide show
  1. package/LICENSE +22 -0
  2. package/docs/BOOK.md +165 -0
  3. package/docs/api/api-overview.md +65 -46
  4. package/docs/api/expand-sync.md +88 -53
  5. package/docs/api/native-plugin.md +121 -71
  6. package/docs/api/position-mapper.md +114 -54
  7. package/docs/api/transform-sync.md +85 -59
  8. package/docs/builtin-macros/clone.md +0 -20
  9. package/docs/builtin-macros/debug.md +0 -23
  10. package/docs/builtin-macros/default.md +1 -40
  11. package/docs/builtin-macros/deserialize/example.md +8 -1416
  12. package/docs/builtin-macros/deserialize.md +8 -1416
  13. package/docs/builtin-macros/hash.md +0 -42
  14. package/docs/builtin-macros/macros-overview/detailed-documentation.md +13 -0
  15. package/docs/builtin-macros/macros-overview/enum-support.md +30 -0
  16. package/docs/builtin-macros/macros-overview/interface-support.md +28 -0
  17. package/docs/builtin-macros/macros-overview/overview.md +36 -0
  18. package/docs/builtin-macros/macros-overview/type-alias-support.md +62 -0
  19. package/docs/builtin-macros/macros-overview.md +171 -130
  20. package/docs/builtin-macros/ord.md +0 -25
  21. package/docs/builtin-macros/partial-eq.md +0 -84
  22. package/docs/builtin-macros/partial-ord.md +11 -43
  23. package/docs/builtin-macros/serialize.md +2 -62
  24. package/docs/concepts/architecture.md +125 -48
  25. package/docs/concepts/derive-system/built-in-vs-custom-macros.md +13 -0
  26. package/docs/concepts/derive-system/overview.md +200 -0
  27. package/docs/concepts/derive-system.md +171 -97
  28. package/docs/concepts/how-macros-work.md +89 -37
  29. package/docs/custom-macros/custom-overview.md +79 -57
  30. package/docs/custom-macros/rust-setup.md +138 -99
  31. package/docs/custom-macros/ts-macro-derive/accessing-field-data.md +40 -31
  32. package/docs/custom-macros/ts-macro-derive/adding-imports.md +14 -11
  33. package/docs/custom-macros/ts-macro-derive/attribute-options.md +20 -25
  34. package/docs/custom-macros/ts-macro-derive/complete-example.md +40 -38
  35. package/docs/custom-macros/ts-macro-derive/deriveinput-structure.md +49 -47
  36. package/docs/custom-macros/ts-macro-derive/function-signature.md +12 -0
  37. package/docs/custom-macros/ts-macro-derive/overview.md +9 -7
  38. package/docs/custom-macros/ts-macro-derive/parsing-input.md +20 -18
  39. package/docs/custom-macros/ts-macro-derive/returning-errors.md +15 -13
  40. package/docs/custom-macros/ts-macro-derive.md +322 -228
  41. package/docs/custom-macros/ts-quote/backtick-template-literals.md +19 -7
  42. package/docs/custom-macros/ts-quote/comments-and.md +56 -22
  43. package/docs/custom-macros/ts-quote/complete-example-json-derive-macro.md +89 -98
  44. package/docs/custom-macros/ts-quote/conditionals-ifif.md +35 -29
  45. package/docs/custom-macros/ts-quote/identifier-concatenation-content.md +30 -22
  46. package/docs/custom-macros/ts-quote/iteration-for.md +48 -40
  47. package/docs/custom-macros/ts-quote/local-constants-let.md +23 -21
  48. package/docs/custom-macros/ts-quote/match-expressions-match.md +46 -38
  49. package/docs/custom-macros/ts-quote/overview.md +5 -10
  50. package/docs/custom-macros/ts-quote/pattern-matching-iflet.md +39 -0
  51. package/docs/custom-macros/ts-quote/quick-reference.md +50 -129
  52. package/docs/custom-macros/ts-quote/side-effects-do.md +13 -78
  53. package/docs/custom-macros/ts-quote/string-interpolation-textexpr.md +36 -0
  54. package/docs/custom-macros/ts-quote/tsstream-injection-typescript.md +43 -35
  55. package/docs/custom-macros/ts-quote/while-loops-while.md +31 -23
  56. package/docs/custom-macros/ts-quote.md +799 -519
  57. package/docs/getting-started/first-macro.md +61 -32
  58. package/docs/getting-started/installation.md +109 -66
  59. package/docs/integration/cli.md +212 -103
  60. package/docs/integration/configuration.md +114 -71
  61. package/docs/integration/integration-overview.md +54 -17
  62. package/docs/integration/mcp-server.md +83 -42
  63. package/docs/integration/svelte-preprocessor.md +183 -126
  64. package/docs/integration/typescript-plugin.md +101 -54
  65. package/docs/integration/vite-plugin.md +116 -76
  66. package/docs/language-servers/ls-overview.md +37 -21
  67. package/docs/language-servers/svelte.md +69 -39
  68. package/docs/language-servers/zed.md +81 -45
  69. package/docs/roadmap/roadmap.md +75 -53
  70. package/docs/sections.json +333 -44
  71. package/package.json +27 -28
@@ -1,48 +1,85 @@
1
1
  # The Derive System
2
- *The derive system is inspired by Rust's derive macros. It allows you to automatically implement common patterns by annotating your classes with `@derive`.*
3
- ## Syntax Reference
4
- Macroforge uses JSDoc comments for all macro annotations. This ensures compatibility with standard TypeScript tooling.
5
- ### The @derive Statement
6
- The `@derive` decorator triggers macro expansion on a class or interface:
7
- **Source:**
2
+
3
+ The derive system is inspired by Rust's derive macros. It allows you to automatically implement common patterns by annotating your classes with `@derive`.
4
+
5
+ ## Syntax Reference
6
+
7
+ Macroforge uses JSDoc comments for all macro annotations. This ensures compatibility with standard TypeScript tooling.
8
+
9
+ ### The @derive Statement
10
+
11
+ The `@derive` decorator triggers macro expansion on a class or interface:
12
+
13
+ Source
14
+
15
+ TypeScript
16
+
8
17
  ```
9
18
  /** @derive(Debug) */
10
19
  class MyClass {
11
- value: string;
20
+ value: string;
12
21
  }
13
- ``` Syntax rules:
14
- - Must be inside a JSDoc comment (`/** */`)
15
- - Must appear immediately before the class/interface declaration
16
- - Multiple macros can be comma-separated: `@derive(A, B, C)`
17
- - Multiple `@derive` statements can be stacked
18
- **Source:**
22
+ ```
23
+
24
+ Syntax rules:
25
+
26
+ * Must be inside a JSDoc comment (`/** */`)
27
+ * Must appear immediately before the class/interface declaration
28
+ * Multiple macros can be comma-separated: `@derive(A, B, C)`
29
+ * Multiple `@derive` statements can be stacked
30
+
31
+ Source
32
+
33
+ TypeScript
34
+
19
35
  ```
20
36
  /** @derive(Debug, Clone) */
21
37
  class User {
22
- name: string;
23
- email: string;
38
+ name: string;
39
+ email: string;
40
+ }
41
+ ```
42
+
43
+ ### The import macro Statement
44
+
45
+ To use macros from external packages, you must declare them with `import macro`:
46
+
47
+ TypeScript
48
+
49
+ ```
50
+ /** import macro { MacroName } from "package-name"; */
51
+ ```
52
+
53
+ Syntax rules:
54
+
55
+ * Must be inside a JSDoc comment (`/** */`)
56
+ * Can appear anywhere in the file (typically at the top)
57
+ * Multiple macros can be imported: `import macro { A, B } from "pkg";`
58
+ * Multiple import statements can be used for different packages
59
+
60
+ TypeScript
61
+
62
+ ```
63
+ /** import macro { JSON, Validate } from "@my/macros"; */
64
+ /** import macro { Builder } from "@other/macros"; */
65
+
66
+ /** @derive(JSON, Validate, Builder) */
67
+ class User {
68
+   name: string;
69
+   email: string;
24
70
  }
25
- ``` ### The import macro Statement
26
- To use macros from external packages, you must declare them with `import macro`:
27
- ```
28
- /** import macro { MacroName } from "package-name"; */
29
- ``` Syntax rules:
30
- - Must be inside a JSDoc comment (`/** */`)
31
- - Can appear anywhere in the file (typically at the top)
32
- - Multiple macros can be imported: `import macro { A, B } from "pkg";`
33
- - Multiple import statements can be used for different packages
34
- ```
35
- /** import macro { JSON, Validate } from "@my/macros"; */
36
- /** import macro { Builder } from "@other/macros"; */
37
-
38
- /** @derive(JSON, Validate, Builder) */
39
- class User {
40
- name: string;
41
- email: string;
42
- }
43
- ``` **Built-in macros Built-in macros (Debug, Clone, Default, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize) do not require an import statement. ### Field Attributes
44
- Macros can define field-level attributes to customize behavior per field:
45
- ****Before:**
71
+ ```
72
+
73
+ Built-in macros
74
+
75
+ Built-in macros (Debug, Clone, Default, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize) do not require an import statement.
76
+
77
+ ### Field Attributes
78
+
79
+ Macros can define field-level attributes to customize behavior per field:
80
+
81
+ Before (Your Code)
82
+
46
83
  ```
47
84
  /** @derive(Debug, Serialize) */
48
85
  class User {
@@ -56,85 +93,122 @@ class User {
56
93
  /** @serde({ skip: true }) */
57
94
  password: string;
58
95
 
59
- /** @serde({ flatten: true }) */
60
96
  metadata: Record<string, unknown>;
61
97
  }
62
- ```
63
- **After:**
64
98
  ```
65
- import { SerializeContext } from "macroforge/serde";
99
+
100
+ After (Generated)
101
+
102
+ ```
103
+ import { SerializeContext as __mf_SerializeContext } from 'macroforge/serde';
66
104
 
67
105
  class User {
68
-
69
-
70
- id: number;
106
+ id: number;
71
107
 
72
- name: string;
108
+ name: string;
73
109
 
74
-
75
-
76
- password: string;
110
+ password: string;
77
111
 
78
-
79
- metadata: Record<string, unknown>;
112
+ metadata: Record<string, unknown>;
80
113
 
81
- static toString(value: User): string {
82
- return userToString(value);
83
- }
84
- /** Serializes a value to a JSON string.
114
+ static toString(value: User): string {
115
+ return userToString(value);
116
+ }
117
+ /** Serializes a value to a JSON string.
85
118
  @param value - The value to serialize
86
119
  @returns JSON string representation with cycle detection metadata */
87
120
 
88
- static serialize(value: User): string {
89
- return userSerialize(value);
90
- }
91
- /** @internal Serializes with an existing context for nested/cyclic object graphs.
121
+ static serialize(value: User): string {
122
+ return userSerialize(value);
123
+ }
124
+ /** @internal Serializes with an existing context for nested/cyclic object graphs.
92
125
  @param value - The value to serialize
93
126
  @param ctx - The serialization context */
94
127
 
95
- static serializeWithContext(value: User, ctx: SerializeContext): Record<string, unknown> {
96
- return userSerializeWithContext(value, ctx);
97
- }
128
+ static serializeWithContext(value: User, ctx: __mf_SerializeContext): Record<string, unknown> {
129
+ return userSerializeWithContext(value, ctx);
130
+ }
98
131
  }
99
132
 
100
- export function userToString(value: User): string {const parts: string[]= []; parts.push("userId: " + value.id); parts.push("name: " + value.name); parts.push("metadata: " + value.metadata); return "User { " + parts.join(", " )+ " }" ; }
133
+ export function userToString(value: User): string {
134
+ const parts: string[] = [];
135
+ parts.push('userId: ' + value.id);
136
+ parts.push('name: ' + value.name);
137
+ parts.push('metadata: ' + value.metadata);
138
+ return 'User { ' + parts.join(', ') + ' }';
139
+ }
101
140
 
102
141
  /** Serializes a value to a JSON string.
103
142
  @param value - The value to serialize
104
- @returns JSON string representation with cycle detection metadata */export function userSerialize(value: User): string {const ctx = SerializeContext.create(); return JSON.stringify(userSerializeWithContext(value, ctx));}/** @internal Serializes with an existing context for nested/cyclic object graphs.
143
+ @returns JSON string representation with cycle detection metadata */ export function userSerialize(
144
+ value: User
145
+ ): string {
146
+ const ctx = __mf_SerializeContext.create();
147
+ return JSON.stringify(userSerializeWithContext(value, ctx));
148
+ } /** @internal Serializes with an existing context for nested/cyclic object graphs.
105
149
  @param value - The value to serialize
106
- @param ctx - The serialization context */export function userSerializeWithContext(value: User, ctx: SerializeContext): Record<string, unknown>{const existingId = ctx.getId(value); if(existingId!== undefined){return {__ref: existingId};}const __id = ctx.register(value); const result: Record<string, unknown>= {__type: "User" , __id,}; result["user_id" ]= value.id; result["name" ]= value.name; {const __flattened = record<string, unknown>SerializeWithContext(value.metadata, ctx); const {__type: _, __id: __,...rest}= __flattened as any; Object.assign(result, rest);}return result;}
107
- ``` Syntax rules:
108
- - Must be inside a JSDoc comment immediately before the field
109
- - Options use object literal syntax: `@attr({ key: value })`
110
- - Boolean options: `@attr({ skip: true })`
111
- - String options: `@attr({ rename: "newName" })`
112
- - Multiple attributes can be on separate lines or combined
113
- Common field attributes by macro:
114
- | Macro | Attribute | Options |
115
- | --- | --- | --- |
116
- | Debug | `@debug` | `skip`, `rename` |
117
- | Clone | `@clone` | `skip`, `clone_with` |
118
- | Serialize/Deserialize | `@serde` | `skip`, `rename`, `flatten`, `default` |
119
- | Hash | `@hash` | `skip` |
120
- | PartialEq/Ord | `@eq`, `@ord` | `skip` |
121
- ## How It Works
122
- 1. **Declaration**: You write `@derive(MacroName)` before a class
123
- 2. **Discovery**: Macroforge finds all derive decorators in your code
124
- 3. **Expansion**: Each named macro receives the class AST and generates code
125
- 4. **Injection**: Generated methods/properties are added to the class
126
- ## What Can Be Derived
127
- The derive system works on:
128
- - **Classes**: The primary target for derive macros
129
- - **Interfaces**: Macros generate companion namespace functions
130
- - **Enums**: Macros generate namespace functions for enum values
131
- - **Type aliases**: Both object types and union types are supported
132
- ## Built-in vs Custom Macros
133
- Macroforge comes with built-in macros that work out of the box. You can also create custom macros in Rust and use them via the `import macro` statement.
134
- | Type | Import Required | Examples |
135
- | --- | --- | --- |
136
- | Built-in | No | Debug, Clone, Default, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize |
137
- | Custom | Yes | Any macro from an external package |
138
- ## Next Steps
139
- - [Explore built-in macros](../../docs/builtin-macros)
140
- - [Create custom macros](../../docs/custom-macros)
150
+ @param ctx - The serialization context */
151
+ export function userSerializeWithContext(
152
+ value: User,
153
+ ctx: __mf_SerializeContext
154
+ ): Record<string, unknown> {
155
+ const existingId = ctx.getId(value);
156
+ if (existingId !== undefined) {
157
+ return { __ref: existingId };
158
+ }
159
+ const __id = ctx.register(value);
160
+ const result: Record<string, unknown> = { __type: 'User', __id };
161
+ result['user_id'] = value.id;
162
+ result['name'] = value.name;
163
+ result['metadata'] = value.metadata;
164
+ return result;
165
+ }
166
+ ```
167
+
168
+ Syntax rules:
169
+
170
+ * Must be inside a JSDoc comment immediately before the field
171
+ * Options use object literal syntax: `@attr({ key: value })`
172
+ * Boolean options: `@attr({ skip: true })`
173
+ * String options: `@attr({ rename: "newName" })`
174
+ * Multiple attributes can be on separate lines or combined
175
+
176
+ Common field attributes by macro:
177
+
178
+ | Macro | Attribute | Options |
179
+ | --------------------- | ------------- | -------------------------------------- |
180
+ | Debug | `@debug` | `skip`, `rename` |
181
+ | Clone | `@clone` | `skip`, `clone_with` |
182
+ | Serialize/Deserialize | `@serde` | `skip`, `rename`, `flatten`, `default` |
183
+ | Hash | `@hash` | `skip` |
184
+ | PartialEq/Ord | `@eq`, `@ord` | `skip` |
185
+
186
+ ## How It Works
187
+
188
+ 1. **Declaration**: You write `@derive(MacroName)` before a class
189
+ 2. **Discovery**: Macroforge finds all derive decorators in your code
190
+ 3. **Expansion**: Each named macro receives the class AST and generates code
191
+ 4. **Injection**: Generated methods/properties are added to the class
192
+
193
+ ## What Can Be Derived
194
+
195
+ The derive system works on:
196
+
197
+ * **Classes**: The primary target for derive macros
198
+ * **Interfaces**: Macros generate companion namespace functions
199
+ * **Enums**: Macros generate namespace functions for enum values
200
+ * **Type aliases**: Both object types and union types are supported
201
+
202
+ ## Built-in vs Custom Macros
203
+
204
+ Macroforge comes with built-in macros that work out of the box. You can also create custom macros in Rust and use them via the `import macro` statement.
205
+
206
+ | Type | Import Required | Examples |
207
+ | -------- | --------------- | ------------------------------------------------------------------------------- |
208
+ | Built-in | No | Debug, Clone, Default, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize |
209
+ | Custom | Yes | Any macro from an external package |
210
+
211
+ ## Next Steps
212
+
213
+ * [Explore built-in macros](../../docs/builtin-macros)
214
+ * [Create custom macros](../../docs/custom-macros)
@@ -1,19 +1,27 @@
1
1
  # How Macros Work
2
- *Macroforge performs compile-time code generation by parsing your TypeScript, expanding macros, and outputting transformed code. This happens before your code runs, resulting in zero runtime overhead.*
3
- ## Compile-Time Expansion
4
- Unlike runtime solutions that use reflection or proxies, Macroforge expands macros at compile time:
5
- 1. **Parse**: Your TypeScript code is parsed into an AST using SWC
6
- 2. **Find**: Macroforge finds `@derive` decorators and their associated items
7
- 3. **Expand**: Each macro generates new code based on the class structure
8
- 4. **Output**: The transformed TypeScript is written out, ready for normal compilation
9
- **Before:**
2
+
3
+ Macroforge performs compile-time code generation by parsing your TypeScript, expanding macros, and outputting transformed code. This happens before your code runs, resulting in zero runtime overhead.
4
+
5
+ ## Compile-Time Expansion
6
+
7
+ Unlike runtime solutions that use reflection or proxies, Macroforge expands macros at compile time:
8
+
9
+ 1. **Parse**: Your TypeScript code is parsed into an AST using SWC
10
+ 2. **Find**: Macroforge finds `@derive` decorators and their associated items
11
+ 3. **Expand**: Each macro generates new code based on the class structure
12
+ 4. **Output**: The transformed TypeScript is written out, ready for normal compilation
13
+
14
+ Before (Your Code)
15
+
10
16
  ```
11
17
  /** @derive(Debug) */
12
18
  class User {
13
19
  name: string;
14
20
  }
15
- ```
16
- **After:**
21
+ ```
22
+
23
+ After (Generated)
24
+
17
25
  ```
18
26
  class User {
19
27
  name: string;
@@ -28,30 +36,74 @@ export function userToString(value: User): string {
28
36
  parts.push('name: ' + value.name);
29
37
  return 'User { ' + parts.join(', ') + ' }';
30
38
  }
31
- ``` ## Zero Runtime Overhead
32
- Because code generation happens at compile time, there's no:
33
- - Runtime reflection or metadata
34
- - Proxy objects or wrappers
35
- - Additional dependencies in your bundle
36
- - Performance cost at runtime
37
- The generated code is plain TypeScript that compiles to efficient JavaScript.
38
- ## Source Mapping
39
- Macroforge tracks the relationship between your source code and the expanded output. This means:
40
- - Errors in generated code point back to your source
41
- - Debugging works correctly
42
- - IDE features like "go to definition" work as expected
43
- > with @derive decorators <div class="font-semibold text-foreground">SWC Parser TypeScript → AST <div class="font-semibold text-foreground">Macro Expansion Engine Finds @derive decorators, runs macros, generates new AST nodes <div class="font-semibold text-foreground">Code Generator AST → TypeScript <div class="font-semibold text-foreground">Expanded TypeScript ready for normal compilation ## Integration Points
44
- Macroforge integrates at two key points:
45
- ### IDE (TypeScript Plugin)
46
- The TypeScript plugin intercepts language server calls to provide:
47
- - Diagnostics that reference your source, not expanded code
48
- - Completions for generated methods
49
- - Hover information showing what macros generate
50
- ### Build (Vite Plugin)
51
- The Vite plugin runs macro expansion during the build process:
52
- - Transforms files before they reach the TypeScript compiler
53
- - Generates type declaration files (.d.ts)
54
- - Produces metadata for debugging
55
- ## Next Steps
56
- - [Learn about the derive system](../docs/concepts/derive-system)
57
- - [Explore the architecture](../docs/concepts/architecture)
39
+ ```
40
+
41
+ ## Zero Runtime Overhead
42
+
43
+ Because code generation happens at compile time, there's no:
44
+
45
+ * Runtime reflection or metadata
46
+ * Proxy objects or wrappers
47
+ * Additional dependencies in your bundle
48
+ * Performance cost at runtime
49
+
50
+ The generated code is plain TypeScript that compiles to efficient JavaScript.
51
+
52
+ ## Source Mapping
53
+
54
+ Macroforge tracks the relationship between your source code and the expanded output. This means:
55
+
56
+ * Errors in generated code point back to your source
57
+ * Debugging works correctly
58
+ * IDE features like "go to definition" work as expected
59
+
60
+ Error positioning
61
+
62
+ The TypeScript plugin uses source mapping to show errors at the `@derive` decorator position, not in the generated code.
63
+
64
+ ## Execution Flow
65
+
66
+ Your Source Code
67
+
68
+ with @derive decorators
69
+
70
+ SWC Parser
71
+
72
+ TypeScript → AST
73
+
74
+ Macro Expansion Engine
75
+
76
+ Finds @derive decorators, runs macros, generates new AST nodes
77
+
78
+ Code Generator
79
+
80
+ AST → TypeScript
81
+
82
+ Expanded TypeScript
83
+
84
+ ready for normal compilation
85
+
86
+ ## Integration Points
87
+
88
+ Macroforge integrates at two key points:
89
+
90
+ ### IDE (TypeScript Plugin)
91
+
92
+ The TypeScript plugin intercepts language server calls to provide:
93
+
94
+ * Diagnostics that reference your source, not expanded code
95
+ * Completions for generated methods
96
+ * Hover information showing what macros generate
97
+
98
+ ### Build (Vite Plugin)
99
+
100
+ The Vite plugin runs macro expansion during the build process:
101
+
102
+ * Transforms files before they reach the TypeScript compiler
103
+ * Generates type declaration files (.d.ts)
104
+ * Produces metadata for debugging
105
+
106
+ ## Next Steps
107
+
108
+ * [Learn about the derive system](../docs/concepts/derive-system)
109
+ * [Explore the architecture](../docs/concepts/architecture)
@@ -1,61 +1,83 @@
1
1
  # Custom Macros
2
- *Macroforge allows you to create custom derive macros in Rust. Your macros have full access to the class AST and can generate any TypeScript code.*
3
- ## Overview
4
- Custom macros are written in Rust and compiled to native Node.js addons. The process involves:
5
- 1. Creating a Rust crate with NAPI bindings
6
- 2. Defining macro functions with `#[ts_macro_derive]`
7
- 3. Using `macroforge_ts_quote` to generate TypeScript code
8
- 4. Building and publishing as an npm package
9
- ## Quick Example
10
- ```
11
- use macroforge_ts::macros::&#123;ts_macro_derive, body&#125;;
12
- use macroforge_ts::ts_syn::&#123;Data, DeriveInput, MacroforgeError, TsStream, parse_ts_macro_input&#125;;
2
+
3
+ Macroforge allows you to create custom derive macros in Rust. Your macros have full access to the class AST and can generate any TypeScript code.
4
+
5
+ ## Overview
6
+
7
+ Custom macros are written in Rust and compiled to native Node.js addons. The process involves:
8
+
9
+ 1. Creating a Rust crate with NAPI bindings
10
+ 2. Defining macro functions with `#[ts_macro_derive]`
11
+ 3. Using `macroforge_ts_quote` to generate TypeScript code
12
+ 4. Building and publishing as an npm package
13
+
14
+ ## Quick Example
15
+
16
+ Rust
17
+
18
+ ```
19
+ use macroforge_ts::macros::{ts_macro_derive, body};
20
+ use macroforge_ts::ts_syn::{Data, DeriveInput, MacroforgeError, TsStream, parse_ts_macro_input};
13
21
 
14
22
  #[ts_macro_derive(
15
- JSON,
16
- description = "Generates toJSON() returning a plain object"
23
+     JSON,
24
+     description = "Generates toJSON() returning a plain object"
17
25
  )]
18
- pub fn derive_json(mut input: TsStream) -> Result&#x3C;TsStream, MacroforgeError> &#123;
19
- let input = parse_ts_macro_input!(input as DeriveInput);
20
-
21
- match &#x26;input.data &#123;
22
- Data::Class(class) => &#123;
23
- Ok(body! &#123;
24
- toJSON(): Record&#x3C;string, unknown> &#123;
25
- return &#123;
26
- &#123;#for field in class.field_names()&#125;
27
- @&#123;field&#125;: this.@&#123;field&#125;,
28
- &#123;/for&#125;
29
- &#125;;
30
- &#125;
31
- &#125;)
32
- &#125;
33
- _ => Err(MacroforgeError::new(
34
- input.decorator_span(),
35
- "@derive(JSON) only works on classes",
36
- )),
37
- &#125;
38
- &#125;
39
- ``` ## Using Custom Macros
40
- Once your macro package is published, users can import and use it:
41
- ```
42
- /** import macro &#123; JSON &#125; from "@my/macros"; */
43
-
44
- /** @derive(JSON) */
45
- class User &#123;
46
- name: string;
47
- age: number;
48
-
49
- constructor(name: string, age: number) &#123;
50
- this.name = name;
51
- this.age = age;
52
- &#125;
53
- &#125;
54
-
55
- const user = new User("Alice", 30);
56
- console.log(user.toJSON()); // &#123; name: "Alice", age: 30 &#125;
57
- ``` > **Note:** The import macro comment tells Macroforge which package provides the macro. ## Getting Started
58
- Follow these guides to create your own macros:
59
- - [Set up a Rust macro crate](../docs/custom-macros/rust-setup)
60
- - [Learn the #[ts_macro_derive] attribute](../docs/custom-macros/ts-macro-derive)
61
- - [Learn the template syntax](../docs/custom-macros/ts-quote)
26
+ pub fn derive_json(mut input: TsStream) -> Result<TsStream, MacroforgeError> {
27
+     let input = parse_ts_macro_input!(input as DeriveInput);
28
+
29
+     match &input.data {
30
+         Data::Class(class) => {
31
+             Ok(body! {
32
+                 toJSON(): Record<string, unknown> {
33
+                     return {
34
+                         {#for field in class.field_names()}
35
+                             @{field}: this.@{field},
36
+                         {/for}
37
+                     };
38
+                 }
39
+             })
40
+         }
41
+         _ => Err(MacroforgeError::new(
42
+             input.decorator_span(),
43
+             "@derive(JSON) only works on classes",
44
+         )),
45
+     }
46
+ }
47
+ ```
48
+
49
+ ## Using Custom Macros
50
+
51
+ Once your macro package is published, users can import and use it:
52
+
53
+ TypeScript
54
+
55
+ ```
56
+ /** import macro { JSON } from "@my/macros"; */
57
+
58
+ /** @derive(JSON) */
59
+ class User {
60
+   name: string;
61
+   age: number;
62
+
63
+   constructor(name: string, age: number) {
64
+     this.name = name;
65
+     this.age = age;
66
+   }
67
+ }
68
+
69
+ const user = new User("Alice", 30);
70
+ console.log(user.toJSON()); // { name: "Alice", age: 30 }
71
+ ```
72
+
73
+ Note
74
+
75
+ The `import macro` comment tells Macroforge which package provides the macro.
76
+
77
+ ## Getting Started
78
+
79
+ Follow these guides to create your own macros:
80
+
81
+ * [Set up a Rust macro crate](../docs/custom-macros/rust-setup)
82
+ * [Learn the #\[ts\_macro\_derive\] attribute](../docs/custom-macros/ts-macro-derive)
83
+ * [Learn the template syntax](../docs/custom-macros/ts-quote)