@node-ctypes/comtypes 0.1.1 → 0.3.0

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 (57) hide show
  1. package/README.md +114 -47
  2. package/dist/automation/dispatch.d.ts +6 -0
  3. package/dist/automation/dispatch.js +78 -29
  4. package/dist/automation/members.js +31 -22
  5. package/dist/automation/variant.d.ts +2 -0
  6. package/dist/automation/variant.js +38 -1
  7. package/dist/cli.js +7 -2
  8. package/dist/client/best.d.ts +6 -0
  9. package/dist/client/best.js +89 -45
  10. package/dist/client/constants.js +2 -2
  11. package/dist/client/dual.d.ts +14 -0
  12. package/dist/client/dual.js +122 -0
  13. package/dist/client/dynamic.d.ts +21 -9
  14. package/dist/client/dynamic.js +123 -18
  15. package/dist/client/events.js +11 -11
  16. package/dist/client/index.d.ts +39 -19
  17. package/dist/client/index.js +124 -17
  18. package/dist/commethod.js +67 -18
  19. package/dist/dispmethod.js +26 -5
  20. package/dist/executor/apartment.d.ts +32 -0
  21. package/dist/executor/apartment.js +226 -0
  22. package/dist/executor/classes.d.ts +10 -0
  23. package/dist/executor/classes.js +18 -0
  24. package/dist/executor/executor.d.ts +76 -0
  25. package/dist/executor/executor.js +208 -0
  26. package/dist/executor/operations.d.ts +29 -0
  27. package/dist/executor/operations.js +95 -0
  28. package/dist/index.d.ts +6 -2
  29. package/dist/index.js +3 -1
  30. package/dist/interface.d.ts +43 -3
  31. package/dist/interface.js +28 -8
  32. package/dist/interfaces/servprov.js +2 -2
  33. package/dist/low-level/index.d.ts +2 -0
  34. package/dist/low-level/index.js +1 -0
  35. package/dist/low-level/native.d.ts +6 -0
  36. package/dist/low-level/native.js +13 -1
  37. package/dist/pointer.d.ts +57 -6
  38. package/dist/pointer.js +233 -9
  39. package/dist/server/comobject.js +9 -3
  40. package/dist/server/errorinfo.js +6 -6
  41. package/dist/server/register.js +5 -0
  42. package/dist/threads.js +4 -4
  43. package/dist/tracking.d.ts +2 -0
  44. package/dist/tracking.js +4 -0
  45. package/dist/typelib/build.d.ts +5 -0
  46. package/dist/typelib/build.js +8 -1
  47. package/dist/typelib/generate.js +14 -11
  48. package/dist/typelib/getmodule.d.ts +14 -3
  49. package/dist/typelib/getmodule.js +61 -19
  50. package/dist/typelib/index.d.ts +1 -1
  51. package/dist/typelib/index.js +1 -1
  52. package/dist/typelib/load.js +32 -8
  53. package/dist/typelib/model.d.ts +3 -0
  54. package/dist/typelib/model.js +87 -66
  55. package/dist/typelib/steps.d.ts +12 -0
  56. package/dist/typelib/steps.js +51 -0
  57. package/package.json +2 -2
