@nativescript/windows-napi 0.0.0-stage → 1.0.0-beta.21

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 CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @nativescript/windows-napi
2
+
3
+ Node-API WinRT interop for Windows.
4
+
5
+ ## How this relates to the other packages
6
+
7
+ - `@nativescript/windows` — the classic V8-based app runtime.
8
+ - `@nativescript/windows-<engine>` (`windows-v8`, `windows-quickjs`, `windows-hermes`, `windows-jsc`) — the Node-API app-runtime variants, each embedding a standalone engine.
9
+ - `@nativescript/windows-napi` (this package) — the same Node-API WinRT bindings as a native addon, for use inside an existing Node, Bun, or Deno process rather than as a standalone app runtime.
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ const winrt = require('@nativescript/windows-napi');
15
+ ```
16
+
17
+ Requires Windows (x64 or arm64) and Node >= 18 (or a Node-API-compatible runtime such as Bun or Deno).
18
+
19
+ ## XAML windows
20
+
21
+ `XamlWindow` hosts `Windows.UI.Xaml` content (XAML Islands) in a Win32 window:
22
+
23
+ ```js
24
+ const { Windows, XamlWindow } = require('@nativescript/windows-napi');
25
+
26
+ const win = new XamlWindow({ style: 'dialog', owner: browserWindow.getNativeWindowHandle() });
27
+ const button = new Windows.UI.Xaml.Controls.Button();
28
+ button.Content = 'OK';
29
+ button.Click = () => win.close();
30
+ win.content = button;
31
+ win.place({ width: 320, height: 120, over: browserWindow.getNativeWindowHandle() });
32
+ win.show();
33
+ ```
34
+
35
+ - `style`: `'dialog'` (title bar, close box) or `'popup'` (borderless, not in the taskbar or Alt+Tab).
36
+ - Options: `owner`, `title`, `topmost`, `theme` (`'system'`, `'dark'`, `'light'`).
37
+ - Events: `activate`, `deactivate`, `close` (title-bar X or Alt+F4; closes when unhandled), `closed`.
38
+ - Helpers: `XamlWindow.foregroundWindow()`, `activateWindow(hwnd)`, `enableWindow(hwnd, enabled)`,
39
+ `windowProcessId(hwnd)`.
40
+
41
+ The host executable's manifest must declare `<maxversiontested Id="10.0.18362.0"/>` or later;
42
+ `electron.exe` does and `node.exe` doesn't, so `XamlWindow` throws in plain Node. XAML events run
43
+ from the host's message loop, so a host with its own UI loop needs no `pumpMessages`.
44
+
45
+ ## Development
46
+
47
+ ```sh
48
+ npm run build # release build via @napi-rs/cli
49
+ npm run build:debug # debug build
50
+ npm test # run the test suite (run-tests.js)
51
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,156 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /* auto-generated by NAPI-RS */
5
+
6
+ /** Format one value exactly as `console.log` (rich=false) or `console.dir` (rich=true) would. */
7
+ export declare function formatValue(value: unknown, rich: boolean): string
8
+ /** Render `console.table` output for a value (optional column filter). */
9
+ export declare function tableFor(value: unknown, columns?: Array<string> | undefined | null): string
10
+ /**
11
+ * Wrap `func` in a NapiDelegate COM object with the given Invoke parameter types.
12
+ * Returns the COM pointer as f64 (refcount 1).
13
+ */
14
+ export declare function makeDelegate(func: (...args: any[]) => any, paramTypes: Array<string>): number
15
+ /**
16
+ * Fire the delegate through its COM vtable with up to three raw (usize-packed) args.
17
+ * Returns the HRESULT.
18
+ */
19
+ export declare function invokeDelegate(ptr: number, p0: number, p1: number, p2: number): number
20
+ /** Release one COM reference; returns the remaining count. */
21
+ export declare function releaseDelegate(ptr: number): number
22
+ /**
23
+ * Call a static WinRT method: `callStaticMethod('Windows.Data.Json.JsonValue',
24
+ * 'CreateStringValue', ['hello'])`.
25
+ */
26
+ export declare function callStaticMethod(className: string, methodName: string, args: Array<unknown>): unknown
27
+ /** Call an instance WinRT method on a pointer external returned by a previous call. */
28
+ export declare function callInstanceMethod(instance: unknown, className: string, methodName: string, args: Array<unknown>): unknown
29
+ /**
30
+ * Build a native-backed JS `Proxy`. Reads/writes flow through Rust trap callbacks into a
31
+ * shared native map — the exact shape `ns_proxy.rs` will take under Node-API.
32
+ */
33
+ export declare function makeNativeProxy(): object
34
+ /**
35
+ * Parse `value` as `ty` into a `NativeValue`, then marshal it back to JS. Throws on parse
36
+ * errors so the JS test can assert rejection.
37
+ */
38
+ export declare function ffiRoundtrip(value: unknown, ty: string): unknown
39
+ /**
40
+ * Parse `value` as a Pointer arg and return the raw pointer as f64 (user-space addresses
41
+ * fit in 2^53).
42
+ */
43
+ export declare function pointerValue(value: unknown): number
44
+ /** Create a native-pointer external carrying `addr` (for pointer round-trip tests). */
45
+ export declare function makeExternal(addr: number): unknown
46
+ /** Parse `value` as a Buffer arg; returns `[dataPtr, byteLength]` as f64s. */
47
+ export declare function bufferInfo(value: unknown): Array<number>
48
+ /** Parse `value` as a Struct arg of `size` bytes (default 0); returns the data pointer as f64. */
49
+ export declare function structPtr(value: unknown, size?: number | undefined | null): number
50
+ /**
51
+ * Write `value` into a native scratch slot as `ty`, then read it back to JS — exercises
52
+ * `write_js_value_to_ptr` + `read_value_from_ptr` (including HSTRING ownership hand-off).
53
+ */
54
+ export declare function writeReadPtr(value: unknown, ty: string): unknown
55
+ /**
56
+ * If `value` is an `interop.out(...)` wrapper, return its wrapped value; else return the
57
+ * string `"<none>"`.
58
+ */
59
+ export declare function outParamValue(value: unknown): unknown
60
+ /** Set the `value` slot of an out-param wrapper; returns whether the set succeeded. */
61
+ export declare function setOutParam(wrapper: object, newValue: unknown): boolean
62
+ /** Serialize `value` as a struct field of type `ty`; returns the little-endian bytes. */
63
+ export declare function structFieldBytes(value: unknown, ty: string): Array<number>
64
+ /**
65
+ * Box `value` as a WinRT `IPropertyValue` of `ty`; returns the raw IInspectable pointer as
66
+ * f64 (0 when boxing is not possible). Requires WinRT initialized (call init() first).
67
+ */
68
+ export declare function boxTyped(value: unknown, ty: string): number
69
+ /**
70
+ * Pump the calling thread's Win32 messages (WinRT async completions, cross-apartment
71
+ * delegate invokes, `createWindow` input). Returns `true` if a message was dispatched.
72
+ */
73
+ export declare function pumpMessages(): boolean
74
+ /** The last JS error (message + stack), if any. */
75
+ export declare function lastError(): string | null
76
+ /**
77
+ * Install the runtime's globals (`__time`, and `performance`/`console` where the host lacks
78
+ * them) onto the host's global object.
79
+ */
80
+ export declare function installGlobals(): void
81
+ /**
82
+ * Resolve a WinRT namespace root (e.g. `getNamespace('Windows')`) as a lazy proxy: member
83
+ * access walks metadata, classes come back as constructable proxies.
84
+ */
85
+ export declare function getNamespace(name: string): object
86
+ /** Generate a fresh UUID string (CoCreateGuid). */
87
+ export declare function nsUuid(): string
88
+ /**
89
+ * Create and show a plain Win32 top-level window; returns its `HWND` as an opaque handle.
90
+ * `pumpMessages`/`enableAutoPump` (already used for WinRT async completions) pump its message
91
+ * queue for free. They peek messages for the whole calling thread, not a specific window.
92
+ */
93
+ export declare function createWindow(title: string, width: number, height: number): unknown
94
+ /**
95
+ * Attach a `Windows.UI.Composition.Compositor` instance to a window from `createWindow` and
96
+ * return the resulting `DesktopWindowTarget` as a normal WinRT proxy. Set its `.Root` to a
97
+ * visual to render into the window.
98
+ */
99
+ export declare function attachCompositorToWindow(compositor: unknown, hwnd: unknown): object
100
+ /**
101
+ * Drain the input/lifecycle events queued for a `createWindow` window since the last poll:
102
+ * `pointerdown {x, y, button}`, `pointerup {x, y}`, `pointermove {x, y}` (latest position only),
103
+ * `resize {width, height}`, `close`. Coordinates are client-area pixels. Poll after `pumpMessages`.
104
+ */
105
+ export declare function pollWindowEvents(hwnd: unknown): object
106
+ /** Client-area size of a `createWindow` window as `{ width, height }`, or `null` once closed. */
107
+ export declare function getWindowSize(hwnd: unknown): unknown
108
+ /** Set the title-bar text of a `createWindow` window. */
109
+ export declare function setWindowTitle(hwnd: unknown, title: string): void
110
+ /**
111
+ * Create a hidden window hosting a `DesktopWindowXamlSource`; returns its HWND as a number.
112
+ * Options: `style` (`"dialog"` | `"popup"`), `owner`, `title`, `topmost`, `dark`.
113
+ */
114
+ export declare function xamlHostCreate(source: unknown, options?: object | undefined | null): number
115
+ /** Set the listener for `"activate"`, `"deactivate"`, `"close"`, `"closed"`; `null` removes it. */
116
+ export declare function xamlHostSetListener(hwnd: unknown, listener?: (...args: any[]) => any | undefined | null): void
117
+ /** Size the client area in DIPs; center over `over`, or on the pointer's monitor at `y` (0..1). */
118
+ export declare function xamlHostPlace(hwnd: unknown, options: object): void
119
+ /** Show the host; with `activate` it takes the foreground. Returns whether it is in front. */
120
+ export declare function xamlHostShow(hwnd: unknown, activate: boolean): boolean
121
+ export declare function xamlHostHide(hwnd: unknown): void
122
+ export declare function xamlHostIsVisible(hwnd: unknown): boolean
123
+ /** Destroy the host window (its listener still receives `"closed"`). */
124
+ export declare function xamlHostDestroy(hwnd: unknown): void
125
+ /** The foreground window (any process) as a number, or 0. */
126
+ export declare function foregroundWindow(): number
127
+ /** Bring a window to the foreground; `false` when Windows refuses. */
128
+ export declare function activateWindow(hwnd: unknown): boolean
129
+ /** Enable or disable input to a window (used to make an owner modal). */
130
+ export declare function enableWindow(hwnd: unknown, enabled: boolean): void
131
+ /** The id of the process that owns a window, or 0. */
132
+ export declare function windowProcessId(hwnd: unknown): number
133
+ /**
134
+ * Whether the WinRT class `name` is sealed (metadata flag). Test hook: lets suites assert
135
+ * they are really covering the composable (non-sealed, null-outer) constructor path.
136
+ */
137
+ export declare function classIsSealed(name: string): boolean | null
138
+ /** Register a third-party `.winmd` file for metadata resolution (WebView2, app types, …). */
139
+ export declare function registerWinmd(path: string): void
140
+ /** Register every `.winmd` in a directory (non-recursive); returns the count registered. */
141
+ export declare function scanWinmdDir(dir: string): number
142
+ /** Wrap a `Windows.Storage.Streams.IBuffer` as a (zero-copy where supported) ArrayBuffer. */
143
+ export declare function arrayBufferFromBuffer(buffer: unknown): unknown
144
+ /**
145
+ * Install the `__ns*` interop natives and the `NSWinRT.interop` JS surface (Pointer/OutParam,
146
+ * `reference` / typed-value boxing, buffer + DateTime utilities) without touching any other
147
+ * host global. Idempotent; `nswinrt.js` calls this on load.
148
+ */
149
+ export declare function installInterop(): void
150
+ /**
151
+ * Install the `.NET`/BCL bridge natives and the `NSWinRT.dotnet` JS surface
152
+ * (invoke/get/fromHandle/registerNamespace, taskToPromise/asDelegate, `NSWinRT.runOnUIThread`).
153
+ * Idempotent; `nswinrt.js` calls this on load. A no-op at the JS layer until a
154
+ * `dotnet-bridge/publish/DotNetBridge.dll` exists next to the app.
155
+ */
156
+ export declare function installDotnet(): void
package/index.js ADDED
@@ -0,0 +1,359 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /* prettier-ignore */
4
+
5
+ /* auto-generated by NAPI-RS */
6
+
7
+ const { existsSync, readFileSync } = require('fs')
8
+ const { join } = require('path')
9
+
10
+ const { platform, arch } = process
11
+
12
+ let nativeBinding = null
13
+ let localFileExisted = false
14
+ let loadError = null
15
+
16
+ function isMusl() {
17
+ // For Node 10
18
+ if (!process.report || typeof process.report.getReport !== 'function') {
19
+ try {
20
+ const lddPath = require('child_process').execSync('which ldd').toString().trim()
21
+ return readFileSync(lddPath, 'utf8').includes('musl')
22
+ } catch (e) {
23
+ return true
24
+ }
25
+ } else {
26
+ const { glibcVersionRuntime } = process.report.getReport().header
27
+ return !glibcVersionRuntime
28
+ }
29
+ }
30
+
31
+ switch (platform) {
32
+ case 'android':
33
+ switch (arch) {
34
+ case 'arm64':
35
+ localFileExisted = existsSync(join(__dirname, 'windows.android-arm64.node'))
36
+ try {
37
+ if (localFileExisted) {
38
+ nativeBinding = require('./windows.android-arm64.node')
39
+ } else {
40
+ nativeBinding = require('@nativescript/windows-napi-android-arm64')
41
+ }
42
+ } catch (e) {
43
+ loadError = e
44
+ }
45
+ break
46
+ case 'arm':
47
+ localFileExisted = existsSync(join(__dirname, 'windows.android-arm-eabi.node'))
48
+ try {
49
+ if (localFileExisted) {
50
+ nativeBinding = require('./windows.android-arm-eabi.node')
51
+ } else {
52
+ nativeBinding = require('@nativescript/windows-napi-android-arm-eabi')
53
+ }
54
+ } catch (e) {
55
+ loadError = e
56
+ }
57
+ break
58
+ default:
59
+ throw new Error(`Unsupported architecture on Android ${arch}`)
60
+ }
61
+ break
62
+ case 'win32':
63
+ switch (arch) {
64
+ case 'x64':
65
+ localFileExisted = existsSync(
66
+ join(__dirname, 'windows.win32-x64-msvc.node')
67
+ )
68
+ try {
69
+ if (localFileExisted) {
70
+ nativeBinding = require('./windows.win32-x64-msvc.node')
71
+ } else {
72
+ nativeBinding = require('@nativescript/windows-napi-win32-x64-msvc')
73
+ }
74
+ } catch (e) {
75
+ loadError = e
76
+ }
77
+ break
78
+ case 'ia32':
79
+ localFileExisted = existsSync(
80
+ join(__dirname, 'windows.win32-ia32-msvc.node')
81
+ )
82
+ try {
83
+ if (localFileExisted) {
84
+ nativeBinding = require('./windows.win32-ia32-msvc.node')
85
+ } else {
86
+ nativeBinding = require('@nativescript/windows-napi-win32-ia32-msvc')
87
+ }
88
+ } catch (e) {
89
+ loadError = e
90
+ }
91
+ break
92
+ case 'arm64':
93
+ localFileExisted = existsSync(
94
+ join(__dirname, 'windows.win32-arm64-msvc.node')
95
+ )
96
+ try {
97
+ if (localFileExisted) {
98
+ nativeBinding = require('./windows.win32-arm64-msvc.node')
99
+ } else {
100
+ nativeBinding = require('@nativescript/windows-napi-win32-arm64-msvc')
101
+ }
102
+ } catch (e) {
103
+ loadError = e
104
+ }
105
+ break
106
+ default:
107
+ throw new Error(`Unsupported architecture on Windows: ${arch}`)
108
+ }
109
+ break
110
+ case 'darwin':
111
+ localFileExisted = existsSync(join(__dirname, 'windows.darwin-universal.node'))
112
+ try {
113
+ if (localFileExisted) {
114
+ nativeBinding = require('./windows.darwin-universal.node')
115
+ } else {
116
+ nativeBinding = require('@nativescript/windows-napi-darwin-universal')
117
+ }
118
+ break
119
+ } catch {}
120
+ switch (arch) {
121
+ case 'x64':
122
+ localFileExisted = existsSync(join(__dirname, 'windows.darwin-x64.node'))
123
+ try {
124
+ if (localFileExisted) {
125
+ nativeBinding = require('./windows.darwin-x64.node')
126
+ } else {
127
+ nativeBinding = require('@nativescript/windows-napi-darwin-x64')
128
+ }
129
+ } catch (e) {
130
+ loadError = e
131
+ }
132
+ break
133
+ case 'arm64':
134
+ localFileExisted = existsSync(
135
+ join(__dirname, 'windows.darwin-arm64.node')
136
+ )
137
+ try {
138
+ if (localFileExisted) {
139
+ nativeBinding = require('./windows.darwin-arm64.node')
140
+ } else {
141
+ nativeBinding = require('@nativescript/windows-napi-darwin-arm64')
142
+ }
143
+ } catch (e) {
144
+ loadError = e
145
+ }
146
+ break
147
+ default:
148
+ throw new Error(`Unsupported architecture on macOS: ${arch}`)
149
+ }
150
+ break
151
+ case 'freebsd':
152
+ if (arch !== 'x64') {
153
+ throw new Error(`Unsupported architecture on FreeBSD: ${arch}`)
154
+ }
155
+ localFileExisted = existsSync(join(__dirname, 'windows.freebsd-x64.node'))
156
+ try {
157
+ if (localFileExisted) {
158
+ nativeBinding = require('./windows.freebsd-x64.node')
159
+ } else {
160
+ nativeBinding = require('@nativescript/windows-napi-freebsd-x64')
161
+ }
162
+ } catch (e) {
163
+ loadError = e
164
+ }
165
+ break
166
+ case 'linux':
167
+ switch (arch) {
168
+ case 'x64':
169
+ if (isMusl()) {
170
+ localFileExisted = existsSync(
171
+ join(__dirname, 'windows.linux-x64-musl.node')
172
+ )
173
+ try {
174
+ if (localFileExisted) {
175
+ nativeBinding = require('./windows.linux-x64-musl.node')
176
+ } else {
177
+ nativeBinding = require('@nativescript/windows-napi-linux-x64-musl')
178
+ }
179
+ } catch (e) {
180
+ loadError = e
181
+ }
182
+ } else {
183
+ localFileExisted = existsSync(
184
+ join(__dirname, 'windows.linux-x64-gnu.node')
185
+ )
186
+ try {
187
+ if (localFileExisted) {
188
+ nativeBinding = require('./windows.linux-x64-gnu.node')
189
+ } else {
190
+ nativeBinding = require('@nativescript/windows-napi-linux-x64-gnu')
191
+ }
192
+ } catch (e) {
193
+ loadError = e
194
+ }
195
+ }
196
+ break
197
+ case 'arm64':
198
+ if (isMusl()) {
199
+ localFileExisted = existsSync(
200
+ join(__dirname, 'windows.linux-arm64-musl.node')
201
+ )
202
+ try {
203
+ if (localFileExisted) {
204
+ nativeBinding = require('./windows.linux-arm64-musl.node')
205
+ } else {
206
+ nativeBinding = require('@nativescript/windows-napi-linux-arm64-musl')
207
+ }
208
+ } catch (e) {
209
+ loadError = e
210
+ }
211
+ } else {
212
+ localFileExisted = existsSync(
213
+ join(__dirname, 'windows.linux-arm64-gnu.node')
214
+ )
215
+ try {
216
+ if (localFileExisted) {
217
+ nativeBinding = require('./windows.linux-arm64-gnu.node')
218
+ } else {
219
+ nativeBinding = require('@nativescript/windows-napi-linux-arm64-gnu')
220
+ }
221
+ } catch (e) {
222
+ loadError = e
223
+ }
224
+ }
225
+ break
226
+ case 'arm':
227
+ if (isMusl()) {
228
+ localFileExisted = existsSync(
229
+ join(__dirname, 'windows.linux-arm-musleabihf.node')
230
+ )
231
+ try {
232
+ if (localFileExisted) {
233
+ nativeBinding = require('./windows.linux-arm-musleabihf.node')
234
+ } else {
235
+ nativeBinding = require('@nativescript/windows-napi-linux-arm-musleabihf')
236
+ }
237
+ } catch (e) {
238
+ loadError = e
239
+ }
240
+ } else {
241
+ localFileExisted = existsSync(
242
+ join(__dirname, 'windows.linux-arm-gnueabihf.node')
243
+ )
244
+ try {
245
+ if (localFileExisted) {
246
+ nativeBinding = require('./windows.linux-arm-gnueabihf.node')
247
+ } else {
248
+ nativeBinding = require('@nativescript/windows-napi-linux-arm-gnueabihf')
249
+ }
250
+ } catch (e) {
251
+ loadError = e
252
+ }
253
+ }
254
+ break
255
+ case 'riscv64':
256
+ if (isMusl()) {
257
+ localFileExisted = existsSync(
258
+ join(__dirname, 'windows.linux-riscv64-musl.node')
259
+ )
260
+ try {
261
+ if (localFileExisted) {
262
+ nativeBinding = require('./windows.linux-riscv64-musl.node')
263
+ } else {
264
+ nativeBinding = require('@nativescript/windows-napi-linux-riscv64-musl')
265
+ }
266
+ } catch (e) {
267
+ loadError = e
268
+ }
269
+ } else {
270
+ localFileExisted = existsSync(
271
+ join(__dirname, 'windows.linux-riscv64-gnu.node')
272
+ )
273
+ try {
274
+ if (localFileExisted) {
275
+ nativeBinding = require('./windows.linux-riscv64-gnu.node')
276
+ } else {
277
+ nativeBinding = require('@nativescript/windows-napi-linux-riscv64-gnu')
278
+ }
279
+ } catch (e) {
280
+ loadError = e
281
+ }
282
+ }
283
+ break
284
+ case 's390x':
285
+ localFileExisted = existsSync(
286
+ join(__dirname, 'windows.linux-s390x-gnu.node')
287
+ )
288
+ try {
289
+ if (localFileExisted) {
290
+ nativeBinding = require('./windows.linux-s390x-gnu.node')
291
+ } else {
292
+ nativeBinding = require('@nativescript/windows-napi-linux-s390x-gnu')
293
+ }
294
+ } catch (e) {
295
+ loadError = e
296
+ }
297
+ break
298
+ default:
299
+ throw new Error(`Unsupported architecture on Linux: ${arch}`)
300
+ }
301
+ break
302
+ default:
303
+ throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
304
+ }
305
+
306
+ if (!nativeBinding) {
307
+ if (loadError) {
308
+ throw loadError
309
+ }
310
+ throw new Error(`Failed to load native binding`)
311
+ }
312
+
313
+ const { formatValue, tableFor, makeDelegate, invokeDelegate, releaseDelegate, callStaticMethod, callInstanceMethod, makeNativeProxy, ffiRoundtrip, pointerValue, makeExternal, bufferInfo, structPtr, writeReadPtr, outParamValue, setOutParam, structFieldBytes, boxTyped, pumpMessages, lastError, installGlobals, getNamespace, nsUuid, createWindow, attachCompositorToWindow, pollWindowEvents, getWindowSize, setWindowTitle, xamlHostCreate, xamlHostSetListener, xamlHostPlace, xamlHostShow, xamlHostHide, xamlHostIsVisible, xamlHostDestroy, foregroundWindow, activateWindow, enableWindow, windowProcessId, classIsSealed, registerWinmd, scanWinmdDir, arrayBufferFromBuffer, installInterop, installDotnet } = nativeBinding
314
+
315
+ module.exports.formatValue = formatValue
316
+ module.exports.tableFor = tableFor
317
+ module.exports.makeDelegate = makeDelegate
318
+ module.exports.invokeDelegate = invokeDelegate
319
+ module.exports.releaseDelegate = releaseDelegate
320
+ module.exports.callStaticMethod = callStaticMethod
321
+ module.exports.callInstanceMethod = callInstanceMethod
322
+ module.exports.makeNativeProxy = makeNativeProxy
323
+ module.exports.ffiRoundtrip = ffiRoundtrip
324
+ module.exports.pointerValue = pointerValue
325
+ module.exports.makeExternal = makeExternal
326
+ module.exports.bufferInfo = bufferInfo
327
+ module.exports.structPtr = structPtr
328
+ module.exports.writeReadPtr = writeReadPtr
329
+ module.exports.outParamValue = outParamValue
330
+ module.exports.setOutParam = setOutParam
331
+ module.exports.structFieldBytes = structFieldBytes
332
+ module.exports.boxTyped = boxTyped
333
+ module.exports.pumpMessages = pumpMessages
334
+ module.exports.lastError = lastError
335
+ module.exports.installGlobals = installGlobals
336
+ module.exports.getNamespace = getNamespace
337
+ module.exports.nsUuid = nsUuid
338
+ module.exports.createWindow = createWindow
339
+ module.exports.attachCompositorToWindow = attachCompositorToWindow
340
+ module.exports.pollWindowEvents = pollWindowEvents
341
+ module.exports.getWindowSize = getWindowSize
342
+ module.exports.setWindowTitle = setWindowTitle
343
+ module.exports.xamlHostCreate = xamlHostCreate
344
+ module.exports.xamlHostSetListener = xamlHostSetListener
345
+ module.exports.xamlHostPlace = xamlHostPlace
346
+ module.exports.xamlHostShow = xamlHostShow
347
+ module.exports.xamlHostHide = xamlHostHide
348
+ module.exports.xamlHostIsVisible = xamlHostIsVisible
349
+ module.exports.xamlHostDestroy = xamlHostDestroy
350
+ module.exports.foregroundWindow = foregroundWindow
351
+ module.exports.activateWindow = activateWindow
352
+ module.exports.enableWindow = enableWindow
353
+ module.exports.windowProcessId = windowProcessId
354
+ module.exports.classIsSealed = classIsSealed
355
+ module.exports.registerWinmd = registerWinmd
356
+ module.exports.scanWinmdDir = scanWinmdDir
357
+ module.exports.arrayBufferFromBuffer = arrayBufferFromBuffer
358
+ module.exports.installInterop = installInterop
359
+ module.exports.installDotnet = installDotnet
package/nswinrt.js ADDED
@@ -0,0 +1,217 @@
1
+ // NSWinRT JS helper layer (ships with the package alongside the native addon).
2
+ // Pure JS that operates on the native WinRT proxies — async→Promise, event helpers.
3
+ // Mirrors the runtime's HELPER_SOURCE `toPromise`, adapted for the napi backend where the
4
+ // host owns the loop (the consumer pumps via `pumpMessages`).
5
+ 'use strict';
6
+ const native = require('./index.js');
7
+
8
+ const Windows = native.getNamespace('Windows');
9
+
10
+ function statusEnum() {
11
+ try { return Windows.Foundation.AsyncStatus; }
12
+ catch { return { Started: 0, Completed: 1, Canceled: 2, Error: 3 }; }
13
+ }
14
+
15
+ function normalizeStatus(status) {
16
+ if (status == null) return NaN;
17
+ if (typeof status === 'number') return status;
18
+ const n = Number(status);
19
+ return Number.isNaN(n) ? NaN : n;
20
+ }
21
+
22
+ // Pump lifecycle: while any WinRT async op is outstanding, the pump timer is ref'd so Node
23
+ // stays alive to deliver Completed; when the last settles, it is unref'd so the process can
24
+ // exit. (An unref'd-only timer would let Node exit before completion fires.)
25
+ let pending = 0;
26
+ function retainPump() {
27
+ pending += 1;
28
+ if (autoPumpTimer && typeof autoPumpTimer.ref === 'function') autoPumpTimer.ref();
29
+ }
30
+ function releasePump() {
31
+ pending = Math.max(0, pending - 1);
32
+ if (pending === 0 && autoPumpTimer && typeof autoPumpTimer.unref === 'function') {
33
+ autoPumpTimer.unref();
34
+ }
35
+ }
36
+
37
+ // Convert a WinRT IAsyncOperation/IAsyncAction proxy to a JS Promise via its Completed event,
38
+ // Status property, and GetResults() method — all provided by the native proxy layer.
39
+ function toPromise(op) {
40
+ if (op == null || (typeof op !== 'object' && typeof op !== 'function')) {
41
+ return Promise.resolve(op);
42
+ }
43
+ if (typeof op.then === 'function' && !('Completed' in op)) return op;
44
+
45
+ const S = statusEnum();
46
+ retainPump();
47
+ return new Promise((resolve, reject) => {
48
+ let settled = false;
49
+ const done = (fn, arg) => { settled = true; releasePump(); fn(arg); };
50
+ const settle = (override) => {
51
+ if (settled) return;
52
+ try {
53
+ const status = normalizeStatus(override !== undefined ? override : op.Status);
54
+ if (status === S.Completed || status === 1) {
55
+ done(resolve, typeof op.GetResults === 'function' ? op.GetResults() : undefined);
56
+ } else if (status === S.Canceled || status === 2) {
57
+ done(reject, new Error('WinRT async operation was canceled'));
58
+ } else if (status === S.Error || status === 3) {
59
+ done(reject, op.ErrorCode || new Error('WinRT async operation failed'));
60
+ }
61
+ } catch (err) { done(reject, err); }
62
+ };
63
+
64
+ const initial = normalizeStatus(op.Status);
65
+ if (!Number.isNaN(initial) && initial !== 0) { settle(initial); return; }
66
+ op.Completed = (asyncInfo, asyncStatus) => settle(asyncStatus);
67
+ // Race guard: it may have completed between the status read and handler assignment.
68
+ const race = normalizeStatus(op.Status);
69
+ if (!Number.isNaN(race) && race !== 0) settle(race);
70
+ });
71
+ }
72
+
73
+ // Drive the Windows message loop until `promise` settles or `timeoutMs` elapses. WinRT STA
74
+ // async completions are delivered as messages, so the loop must be pumped for them to fire.
75
+ async function awaitWithPump(promise, timeoutMs = 5000) {
76
+ let done = false, result, error, ok;
77
+ promise.then((r) => { done = true; ok = true; result = r; },
78
+ (e) => { done = true; ok = false; error = e; });
79
+ const start = Date.now();
80
+ while (!done && Date.now() - start < timeoutMs) {
81
+ native.pumpMessages();
82
+ await new Promise((r) => setImmediate(r));
83
+ }
84
+ if (!done) throw new Error('awaitWithPump timed out');
85
+ if (!ok) throw error;
86
+ return result;
87
+ }
88
+
89
+ // Pump the WinRT message loop automatically on a Node timer so awaiting WinRT Promises is
90
+ // transparent (no manual `awaitWithPump`). The timer is unref'd, so it never keeps the process
91
+ // alive on its own. Returns a stop function. Safe to call once at startup.
92
+ let autoPumpTimer = null;
93
+ function enableAutoPump(intervalMs = 4) {
94
+ if (autoPumpTimer) return () => disableAutoPump();
95
+ autoPumpTimer = setInterval(() => { native.pumpMessages(); }, intervalMs);
96
+ if (typeof autoPumpTimer.unref === 'function') autoPumpTimer.unref();
97
+ return () => disableAutoPump();
98
+ }
99
+ function disableAutoPump() {
100
+ if (autoPumpTimer) { clearInterval(autoPumpTimer); autoPumpTimer = null; }
101
+ }
102
+
103
+ // interop.* — the full NSWinRT.interop surface (Pointer/OutParam, reference/typed-value
104
+ // boxing, buffer + DateTime utilities, uuid/winmd registration, zero-copy
105
+ // arrayBufferFromBuffer). Installed by the shared native layer so the surface is identical
106
+ // across Node/Bun/Deno and the standalone engine hosts.
107
+ native.installInterop();
108
+ const interop = globalThis.NSWinRT.interop;
109
+
110
+ // dotnet.* — the .NET/BCL bridge (NSWinRT.dotnet: invoke/get/fromHandle/registerNamespace,
111
+ // taskToPromise/asDelegate, plus NSWinRT.runOnUIThread). A no-op at the JS layer until a
112
+ // dotnet-bridge/publish/DotNetBridge.dll exists next to the app.
113
+ native.installDotnet();
114
+ const dotnet = globalThis.NSWinRT.dotnet;
115
+
116
+ // Windows.UI.Xaml content in a Win32 window (XAML Islands). Needs a thread that pumps messages.
117
+ let xamlManager = null;
118
+
119
+ function systemTheme() {
120
+ const vm = Windows.UI.ViewManagement;
121
+ const bg = new vm.UISettings().GetColorValue(vm.UIColorType.Background);
122
+ return bg.R < 128 ? 'dark' : 'light';
123
+ }
124
+
125
+ class XamlWindow {
126
+ /**
127
+ * @param {object} [options]
128
+ * @param {'dialog'|'popup'} [options.style] dialog: title bar and close box; popup: borderless,
129
+ * not in the taskbar or Alt+Tab.
130
+ * @param {number|bigint|Buffer} [options.owner] owner window handle.
131
+ * @param {string} [options.title]
132
+ * @param {boolean} [options.topmost]
133
+ * @param {'system'|'dark'|'light'} [options.theme] title bar theme; read it back from `theme`.
134
+ */
135
+ constructor(options = {}) {
136
+ if (!xamlManager) {
137
+ try {
138
+ xamlManager = Windows.UI.Xaml.Hosting.WindowsXamlManager.InitializeForCurrentThread();
139
+ } catch (e) {
140
+ if (!/0x8000FFFF/i.test(String(e && e.message))) throw e;
141
+ throw new Error('XamlWindow: XAML Islands are unavailable in this process. The host ' +
142
+ 'executable\'s manifest must declare <maxversiontested Id="10.0.18362.0"/> or later.');
143
+ }
144
+ }
145
+ const { theme = 'system', ...rest } = options;
146
+ this.theme = theme === 'system' ? systemTheme() : theme;
147
+ this.source = new Windows.UI.Xaml.Hosting.DesktopWindowXamlSource();
148
+ this.hwnd = native.xamlHostCreate(this.source, { ...rest, dark: this.theme === 'dark' });
149
+ this.closed = false;
150
+ this._handlers = { activate: [], deactivate: [], close: [], closed: [] };
151
+ native.xamlHostSetListener(this.hwnd, (type) => this._emit(type));
152
+ }
153
+
154
+ get content() { return this.source.Content; }
155
+ set content(element) { this.source.Content = element; }
156
+
157
+ get visible() { return !this.closed && native.xamlHostIsVisible(this.hwnd); }
158
+
159
+ /** `activate`, `deactivate`, `close` (title-bar X or Alt+F4; closes when unhandled), `closed`. */
160
+ on(type, fn) {
161
+ if (!this._handlers[type]) throw new TypeError(`XamlWindow: unknown event '${type}'`);
162
+ this._handlers[type].push(fn);
163
+ return this;
164
+ }
165
+
166
+ off(type, fn) {
167
+ const list = this._handlers[type];
168
+ if (list && list.includes(fn)) list.splice(list.indexOf(fn), 1);
169
+ return this;
170
+ }
171
+
172
+ /** Client size in DIPs; centered over `over`, or on the pointer's monitor at `y` (0..1). */
173
+ place({ width, height, over, y } = {}) {
174
+ native.xamlHostPlace(this.hwnd, { width, height, over, y });
175
+ return this;
176
+ }
177
+
178
+ /** Returns whether the window is in the foreground. */
179
+ show({ activate = true } = {}) { return native.xamlHostShow(this.hwnd, activate); }
180
+
181
+ hide() { if (!this.closed) native.xamlHostHide(this.hwnd); }
182
+
183
+ close() { if (!this.closed) native.xamlHostDestroy(this.hwnd); }
184
+
185
+ _emit(type) {
186
+ if (type === 'closed') {
187
+ this.closed = true;
188
+ try { this.source.Close(); } catch {}
189
+ }
190
+ const handlers = this._handlers[type].slice();
191
+ if (type === 'close' && handlers.length === 0) this.close();
192
+ for (const fn of handlers) {
193
+ // Rethrown outside the native callback so the host reports it as uncaught.
194
+ try { fn(); } catch (e) { setTimeout(() => { throw e; }); }
195
+ }
196
+ }
197
+
198
+ static systemTheme() { return systemTheme(); }
199
+ /** The foreground window of any process, as a number (0 if none). */
200
+ static foregroundWindow() { return native.foregroundWindow(); }
201
+ /** Bring a window to the foreground; `false` if Windows refuses. */
202
+ static activateWindow(hwnd) { return native.activateWindow(hwnd); }
203
+ static enableWindow(hwnd, enabled) { native.enableWindow(hwnd, enabled); }
204
+ static windowProcessId(hwnd) { return native.windowProcessId(hwnd); }
205
+ }
206
+
207
+ module.exports = {
208
+ native,
209
+ Windows,
210
+ toPromise,
211
+ awaitWithPump,
212
+ enableAutoPump,
213
+ disableAutoPump,
214
+ interop,
215
+ dotnet,
216
+ XamlWindow,
217
+ };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
- {
2
- "name": "@nativescript/windows-napi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@nativescript/windows-napi",
3
+ "version": "1.0.0-beta.21",
4
+ "description": "Node-API WinRT interop for Windows.",
5
+ "main": "nswinrt.js",
6
+ "types": "index.d.ts",
7
+ "exports": {
8
+ ".": "./nswinrt.js",
9
+ "./native": "./index.js",
10
+ "./nswinrt.js": "./nswinrt.js"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "index.d.ts",
15
+ "nswinrt.js",
16
+ "windows.*.node"
17
+ ],
18
+ "napi": {
19
+ "name": "windows",
20
+ "triples": {
21
+ "defaults": false,
22
+ "additional": [
23
+ "x86_64-pc-windows-msvc",
24
+ "aarch64-pc-windows-msvc"
25
+ ]
26
+ }
27
+ },
28
+ "os": [
29
+ "win32"
30
+ ],
31
+ "engines": {
32
+ "node": ">= 18"
33
+ },
34
+ "scripts": {
35
+ "build": "napi build --platform --release",
36
+ "build:debug": "napi build --platform",
37
+ "test": "node test/run-tests.js"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/NativeScript/windows",
42
+ "directory": "windows-napi"
43
+ },
44
+ "devDependencies": {
45
+ "@napi-rs/cli": "^2.18.0"
46
+ }
47
+ }
Binary file
Binary file