node-api-dotnet-generator 0.2.5

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 ADDED
@@ -0,0 +1,313 @@
1
+ # Node API for .NET: JavaScript + .NET Interop
2
+
3
+ This project enables advanced interoperability between .NET and JavaScript in the same process.
4
+
5
+ - Load .NET assemblies and call .NET APIs in-proc from a JavaScript application.
6
+ - Load JavaScript packages call JS APIs in-proc from a .NET application.
7
+
8
+ Interop is high-performance and supports TypeScript type-definitions generation, async
9
+ (tasks/promises), streams, and more. It uses [Node API](https://nodejs.org/api/n-api.html) so
10
+ it is compatible with any Node.js version (without recompiling) or other JavaScript runtime that
11
+ supports Node API.
12
+
13
+ :warning: _**Status: In Development** - Core functionality works, but many things are incomplete,
14
+ and it isn't yet all packaged up nicely in a way that can be easily consumed._
15
+
16
+ [Instructions for getting started are below.](#getting-started)
17
+
18
+ ### Minimal example - JS calling .NET
19
+ ```JavaScript
20
+ // JavaScript
21
+ const Console = require('node-api-dotnet').Console;
22
+ Console.WriteLine('Hello from .NET!');
23
+ ```
24
+
25
+ ### Minimal example - .NET calling JS
26
+ ```C#
27
+ // C#
28
+ interface IConsole { void Log(string message); }
29
+
30
+ var nodejs = new NodejsPlatform(libnodePath).CreateEnvironment();
31
+ nodejs.Run(() => {
32
+ var console = nodejs.Import<IConsole>("global", "console");
33
+ console.Log("Hello from JS!");
34
+ });
35
+ ```
36
+
37
+ For more examples, see the [examples](./examples/) directory.
38
+
39
+ ## Feature Highlights
40
+ - [Load and call .NET assemblies from JS](#load-and-call-net-assemblies-from-js)
41
+ - [Load and call JavaScript packages from .NET](#load-and-call-javascript-packages-from-net)
42
+ - [Generate TS type definitions for .NET APIs](#generate-ts-type-definitions-for-net-apis)
43
+ - [Full async support](#full-async-support)
44
+ - [Error propagation](#error-propagation)
45
+ - [Develop Node.js addons with C#](#develop-nodejs-addons-with-c)
46
+ - [Optionally work directly with JS types in C#](#optionally-work-directly-with-js-types-in-c)
47
+ - [Automatic efficient marshaling](#automatic-efficient-marshaling)
48
+ - [Stream across .NET and JS](#stream-across-net-and-js)
49
+ - [Optional .NET native AOT compilation](#optional-net-native-aot-compilation)
50
+ - [High performance](#high-performance)
51
+
52
+ ### Load and call .NET assemblies from JS
53
+ The `node-api-dotnet` package manages hosting the .NET runtime in the JS process
54
+ (if not using AOT - see below). The .NET core library types are available directly on the
55
+ `node-api-dotnet` module, and additional .NET assemblies can be loaded by file path:
56
+ ```JavaScript
57
+ // JavaScript
58
+ const dotnet = require('node-api-dotnet');
59
+ const ExampleAssembly = dotnet.load('path/to/ExampleAssembly.dll');
60
+ const exampleObj = new ExampleAssembly.ExampleClass(...args);
61
+ ```
62
+
63
+ .NET namespaces are stripped for convenience, but in case of ambiguity it's possible to get a type
64
+ by full name:
65
+ ```JavaScript
66
+ // JavaScript
67
+ const MyType = ExampleAssembly['Namespace.Qualified.MyType'];
68
+ ```
69
+
70
+ ### Load and call JavaScript packages from .NET
71
+ Calling JavaScript from .NET requires hosting a JS runtime such as Node.js in the .NET app.
72
+ Then JS packages can be imported either directly as JS values or by declaring C# interfaces for
73
+ the JS types and using automatic marshalling.
74
+
75
+ All interaction with a JavaScript environment must be from its thread, via the
76
+ `Run()`, `RunAsync()`, or `Post()` methods on the JS environment object.
77
+ ```C#
78
+ // C#
79
+ interface IExample
80
+ {
81
+ void ExampleMethod();
82
+ }
83
+
84
+ var nodejsPlatform = new NodejsPlatform(libnodePath);
85
+ var nodejs = nodejsPlatform.CreateEnvironment();
86
+
87
+ nodejs.Run(() => {
88
+ // Import a module property, then call a function on it.
89
+ var example1 = nodejs.Import("example-npm-package", "ExampleObject");
90
+ example1.CallMethod("exampleMethod");
91
+
92
+ // Import the module property using an interface, and call the same function.
93
+ var example2 = nodejs.Import<IExample>("example-npm-package", "ExampleObject");
94
+ example2.ExampleMethod();
95
+ });
96
+ ```
97
+
98
+ In the future, it may be possible to automatically generate .NET API definitions from TypeScript
99
+ type definitions.
100
+
101
+ ### Generate TS type definitions for .NET APIs
102
+ If writing TypeScript, or type-checked JavaScript, there is a tool to generate type `.d.ts` type
103
+ definitions for .NET APIs. Soon, it should also generate a small `.js` file that exports the
104
+ assembly in a more natural way as a JS module.
105
+ ```bash
106
+ $ npm exec node-api-dotnet-generator --assembly ExampleAssembly.dll --typedefs ExampleAssembly.d.ts
107
+ ```
108
+ ```TypeScript
109
+ // TypeScript
110
+ import { ExampleClass } from './ExampleAssembly';
111
+ ExampleClass.ExampleMethod(...args); // This call is type-checked!
112
+ ```
113
+
114
+ For reference, there is a [list of C# type projections to TypeScript](/Docs/typescript.md).
115
+
116
+ ### Full async support
117
+ JavaScript code can `await` a call to a .NET method that returns a `Task`. The marshaller
118
+ automatically sets up a `SynchronizationContext` so that the .NET result is returned back to the
119
+ JS thread.
120
+ ```TypeScript
121
+ // TypeScript
122
+ import { ExampleClass } from './ExampleAssembly';
123
+ const asyncResult = await ExampleClass.GetSomethingAsync(...args);
124
+ ```
125
+ .NET `Task`s are seamlessly marshaled to & from JS `Promise`s. So JS code can work naturally with
126
+ a `Promise` returned from a .NET async method, and a JS `Promise` passed to .NET becomes a
127
+ `JSPromise` that can be `await`ed in the C# code.
128
+
129
+ ### Error propagation
130
+ Exceptions/errors thrown in .NET or JS are propagated across the boundary with stack traces.
131
+
132
+ _Under development. More to be written..._
133
+
134
+ ### Develop Node.js addons with C#
135
+ A C# class library project can use the `[JSExport]` attribute to tag (and rename) APIs that are
136
+ exported when the library is built as a JavaScript module. A [C# Source Generator](
137
+ https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview) runs as
138
+ part of the compilation and generates code to export the tagged APIs and marshal values between
139
+ JavaScript and C#.
140
+
141
+ ```C#
142
+ // C#
143
+ [JSExport] // Export class and all public members to JS.
144
+ public class ExampleClass { ... }
145
+
146
+ public static class ExampleStaticClass
147
+ {
148
+ [JSExport("exampleFunction")] // Export as a module-level function.
149
+ public static string StaticMethod(ExampleClass obj) { ... }
150
+
151
+ // (Other public members in this class are not exported by default.)
152
+ }
153
+ ```
154
+
155
+ The `[JSExport]` source generator enables faster startup time because the marshaling code is
156
+ generated at build time rather than dynamically emitted at runtime (as when calling a pre-built
157
+ assembly). The source generator also enables building ahead-of-time compiled libraries in C# that
158
+ can be called by JavaScript without depending on the .NET Runtime. (More on that below.)
159
+
160
+ ### Optionally work directly with JS types in C#
161
+ The class library includes an object model for the JavaScript type system. `JSValue` represents a
162
+ value of any type, and there are more types like `JSObject`, `JSArray`, `JSMap`, `JSPromise`, etc.
163
+ C# code can work directly with those types if desired:
164
+
165
+ ```C#
166
+ // C#
167
+ [JSExport]
168
+ public static JSPromise JSAsyncExample(JSValue input)
169
+ {
170
+ // Example of integration between C# async/await and JS promises.
171
+ string greeter = (string)input;
172
+ return new JSPromise(async (resolve) =>
173
+ {
174
+ await Task.Delay(50);
175
+ resolve((JSValue)$"Hey {greeter}!");
176
+ });
177
+ }
178
+ ```
179
+
180
+ ### Automatic efficient marshaling
181
+ There are two ways to get automatic marshaling between C# and JavaScript types:
182
+ 1. Compile a C# class library with `[JSExport]` attributes like the examples above. The source
183
+ generator produces marshaling code that is compiled with the assembly.
184
+
185
+ 2. Load a pre-built .NET assembly, as in the earlier examples. The loader will use reflection to
186
+ scan the APIs, then emit marshaling code on-demand for each type that is referenced by JS. The
187
+ dynamic marshalling code is derived from the same expression trees that are used for compile-time
188
+ source-generation, but is generated and at runtime and compiled with
189
+ [`LambdaExpression.Compile()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.lambdaexpression.compile).
190
+ So there is a small startup cost from that reflection and compilation, but subsequent calls to
191
+ the same APIs may be just as fast as the pre-compiled marshaling code (and are just as likely
192
+ to be JITted).
193
+
194
+ The marshaller uses the strong typing information from the C# API declarations as hints about how to
195
+ convert values beteen JavaScript and C#. Here's a general summary of conversions:
196
+ - Primitives (numbers, strings, etc.) are passed by value directy.
197
+ - C# structs have all properties passed by value (shallow copied).
198
+ - C# classes are passed by reference. Any JS call to a C# class or interface property or method
199
+ gets proxied over to the C# instance of the class. (Object GC lifetimes are synchronized
200
+ accordingly.)
201
+ - JS code may implement a C# interface, and pass that implementation back to C# code where it
202
+ becomes a proxy that C# code can use.
203
+ - C# collections like `IList<T>` and JS collections like `Map<T>` are also passed by reference;
204
+ access to collection elements is proxied to whichever side the real instance of the collection
205
+ is on.
206
+ - JS `TypedArray`s are mapped to C# `Memory<T>` and passed by reference using shared memory
207
+ (no proxying is needed).
208
+ - Other types like enums, dates, and delegates are automatically marshaled as one would expect.
209
+ - Custom marshaling and marshaling hints [may be supported later](
210
+ https://github.com/jasongin/napi-dotnet/pull/25).
211
+
212
+ ### Stream across .NET and JS
213
+ .NET `Stream`s are automatically marshalled to and from Node.js `Duplex` (or `Readable` or
214
+ `Writable`) streams. That means JS code can seamlessly read from or write to streams created
215
+ by .NET. Or .NET code can read from or write to streams created by JS. Streamed data is
216
+ transferred using shared memory (without any additional sockets or pipes), so memory allocation
217
+ and copying is minimized.
218
+
219
+ ### Optional .NET native AOT compilation
220
+ This library supports hosting the .NET Runtime in the same process as the JavaScript runtime.
221
+ Alternatively, it also supports building [native ahead-of-time (AOT) compiled C#](
222
+ https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/) libraries that are
223
+ loadable as a JavaScript module _without depending on the .NET Runtime_.
224
+
225
+ There are advantages and disadvantages to either approach:
226
+ | | .NET Runtime | .NET Native AOT |
227
+ |---------------------|--------------|-----------------|
228
+ | API compatibility | Broad compatibility with .NET APIs | Limited compatibility with APIs designed to support AOT |
229
+ | Ease of deployment | Requires a matching version of .NET to be installed on the target system | A .NET installation is not required (though some platform libs may be required on Linux/Mac)
230
+ | Size of deployment | Compact - only IL assemblies need to be deployed | Larger due to bundling necessary runtime code - minimum ~3 MB per platform |
231
+ | Performance | Slightly slower startup (JIT) | Slightly faster startup (no JIT) |
232
+ | Runtime limitations | Full .NET functionality | Some .NET features like reflection and code-generation aren't supported |
233
+
234
+ ### High performance
235
+ The project is designed to be as performant as possible when bridging between .NET and JavaScript.
236
+ Techniques benefitting performance include:
237
+ - Automatic marshaling avoids any use of JSON serialization, and uses generated code to avoid
238
+ reflection.
239
+ - Automatic marshalling uses shared memory or proxies when possible to minimize the amount of
240
+ data transferred across the boundary.
241
+ - Simple calls between JS and C# require **_almost_** zero memory allocation. (Maybe it will be
242
+ zero eventually.)
243
+ - Most JavaScript values are represented in C# as small structs (basically containing just a
244
+ handle to the JS value), which helps avoid memory allocation.
245
+ - Marshaling code uses modern C# performance features like `Span<T>` and `stackalloc` to minimize
246
+ heap allocations and copying.
247
+
248
+ Thanks to these design choices, JS to .NET calls are [more than twice as fast](
249
+ https://github.com/jasongin/napi-dotnet/pull/23) when compared to `edge-js` using
250
+ [that project's benchmark](https://github.com/tjanczuk/edge/wiki/Performance).
251
+
252
+ ## Getting Started
253
+ #### Requirements
254
+ - .NET 6 or later
255
+ - .NET 7 or later is required for AOT support.
256
+ - .NET Framework 4.7.2 or later is supported at runtime,
257
+ but .NET 6 SDK is still required for building.
258
+ - Node.js v16 or later
259
+ - Other JS runtimes may be supported in the future.
260
+ - OS: Windows, Mac, or Linux
261
+ - It should work on any platform where .NET 6 is supported.
262
+
263
+ #### Instructions
264
+ For calling .NET from JS, choose between one of the following scenarios:
265
+ - [Dynamically invoke .NET APIs from JavaScript](./Docs/dynamic-invoke.md)<br/>
266
+ Dynamic invocation is simpler to set up: all you need is the `node-api-dotnet` npm package and
267
+ the path to a .NET assembly you want to call. But it has some limitations (not all kinds of APIs
268
+ are supported), and is not quite as fast as a C# module, because marshalling code must be
269
+ generated at runtime.
270
+ - [Develop a Node module in C#](./Docs/node-module.md)<br/>
271
+ A C# Node module is appropriate for an application that has more advanced interop needs. It can
272
+ be faster because marshalling code can be generated at compile time, and the shape of the APIs
273
+ exposed to JavaScript can be adapted with JS interop in mind.
274
+
275
+ For calling JS from .NET, more documentation will be added soon. For now, see the
276
+ [`winui-fluid` example code](./examples/winui-fluid/).
277
+
278
+ Generated TypeScript type definitions can be utilized with any of these aproaches.
279
+
280
+ ## Development
281
+ For information about building, testing, and contributing changes to this project, see
282
+ [README-DEV.md](./README-DEV.md).
283
+
284
+ ## Contributing
285
+
286
+ This project welcomes contributions and suggestions. Most contributions require you to agree to a
287
+ Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
288
+ the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
289
+
290
+ When you submit a pull request, a CLA bot will automatically determine whether you need to provide
291
+ a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the
292
+ instructions provided by the bot. You will only need to do this once across all repos using our CLA.
293
+
294
+ This project has adopted the
295
+ [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
296
+ For more information see the
297
+ [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
298
+ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or
299
+ comments.
300
+
301
+ ## Trademarks
302
+
303
+ This project may contain trademarks or logos for projects, products, or services. Authorized use of
304
+ Microsoft trademarks or logos is subject to and must follow
305
+ [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
306
+ Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion
307
+ or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those
308
+ third-party's policies.
309
+
310
+ <br/>
311
+ <br/>
312
+
313
+ ![.NET + JS scene](./Docs/images/dotnet-bot_scene_coffee-shop.png)
package/index.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT License.
5
+
6
+ const path = require('path');
7
+ const assemblyDir = path.join(__dirname, 'net6.0');
8
+
9
+ const dotnet = require('node-api-dotnet');
10
+
11
+ // The generator depends on these assemblies; for now they have to be loaded explicitly.
12
+ dotnet.load(path.join(assemblyDir, 'System.Reflection.MetadataLoadContext.dll'));
13
+ dotnet.load(path.join(assemblyDir, 'Microsoft.CodeAnalysis.dll'));
14
+
15
+ const Generator = dotnet.load(path.join(assemblyDir, 'Microsoft.JavaScript.NodeApi.Generator.dll'));
16
+
17
+ const args = process.argv.slice(2);
18
+ Generator.Program.Main(args);
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "node-api-dotnet-generator",
3
+ "version": "0.2.5",
4
+ "description": "Node-API for .Net code generator",
5
+ "main": "index.js",
6
+ "bin": "index.js",
7
+ "license": "MIT",
8
+ "author": "Microsoft",
9
+ "dependencies": {
10
+ "node-api-dotnet": "0.2.5"
11
+ },
12
+ "keywords": [
13
+ "Node-API",
14
+ "NAPI",
15
+ "generator",
16
+ ".Net",
17
+ "dotnet"
18
+ ],
19
+ "repository": "github:microsoft/node-api-dotnet",
20
+ "homepage": "https://github.com/microsoft/node-api-dotnet#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/microsoft/node-api-dotnet/issues"
23
+ }
24
+ }