@@ -0,0 +1,208 @@
1
+ // The COM executor: a node-ctypes Executor (a native thread with a FIFO queue)
2
+ // in the multithreaded apartment. Native calls prepared on the JavaScript
3
+ // thread run there one at a time, in arrival order, so that the JavaScript
4
+ // thread never waits for them. IErrorInfo is per thread: the job queued right
5
+ // after each HRESULT call takes it on the same thread.
6
+ import * as ctypes from "node-ctypes";
7
+ import { COINIT_MULTITHREADED } from "../constants.js";
8
+ import { GUID } from "../guid.js";
9
+ import { ole32, oleaut32, takeBSTR } from "../low-level/native.js";
10
+ import { functionCache, vtableEntry } from "../low-level/vtable.js";
11
+ const { c_int32, c_uint32, c_void_p } = ctypes;
12
+ const IID_ISupportErrorInfo = new GUID("{DF0B3D60-548F-101B-8E65-08002B2BD119}");
13
+ // IErrorInfo getters and ISupportErrorInfo::InterfaceSupportsErrorInfo share
14
+ // the HRESULT (this, pointer) signature.
15
+ const PointerArgAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p));
16
+ const QueryInterfaceAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p));
17
+ const ReleaseAt = functionCache(() => ctypes.WINFUNCTYPE(c_uint32, c_void_p));
18
+ let executor = null;
19
+ let closing = null;
20
+ let generation = 0;
21
+ let exitHandler = null;
22
+ /** The running executor, started on first use with its thread in the multithreaded apartment. */
23
+ function current() {
24
+ if (executor)
25
+ return executor;
26
+ const created = new ctypes.Executor({ name: "node-comtypes" });
27
+ // The first job: every later one runs in the multithreaded apartment. A
28
+ // failure surfaces as CO_E_NOTINITIALIZED from the calls themselves.
29
+ ole32()
30
+ .CoInitializeEx.callOn(created, null, COINIT_MULTITHREADED)
31
+ .catch(() => undefined);
32
+ executor = created;
33
+ generation++;
34
+ if (!exitHandler) {
35
+ // As node-python: finalize on a normal exit, so that proxies to other
36
+ // processes are released; a forced process.exit() abandons the thread.
37
+ exitHandler = () => void finalize();
38
+ process.on("beforeExit", exitHandler);
39
+ }
40
+ return created;
41
+ }
42
+ /** The running executor (started on demand), for code that queues its own calls. */
43
+ export function executorTarget() {
44
+ return current();
45
+ }
46
+ /** Counters of the COM executor. Python equivalent: node-python's `python.stats()`. */
47
+ export function stats() {
48
+ return { running: executor?.running ?? false, pending: executor?.pending ?? 0, completed: executor?.completed ?? 0, generation };
49
+ }
50
+ /** Whether references owned by executor `generation` are still alive (its executor is running). */
51
+ export function executorAlive(generation) {
52
+ return executor !== null && generation === executorGeneration();
53
+ }
54
+ /** Generation of the current executor (0 before the first one starts). */
55
+ export function executorGeneration() {
56
+ return generation;
57
+ }
58
+ /**
59
+ * Drain the operations already accepted by the COM executor, leave its
60
+ * apartment and stop its thread; resolves once their promises have settled. Called automatically on a normal
61
+ * `beforeExit`. A later asynchronous operation starts a new executor.
62
+ */
63
+ export function finalize() {
64
+ if (closing)
65
+ return closing;
66
+ const stopping = executor;
67
+ if (!stopping)
68
+ return Promise.resolve();
69
+ executor = null;
70
+ if (exitHandler) {
71
+ process.off("beforeExit", exitHandler);
72
+ exitHandler = null;
73
+ }
74
+ // FIFO: after every accepted call, before the thread stops.
75
+ ole32()
76
+ .CoUninitialize.callOn(stopping)
77
+ .catch(() => undefined);
78
+ // The promises of the drained operations settle a few microtasks after their
79
+ // calls: one more turn of the event loop lets them settle first.
80
+ closing = stopping
81
+ .close()
82
+ .then(() => new Promise((resolve) => setImmediate(resolve)))
83
+ .finally(() => {
84
+ closing = null;
85
+ });
86
+ return closing;
87
+ }
88
+ const prototypes = new WeakMap();
89
+ /** The native function at `address`, bound once per signature and address. */
90
+ function bind(restype, argtypes, address) {
91
+ let byRestype = prototypes.get(argtypes);
92
+ if (!byRestype)
93
+ prototypes.set(argtypes, (byRestype = new Map()));
94
+ let cache = byRestype.get(restype);
95
+ if (!cache)
96
+ byRestype.set(restype, (cache = functionCache(() => ctypes.WINFUNCTYPE(restype, ...argtypes))));
97
+ return cache(address);
98
+ }
99
+ /** Id of the last call submitted to `target`: another call was submitted after a call whose id is lower. */
100
+ export function lastJob(target) {
101
+ return target._lastJob;
102
+ }
103
+ /** Remove call `job` from the queue of `target` if it has not started: its promise rejects with `reason`. */
104
+ export function cancelJob(target, job, reason) {
105
+ return target._cancel(job, reason);
106
+ }
107
+ /** Queue `GetErrorInfo` on `target`: the thread's error object (owned), or `null`. */
108
+ function takeErrorObject(target) {
109
+ const out = new c_void_p();
110
+ return oleaut32()
111
+ .GetErrorInfo.callOn(target, 0, ctypes.byref(out))
112
+ .then((hr) => (hr === 0 && out.value ? out.value : null));
113
+ }
114
+ function release(target, address) {
115
+ ReleaseAt(vtableEntry(address, 2))
116
+ .callOn(target, address)
117
+ .catch(() => undefined);
118
+ }
119
+ /** Whether `object` declares error information for interface `iid` (ISupportErrorInfo), on the executor. */
120
+ async function supportsErrorInfo(target, object, iid) {
121
+ const out = new c_void_p();
122
+ const hr = await QueryInterfaceAt(vtableEntry(object, 0)).callOn(target, object, IID_ISupportErrorInfo._buffer, ctypes.byref(out));
123
+ if (hr < 0 || !out.value)
124
+ return false;
125
+ const support = out.value;
126
+ try {
127
+ return (await PointerArgAt(vtableEntry(support, 3)).callOn(target, support, iid._buffer)) === 0;
128
+ }
129
+ finally {
130
+ release(target, support);
131
+ }
132
+ }
133
+ /** Read an error object on the executor, where it belongs (it may be a proxy). */
134
+ async function readErrorObject(target, errorObject) {
135
+ const guid = new GUID();
136
+ const context = new c_uint32();
137
+ const strings = [4, 5, 6].map(() => new c_void_p());
138
+ const [hasGuid, source, description, helpFile, hasContext] = await Promise.all([
139
+ PointerArgAt(vtableEntry(errorObject, 3)).callOn(target, errorObject, guid._buffer),
140
+ ...strings.map((out, index) => PointerArgAt(vtableEntry(errorObject, 4 + index)).callOn(target, errorObject, ctypes.byref(out))),
141
+ PointerArgAt(vtableEntry(errorObject, 7)).callOn(target, errorObject, ctypes.byref(context)),
142
+ ]);
143
+ // BSTRs are allocated by the task allocator: freed from any thread.
144
+ const text = (hr, out) => (hr >= 0 ? takeBSTR(out.value) : null);
145
+ return {
146
+ guid: hasGuid >= 0 && !guid.isNull() ? guid : null,
147
+ source: text(source, strings[0]),
148
+ description: text(description, strings[1]),
149
+ helpFile: text(helpFile, strings[2]),
150
+ helpContext: hasContext >= 0 ? context.value : 0,
151
+ };
152
+ }
153
+ async function errorDetails(target, errorObject, errorInfo) {
154
+ const taken = await errorObject;
155
+ if (!taken)
156
+ return null;
157
+ try {
158
+ // As Python comtypes: only for an object that declares support for the interface.
159
+ if (!(await supportsErrorInfo(target, errorInfo.object, new GUID(errorInfo.iid))))
160
+ return null;
161
+ return await readErrorObject(target, taken);
162
+ }
163
+ catch {
164
+ return null;
165
+ }
166
+ finally {
167
+ release(target, taken);
168
+ }
169
+ }
170
+ /**
171
+ * Run a raw native call (e.g. a vtable entry, with `this` as the first
172
+ * argument) on the COM executor thread. Memory passed by address stays
173
+ * referenced until the call completes; for HRESULT failures, `errorInfo`
174
+ * reads `IErrorInfo` on the executor thread.
175
+ *
176
+ * As Python comtypes, `GetErrorInfo` runs only after a failure, and it must
177
+ * be the next call on the executor thread: a later call could replace or clear
178
+ * the error object. That holds when nothing was submitted after the failed
179
+ * call (code that awaits each call); otherwise, e.g. in a burst of calls
180
+ * already queued, the failure has no details.
181
+ */
182
+ export function executorCall(call, options = {}) {
183
+ // A single promise step after the call (no async function): this runs for every method call.
184
+ let target;
185
+ let pending;
186
+ let job;
187
+ try {
188
+ target = current();
189
+ const fn = bind(call.restype, call.argtypes, call.fn);
190
+ if (options.operation?.aborted)
191
+ throw options.operation.reason;
192
+ // The id of this call, written by node-ctypes for this invocation only.
193
+ const callTarget = { executor: target, signal: options.signal, _job: 0 };
194
+ pending = fn.callOn(callTarget, ...call.args);
195
+ job = callTarget._job;
196
+ if (job !== 0)
197
+ options.operation?.queued(target, job);
198
+ }
199
+ catch (error) {
200
+ return Promise.reject(error);
201
+ }
202
+ const { errorInfo } = call;
203
+ return pending.then((value) => {
204
+ if (!(typeof value === "number" && value < 0) || !errorInfo || lastJob(target) !== job)
205
+ return { value, details: null };
206
+ return errorDetails(target, takeErrorObject(target), errorInfo).then((details) => ({ value, details }));
207
+ });
208
+ }
@@ -0,0 +1,29 @@
1
+ import type * as ctypes from "node-ctypes";
2
+ /** The executor calls of one asynchronous operation, cancelled by `run()`. */
3
+ export declare class Operation {
4
+ #private;
5
+ /** Whether `run()` aborted the operation: its next calls are rejected with {@link reason}. */
6
+ get aborted(): boolean;
7
+ get reason(): unknown;
8
+ /** Record call `job` just queued on `executor`. */
9
+ queued(executor: ctypes.Executor, job: number): void;
10
+ /** Remove the queued calls not started yet; their promises reject with `reason`. */
11
+ abort(reason: unknown): void;
12
+ }
13
+ /** Start an operation whose executor calls are recorded in `operation`; `run()` can then cancel it. */
14
+ export declare function operation<T>(start: (operation: Operation) => Promise<T>): Promise<T>;
15
+ /** `derived` (e.g. a converted result of `source`) cancels the operation of `source`. */
16
+ export declare function linkOperation<T>(derived: Promise<T>, source: Promise<unknown>): Promise<T>;
17
+ export interface RunOptions {
18
+ /** Aborting it rejects with `signal.reason` and skips the operation's queued executor calls. */
19
+ readonly signal?: AbortSignal;
20
+ }
21
+ /**
22
+ * Await a COM operation (the promise of a method call, `CreateObject`,
23
+ * `GetObject`, ...) with an AbortSignal: `run(obj.Slow(), { signal:
24
+ * AbortSignal.timeout(1000) })`. On abort the promise rejects with
25
+ * `signal.reason`; executor calls still queued are skipped, a running call
26
+ * completes (COM does not interrupt it). Python equivalent: none
27
+ * (node-python's `python.run`).
28
+ */
29
+ export declare function run<T>(promise: PromiseLike<T>, { signal }?: RunOptions): Promise<T>;
@@ -0,0 +1,95 @@
1
+ // Asynchronous COM operations and their cancellation, as node-python's
2
+ // `run(promise, { signal })`: an operation records the calls it queues on the
3
+ // executor, and aborting it removes those not started yet; calls already
4
+ // running complete. No AbortController or listener per call: only `run()`
5
+ // with a signal pays for cancellation.
6
+ import { cancelJob } from "./executor.js";
7
+ /** The executor calls of one asynchronous operation, cancelled by `run()`. */
8
+ export class Operation {
9
+ #aborted = false;
10
+ #reason;
11
+ // The first queued call, then the others (an operation usually makes one).
12
+ #executor = null;
13
+ #job = 0;
14
+ #more = null;
15
+ /** Whether `run()` aborted the operation: its next calls are rejected with {@link reason}. */
16
+ get aborted() {
17
+ return this.#aborted;
18
+ }
19
+ get reason() {
20
+ return this.#reason;
21
+ }
22
+ /** Record call `job` just queued on `executor`. */
23
+ queued(executor, job) {
24
+ if (this.#executor === null) {
25
+ this.#executor = executor;
26
+ this.#job = job;
27
+ }
28
+ else {
29
+ (this.#more ??= []).push([executor, job]);
30
+ }
31
+ }
32
+ /** Remove the queued calls not started yet; their promises reject with `reason`. */
33
+ abort(reason) {
34
+ if (this.#aborted)
35
+ return;
36
+ this.#aborted = true;
37
+ this.#reason = reason;
38
+ if (this.#executor)
39
+ cancelJob(this.#executor, this.#job, reason);
40
+ for (const [executor, job] of this.#more ?? [])
41
+ cancelJob(executor, job, reason);
42
+ this.#executor = null;
43
+ this.#more = null;
44
+ }
45
+ }
46
+ const operations = new WeakMap();
47
+ /** Start an operation whose executor calls are recorded in `operation`; `run()` can then cancel it. */
48
+ export function operation(start) {
49
+ const current = new Operation();
50
+ const promise = start(current);
51
+ operations.set(promise, current);
52
+ return promise;
53
+ }
54
+ /** `derived` (e.g. a converted result of `source`) cancels the operation of `source`. */
55
+ export function linkOperation(derived, source) {
56
+ const current = operations.get(source);
57
+ if (current)
58
+ operations.set(derived, current);
59
+ return derived;
60
+ }
61
+ function isThenable(value) {
62
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
63
+ }
64
+ /**
65
+ * Await a COM operation (the promise of a method call, `CreateObject`,
66
+ * `GetObject`, ...) with an AbortSignal: `run(obj.Slow(), { signal:
67
+ * AbortSignal.timeout(1000) })`. On abort the promise rejects with
68
+ * `signal.reason`; executor calls still queued are skipped, a running call
69
+ * completes (COM does not interrupt it). Python equivalent: none
70
+ * (node-python's `python.run`).
71
+ */
72
+ export function run(promise, { signal } = {}) {
73
+ if (!isThenable(promise))
74
+ return Promise.reject(new TypeError("run() needs the promise of a COM operation"));
75
+ if (!signal)
76
+ return Promise.resolve(promise);
77
+ const current = operations.get(promise);
78
+ return new Promise((resolve, reject) => {
79
+ const abort = () => {
80
+ current?.abort(signal.reason);
81
+ reject(signal.reason);
82
+ };
83
+ Promise.resolve(promise).then((value) => {
84
+ signal.removeEventListener("abort", abort);
85
+ resolve(value);
86
+ }, (error) => {
87
+ signal.removeEventListener("abort", abort);
88
+ reject(error);
89
+ });
90
+ if (signal.aborted)
91
+ abort();
92
+ else
93
+ signal.addEventListener("abort", abort, { once: true });
94
+ });
95
+ }
package/dist/index.d.ts CHANGED
@@ -4,8 +4,12 @@ export * from "./hresult.ts";
4
4
  export { COMError, checkHRESULT, hresultText, systemMessage } from "./errors.ts";
5
5
  export type { COMErrorDetails, COMErrorOptions } from "./errors.ts";
6
6
  export { takeErrorInfo } from "./errorinfo.ts";
7
+ export { stats, finalize } from "./executor/executor.ts";
8
+ export { run } from "./executor/operations.ts";
9
+ export type { RunOptions } from "./executor/operations.ts";
10
+ export type { ExecutorStats } from "./executor/executor.ts";
7
11
  export { COMInterface, STDMETHOD, HRESULT, findInterface, derivesFrom } from "./interface.ts";
8
- export type { DispatchCall, InterfaceDef, ComInterfaceDef, InterfacePointer, InterfaceSpec, InterfaceMethods, MethodSpec, MethodKind, MethodMarshal, MethodFunction, MethodResult, MethodsOf, PropertiesOf, PointerClass, RawFunction, } from "./interface.ts";
12
+ export type { Asynchronous, DispatchCall, DispatchCallAsync, InterfaceDef, ComInterfaceDef, InterfacePointer, InterfaceSpec, InterfaceMethods, MethodSpec, MethodKind, MethodMarshal, MethodMarshalAsync, MethodFunction, MethodResult, MethodsOf, NativeRunner, PropertiesOf, PointerClass, RawFunction, SyncInterfaceMethods, SyncMethodsOf, SyncPointer, Synchronous, } from "./interface.ts";
9
13
  export { COMMETHOD, BSTR, LPOLESTR, REFGUID, REFIID, REFCLSID, SAFEARRAY, SELF, DATE, CURRENCY, lazy, dispid, helpstring, classifyParamType, resolveParamInterface } from "./commethod.ts";
10
14
  export type { ComParamType, ParamFlag, ParamSpec, ParamInfo, IdlFlag, DispIdFlag, HelpStringFlag, InValue, OutValue, ArgumentsOf, OutputsOf, CommethodResult, CommethodFunction, CommethodSpec, ComObject, BSTRType, LPOLESTRType, RefGuidType, SafeArrayType, SelfMarker, LazyInterface, DateType, CurrencyType, ParamKind, } from "./commethod.ts";
11
15
  export { COMPointer } from "./pointer.ts";
@@ -24,4 +28,4 @@ export * from "./typelib/index.ts";
24
28
  export { marshalInterface, unmarshalInterface, unmarshalDispatch, releaseMarshaled, GlobalInterfaceTable, IGlobalInterfaceTable, CLSID_StdGlobalInterfaceTable } from "./threads.ts";
25
29
  export type { MarshaledInterface } from "./threads.ts";
26
30
  export type { MessagePump } from "./pump.ts";
27
- export declare const version = "0.1.1";
31
+ export declare const version = "0.2.0";
package/dist/index.js CHANGED
@@ -2,6 +2,8 @@ export { GUID, GUID_NULL, toGUID } from "./guid.js";
2
2
  export * from "./hresult.js";
3
3
  export { COMError, checkHRESULT, hresultText, systemMessage } from "./errors.js";
4
4
  export { takeErrorInfo } from "./errorinfo.js";
5
+ export { stats, finalize } from "./executor/executor.js";
6
+ export { run } from "./executor/operations.js";
5
7
  export { COMInterface, STDMETHOD, HRESULT, findInterface, derivesFrom } from "./interface.js";
6
8
  export { COMMETHOD, BSTR, LPOLESTR, REFGUID, REFIID, REFCLSID, SAFEARRAY, SELF, DATE, CURRENCY, lazy, dispid, helpstring, classifyParamType, resolveParamInterface } from "./commethod.js";
7
9
  export { COMPointer } from "./pointer.js";
@@ -15,4 +17,4 @@ export { pumpMessages, PumpEvents, startMessagePump, waitFor } from "./pump.js";
15
17
  export { DISPMETHOD, DISPPROPERTY } from "./dispmethod.js";
16
18
  export * from "./typelib/index.js";
17
19
  export { marshalInterface, unmarshalInterface, unmarshalDispatch, releaseMarshaled, GlobalInterfaceTable, IGlobalInterfaceTable, CLSID_StdGlobalInterfaceTable } from "./threads.js";
18
- export const version = "0.1.1";
20
+ export const version = "0.2.0";
@@ -4,6 +4,7 @@ import type { GUIDLike } from "./guid.ts";
4
4
  import { COMPointer } from "./pointer.ts";
5
5
  import type { Slot } from "./pointer.ts";
6
6
  import type { ArgumentsOf, CommethodFunction, OutValue, ParamSpec } from "./commethod.ts";
7
+ import type { ResultLocation } from "./executor/apartment.ts";
7
8
  /** HRESULT restype marker: such methods raise {@link COMError} on failure. */
8
9
  export declare const HRESULT: ctypes.SimpleCDataConstructor<"int32"> & {
9
10
  _isHResult: true;
@@ -16,8 +17,18 @@ export type MethodKind = "method" | "propget" | "propput" | "propputref";
16
17
  * the results (COMMETHOD). `self` is the interface declaring the method.
17
18
  */
18
19
  export type MethodMarshal = (fn: (...args: any[]) => any, address: bigint, args: readonly unknown[], self: InterfaceDef<any>) => unknown;
20
+ /**
21
+ * Runs a native call on the COM executor: `native` are the converted
22
+ * arguments (without `this`), `results` the locations of interface results.
23
+ * Resolves with the raw result; rejects with {@link COMError} for HRESULT failures.
24
+ */
25
+ export type NativeRunner = (native: readonly unknown[], results: readonly ResultLocation[]) => Promise<unknown>;
26
+ /** Asynchronous counterpart of {@link MethodMarshal}: converts, awaits `run`, converts the results. */
27
+ export type MethodMarshalAsync = (run: NativeRunner, args: readonly unknown[], self: InterfaceDef<any>) => Promise<unknown>;
19
28
  /** Calls a dispatch member (DISPMETHOD / DISPPROPERTY) through `IDispatch::Invoke`; `put` for property writes. */
20
29
  export type DispatchCall = (pointer: COMPointer, args: readonly unknown[], self: InterfaceDef<any>, put?: boolean) => unknown;
30
+ /** Calls a dispatch method through `IDispatch::Invoke` on the COM executor. */
31
+ export type DispatchCallAsync = (pointer: COMPointer, args: readonly unknown[], self: InterfaceDef<any>) => Promise<unknown>;
21
32
  /**
22
33
  * A vtable method. `F` is the JavaScript signature for STDMETHOD; COMMETHOD
23
34
  * specs carry their parameter specs (`__params`) so that `SELF` can be
@@ -36,12 +47,16 @@ export interface MethodSpec<N extends string = string, F extends (...args: any[]
36
47
  /** `dispid(n)` IDL flag, if any. */
37
48
  readonly dispid: number | null;
38
49
  readonly marshal: MethodMarshal | null;
50
+ /** Asynchronous conversion (COMMETHOD); `null`: raw arguments. */
51
+ readonly marshalAsync?: MethodMarshalAsync | null;
39
52
  /** Number of required JavaScript arguments (COMMETHOD), `null` for STDMETHOD. */
40
53
  readonly requiredArguments: number | null;
41
54
  /** Number of JavaScript input arguments (COMMETHOD), `null` for STDMETHOD. */
42
55
  readonly inputArguments: number | null;
43
56
  /** Dispatch members (DISPMETHOD / DISPPROPERTY): no vtable slot, called through `IDispatch::Invoke`. */
44
57
  readonly dispatch?: DispatchCall | null;
58
+ /** Asynchronous call of a dispatch method. */
59
+ readonly dispatchAsync?: DispatchCallAsync | null;
45
60
  /** DISPPROPERTY without `readonly`: also writable. */
46
61
  readonly writable?: boolean;
47
62
  /** Type-level only. */
@@ -100,20 +115,41 @@ export type PropertiesOf<M extends readonly MethodSpec[], Self = unknown> = {
100
115
  /** Write-only properties. */
101
116
  -readonly [S in M[number] as S extends Setter<S> ? (S["property"] extends keyof AccessorNames<M, Self> ? never : MethodFunction<S, Self> extends (value: any) => any ? S["property"] : never) : never]: Parameters<MethodFunction<S, Self>>[0];
102
117
  };
103
- /** Method and property signatures of a `methods` tuple, with `SELF` resolved to `Self`. */
118
+ /** The same function, returning a promise of its result. */
119
+ export type Asynchronous<F> = F extends (...args: infer A) => infer R ? (...args: A) => Promise<Awaited<R>> : F;
120
+ /** A member as installed on pointers: methods (kind `method`) are asynchronous, accessors synchronous. */
121
+ type MemberOf<S, Self> = S extends {
122
+ readonly kind: "method";
123
+ } ? Asynchronous<MethodFunction<S, Self>> : MethodFunction<S, Self>;
124
+ /**
125
+ * Method and property signatures of a `methods` tuple, with `SELF` resolved
126
+ * to `Self`: methods return promises, properties and accessors are synchronous.
127
+ */
104
128
  export type MethodsOf<M extends readonly MethodSpec[], Self = unknown> = {
129
+ [S in M[number] as S["name"]]: MemberOf<S, Self>;
130
+ } & PropertiesOf<M, Self>;
131
+ /** Like {@link MethodsOf}, with every method synchronous (the `sync()` view). */
132
+ export type SyncMethodsOf<M extends readonly MethodSpec[], Self = unknown> = {
105
133
  [S in M[number] as S["name"]]: MethodFunction<S, Self>;
106
134
  } & PropertiesOf<M, Self>;
107
135
  /** Method signatures of an interface, including the inherited ones. */
108
136
  export type InterfaceMethods<I> = I extends {
109
137
  readonly __methods?: infer T;
110
138
  } ? NonNullable<T> : {};
139
+ /** Synchronous method signatures of an interface, including the inherited ones. */
140
+ export type SyncInterfaceMethods<I> = I extends {
141
+ readonly __sync?: infer T;
142
+ } ? NonNullable<T> : {};
111
143
  /** A typed pointer to interface `I`: {@link COMPointer} plus the interface methods and properties. */
112
144
  export type InterfacePointer<I extends InterfaceDef<any> = InterfaceDef> = COMPointer<I> & Omit<InterfaceMethods<I>, keyof COMPointer>;
145
+ /** A synchronous view of a pointer to interface `I` (see `sync()`). */
146
+ export type SyncPointer<I extends InterfaceDef<any> = InterfaceDef> = COMPointer<I> & Omit<SyncInterfaceMethods<I>, keyof COMPointer>;
147
+ /** The synchronous view type of a pointer type. */
148
+ export type Synchronous<P> = P extends COMPointer<infer I> ? SyncPointer<I> : never;
113
149
  /** Pointer class generated for an interface. */
114
150
  export type PointerClass = new (address: bigint, iface: InterfaceDef<any>) => COMPointer;
115
151
  /** Interface definition returned by {@link COMInterface}. */
116
- export interface InterfaceDef<TMethods extends object = {}> {
152
+ export interface InterfaceDef<TMethods extends object = {}, TSync extends object = TMethods> {
117
153
  readonly name: string;
118
154
  readonly iid: GUID;
119
155
  readonly base: InterfaceDef<any> | null;
@@ -128,11 +164,15 @@ export interface InterfaceDef<TMethods extends object = {}> {
128
164
  readonly dispMethods: readonly MethodSpec[];
129
165
  /** Pointer class: a {@link COMPointer} subclass with the interface methods. */
130
166
  readonly Pointer: PointerClass;
167
+ /** Class of the synchronous views (`sync()`). */
168
+ readonly SyncPointer: PointerClass;
131
169
  /** Type-level only: the method signatures. Never set at runtime. */
132
170
  readonly __methods?: TMethods;
171
+ /** Type-level only: the synchronous method signatures. Never set at runtime. */
172
+ readonly __sync?: TSync;
133
173
  }
134
174
  /** Definition type of `COMInterface({ extends: B, methods: M, dispMethods: D })`; recursive so that `SELF` refers to it. */
135
- export interface ComInterfaceDef<B, M extends readonly MethodSpec[], D extends readonly MethodSpec[] = readonly []> extends InterfaceDef<InterfaceMethods<B> & MethodsOf<M, ComInterfaceDef<B, M, D>> & MethodsOf<D, ComInterfaceDef<B, M, D>>> {
175
+ export interface ComInterfaceDef<B, M extends readonly MethodSpec[], D extends readonly MethodSpec[] = readonly []> extends InterfaceDef<InterfaceMethods<B> & MethodsOf<M, ComInterfaceDef<B, M, D>> & MethodsOf<D, ComInterfaceDef<B, M, D>>, SyncInterfaceMethods<B> & SyncMethodsOf<M, ComInterfaceDef<B, M, D>> & SyncMethodsOf<D, ComInterfaceDef<B, M, D>>> {
136
176
  }
137
177
  export interface InterfaceSpec<M extends readonly MethodSpec[], B extends InterfaceDef<any> | undefined, D extends readonly MethodSpec[] = readonly []> {
138
178
  readonly name: string;
package/dist/interface.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as ctypes from "node-ctypes";
2
2
  import { GUID, toGUID } from "./guid.js";
3
- import { COMPointer, createSlot, invokeSlot } from "./pointer.js";
3
+ import { COMPointer, createSlot, invokeSlot, invokeSlotAsync } from "./pointer.js";
4
4
  /** HRESULT restype marker: such methods raise {@link COMError} on failure. */
5
5
  export const HRESULT = ctypes.HRESULT;
6
6
  /**
@@ -23,6 +23,7 @@ export function STDMETHOD(restype, name, argtypes) {
23
23
  property: name,
24
24
  dispid: null,
25
25
  marshal: null,
26
+ marshalAsync: null,
26
27
  requiredArguments: null,
27
28
  inputArguments: null,
28
29
  });
@@ -72,16 +73,20 @@ function installProperties(prototype, methods) {
72
73
  });
73
74
  }
74
75
  }
75
- /** Install dispatch members: methods calling `IDispatch::Invoke`, plus the property accessors. */
76
- function installDispatchMembers(prototype, members, owner) {
76
+ /**
77
+ * Install dispatch members: methods calling `IDispatch::Invoke` (on the COM
78
+ * executor when `asynchronous`), plus the synchronous property accessors.
79
+ */
80
+ function installDispatchMembers(prototype, members, owner, asynchronous) {
77
81
  const accessors = [];
78
82
  for (const member of members) {
79
83
  const call = member.dispatch;
84
+ const callAsync = asynchronous && member.kind === "method" ? member.dispatchAsync : null;
80
85
  if (!(member.name in COMPointer.prototype)) {
81
86
  Object.defineProperty(prototype, member.name, {
82
87
  value: {
83
88
  [member.name](...args) {
84
- return call(this, args, owner.definition);
89
+ return callAsync ? callAsync(this, args, owner.definition) : call(this, args, owner.definition);
85
90
  },
86
91
  }[member.name],
87
92
  writable: true,
@@ -154,6 +159,10 @@ export function COMInterface(spec) {
154
159
  const Pointer = class extends Parent {
155
160
  };
156
161
  Object.defineProperty(Pointer, "name", { value: `POINTER(${spec.name})` });
162
+ const SyncParent = base?.SyncPointer ?? COMPointer;
163
+ const SyncPointer = class extends SyncParent {
164
+ };
165
+ Object.defineProperty(SyncPointer, "name", { value: `SYNC(${spec.name})` });
157
166
  const first = slots.length - methods.length;
158
167
  methods.forEach((method, index) => {
159
168
  // COMPointer members (QueryInterface, AddRef, Release, ...) take precedence,
@@ -161,17 +170,28 @@ export function COMInterface(spec) {
161
170
  if (method.name in COMPointer.prototype)
162
171
  return;
163
172
  const slot = first + index;
164
- const fn = {
173
+ const synchronous = {
165
174
  [method.name](...args) {
166
175
  return invokeSlot(this, slot, args);
167
176
  },
168
177
  }[method.name];
169
- Object.defineProperty(Pointer.prototype, method.name, { value: fn, writable: true, configurable: true });
178
+ // Methods run on the COM executor; accessors stay synchronous.
179
+ const asynchronous = method.kind === "method"
180
+ ? {
181
+ [method.name](...args) {
182
+ return invokeSlotAsync(this, slot, args);
183
+ },
184
+ }[method.name]
185
+ : synchronous;
186
+ Object.defineProperty(Pointer.prototype, method.name, { value: asynchronous, writable: true, configurable: true });
187
+ Object.defineProperty(SyncPointer.prototype, method.name, { value: synchronous, writable: true, configurable: true });
170
188
  });
171
189
  installProperties(Pointer.prototype, methods);
172
- installDispatchMembers(Pointer.prototype, dispOwn, owner);
190
+ installProperties(SyncPointer.prototype, methods);
191
+ installDispatchMembers(Pointer.prototype, dispOwn, owner, true);
192
+ installDispatchMembers(SyncPointer.prototype, dispOwn, owner, false);
173
193
  const dispMethods = Object.freeze([...(base?.dispMethods ?? []), ...dispOwn]);
174
- const definition = Object.freeze({ name: spec.name, iid, base, methods, allMethods, methodIndex, slots, dispMethods, Pointer });
194
+ const definition = Object.freeze({ name: spec.name, iid, base, methods, allMethods, methodIndex, slots, dispMethods, Pointer, SyncPointer });
175
195
  owner.definition = definition;
176
196
  if (spec.register !== false)
177
197
  registry.set(iid.toString(), definition);
@@ -54,7 +54,7 @@ import * as ctypes from "node-ctypes";
54
54
  import { borrowReference } from "../automation/variant.js";
55
55
  import { GUID, toGUID } from "../guid.js";
56
56
  import { COMInterface, HRESULT, STDMETHOD } from "../interface.js";
57
- import { COMPointer } from "../pointer.js";
57
+ import { COMPointer, sync } from "../pointer.js";
58
58
  import { IUnknown } from "./unknown.js";
59
59
  const { POINTER, c_void_p } = ctypes;
60
60
  /** Services of an object by service ID. Python equivalent: `comtypes.IServiceProvider`. */
@@ -77,7 +77,7 @@ export function queryService(object, service, iface) {
77
77
  const pointer = __addDisposableResource(env_1, COMPointer.fromAddress(borrowed.address, borrowed.interface, { addRef: true }), false);
78
78
  const provider = __addDisposableResource(env_1, pointer.QueryInterface(IServiceProvider), false);
79
79
  const out = new ctypes.c_void_p();
80
- provider.QueryService(toGUID(service), iface.iid, ctypes.byref(out));
80
+ sync(provider).QueryService(toGUID(service), iface.iid, ctypes.byref(out));
81
81
  return COMPointer.fromAddress(out.value, iface);
82
82
  }
83
83
  catch (e_1) {
@@ -1,5 +1,7 @@
1
1
  export { ole32, oleaut32, allocBSTR, readBSTR, takeBSTR, takeCoTaskMemString, readMemory, writeMemory, isWindows, POINTER_SIZE } from "./native.ts";
2
2
  export type { Ole32, OleAut32 } from "./native.ts";
3
3
  export { vtableEntry, functionCache, rawQueryInterface, rawAddRef, rawRelease } from "./vtable.ts";
4
+ export { executorCall, executorGeneration } from "../executor/executor.ts";
5
+ export type { CallOptions, NativeCall, NativeResult } from "../executor/executor.ts";
4
6
  export { COSERVERINFO, MULTI_QI } from "./types.ts";
5
7
  export { HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, readString, subkeys, writeString, deleteTree } from "./registry.ts";
@@ -1,4 +1,5 @@
1
1
  export { ole32, oleaut32, allocBSTR, readBSTR, takeBSTR, takeCoTaskMemString, readMemory, writeMemory, isWindows, POINTER_SIZE } from "./native.js";
2
2
  export { vtableEntry, functionCache, rawQueryInterface, rawAddRef, rawRelease } from "./vtable.js";
3
+ export { executorCall, executorGeneration } from "../executor/executor.js";
3
4
  export { COSERVERINFO, MULTI_QI } from "./types.js";
4
5
  export { HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, readString, subkeys, writeString, deleteTree } from "./registry.js";
@@ -70,6 +70,12 @@ export declare function allocBSTR(text: string): bigint;
70
70
  export declare function readBSTR(bstr: bigint | null): string | null;
71
71
  /** Read a BSTR and free it. */
72
72
  export declare function takeBSTR(bstr: bigint | null): string | null;
73
+ /**
74
+ * A copy of the structure at `address`, for data that is only read (type
75
+ * descriptors): cheaper than a view over native memory (`from_address`).
76
+ * Pointers inside still refer to native memory.
77
+ */
78
+ export declare function copyStruct<T>(type: new (...args: any[]) => T, address: bigint): T;
73
79
  /** Copy `size` bytes of native memory at `address`. */
74
80
  export declare function readMemory(address: bigint, size: number): Buffer;
75
81
  /** Copy `data` to native memory at `address`. */
@@ -92,7 +92,9 @@ export function allocBSTR(text) {
92
92
  export function readBSTR(bstr) {
93
93
  if (!bstr)
94
94
  return null;
95
- return readMemory(bstr, ctypes.readValue(bstr - 4n, c_uint32) & ~1).toString("utf16le");
95
+ // The length prefix counts bytes; embedded NULs are part of the string.
96
+ const length = ctypes.readValue(bstr - 4n, c_uint32) >>> 1;
97
+ return length ? (ctypes.wstring_at(bstr, length) ?? "") : "";
96
98
  }
97
99
  /** Read a BSTR and free it. */
98
100
  export function takeBSTR(bstr) {
@@ -105,6 +107,16 @@ export function takeBSTR(bstr) {
105
107
  oleaut32().SysFreeString(bstr);
106
108
  }
107
109
  }
110
+ /**
111
+ * A copy of the structure at `address`, for data that is only read (type
112
+ * descriptors): cheaper than a view over native memory (`from_address`).
113
+ * Pointers inside still refer to native memory.
114
+ */
115
+ export function copyStruct(type, address) {
116
+ const bytes = Buffer.allocUnsafe(ctypes.sizeof(type));
117
+ ctypes.memmove(bytes, address, bytes.length);
118
+ return type.from_buffer(bytes);
119
+ }
108
120
  /** Copy `size` bytes of native memory at `address`. */
109
121
  export function readMemory(address, size) {
110
122
  const buffer = Buffer.alloc(size);