@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
package/dist/commethod.js CHANGED
@@ -119,7 +119,7 @@ function safeArrayCodec(vt) {
119
119
  },
120
120
  output(initial, hasInitial) {
121
121
  const start = hasInitial && initial !== null && initial !== undefined ? create(initial) : null;
122
- return pointerHolder(byReference, (psa) => {
122
+ const holder = pointerHolder(byReference, (psa) => {
123
123
  try {
124
124
  return readSafeArray(psa ?? 0n, vt);
125
125
  }
@@ -127,6 +127,8 @@ function safeArrayCodec(vt) {
127
127
  destroySafeArray(psa);
128
128
  }
129
129
  }, destroySafeArray, start);
130
+ // Arrays of objects are handed over to a single-threaded home element by element.
131
+ return { ...holder, result: { kind: "safearray" } };
130
132
  },
131
133
  };
132
134
  }
@@ -193,7 +195,7 @@ function interfaceCodec(type) {
193
195
  const reference = hasInitial ? interfaceReference(initial, iface) : null;
194
196
  if (reference && !reference.owned)
195
197
  rawAddRef(reference.address);
196
- return pointerHolder(byReference, (address) => (address ? COMPointer.fromAddress(address, iface) : null), rawRelease, reference?.address ?? null);
198
+ return { ...pointerHolder(byReference, (address) => (address ? COMPointer.fromAddress(address, iface) : null), rawRelease, reference?.address ?? null), result: { kind: "pointer", iid: iface.iid } };
197
199
  },
198
200
  };
199
201
  }
@@ -211,6 +213,7 @@ const variantCodec = {
211
213
  let consumed = false;
212
214
  return {
213
215
  arg: variant._buffer,
216
+ result: { kind: "variant" },
214
217
  read() {
215
218
  consumed = true;
216
219
  try {
@@ -361,6 +364,12 @@ function outputCodec(type) {
361
364
  }
362
365
  // ── COMMETHOD ─────────────────────────────────────────────────────────
363
366
  const PARAM_FLAGS = new Set(["in", "out", "retval", "lcid", "optional"]);
367
+ function release(prepared) {
368
+ for (const holder of prepared.holders)
369
+ holder.free();
370
+ for (const cleanup of prepared.cleanup.reverse())
371
+ cleanup();
372
+ }
364
373
  /**
365
374
  * Describe a vtable method with IDL flags. Python equivalent: `comtypes.COMMETHOD`.
366
375
  *
@@ -423,7 +432,8 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
423
432
  const inputs = infos.filter((info) => info.input);
424
433
  const required = inputs.filter((info) => !info.optional).length;
425
434
  const hasOutputs = infos.some((info) => info.output);
426
- const marshal = (fn, address, args, self) => {
435
+ // Converts the arguments; on failure, releases what was already converted.
436
+ const prepare = (args, self) => {
427
437
  let positional = args;
428
438
  let byName = null;
429
439
  const last = args[args.length - 1];
@@ -436,9 +446,7 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
436
446
  }
437
447
  if (positional.length > inputs.length)
438
448
  throw new TypeError(`${name}: expected at most ${inputs.length} arguments, got ${positional.length}`);
439
- const native = [];
440
- const holders = [];
441
- const cleanup = [];
449
+ const prepared = { native: [], holders: [], cleanup: [] };
442
450
  try {
443
451
  let position = 0;
444
452
  infos.forEach((info, index) => {
@@ -461,25 +469,65 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
461
469
  }
462
470
  if (info.output) {
463
471
  const holder = codec.output(value, info.input && supplied, self);
464
- holders.push(holder);
465
- native.push(holder.arg);
472
+ prepared.holders.push(holder);
473
+ prepared.native.push(holder.arg);
466
474
  }
467
475
  else {
468
- native.push(codec.input(value, cleanup, self));
476
+ prepared.native.push(codec.input(value, prepared.cleanup, self));
469
477
  }
470
478
  });
471
- const result = fn(address, ...native);
472
- if (!hasOutputs)
473
- return result;
474
- const values = holders.map((holder) => wrapOutput(holder.read()));
475
- return values.length === 1 ? values[0] : values;
479
+ return prepared;
480
+ }
481
+ catch (error) {
482
+ release(prepared);
483
+ throw error;
484
+ }
485
+ };
486
+ const finish = (prepared, result) => {
487
+ if (!hasOutputs)
488
+ return result;
489
+ const values = prepared.holders.map((holder) => wrapOutput(holder.read()));
490
+ return values.length === 1 ? values[0] : values;
491
+ };
492
+ const marshal = (fn, address, args, self) => {
493
+ const prepared = prepare(args, self);
494
+ try {
495
+ return finish(prepared, fn(address, ...prepared.native));
476
496
  }
477
497
  finally {
478
- for (const holder of holders)
479
- holder.free();
480
- for (const release of cleanup.reverse())
481
- release();
498
+ release(prepared);
499
+ }
500
+ };
501
+ // The converted arguments stay alive (and owned here) until the call completes.
502
+ // Promise steps instead of an async function: this runs for every method call.
503
+ const marshalAsync = (run, args, self) => {
504
+ let prepared;
505
+ let pending;
506
+ try {
507
+ prepared = prepare(args, self);
508
+ }
509
+ catch (error) {
510
+ return Promise.reject(error);
511
+ }
512
+ try {
513
+ const results = prepared.holders.flatMap((holder) => (holder.result ? [{ location: ctypes.addressof(holder.arg), ...holder.result }] : []));
514
+ pending = run(prepared.native, results);
515
+ }
516
+ catch (error) {
517
+ release(prepared);
518
+ return Promise.reject(error);
482
519
  }
520
+ return pending.then((value) => {
521
+ try {
522
+ return finish(prepared, value);
523
+ }
524
+ finally {
525
+ release(prepared);
526
+ }
527
+ }, (error) => {
528
+ release(prepared);
529
+ throw error;
530
+ });
483
531
  };
484
532
  const methodName = kind === "propget" ? `_get_${name}` : kind === "propput" ? `_set_${name}` : kind === "propputref" ? `_setref_${name}` : name;
485
533
  return Object.freeze({
@@ -491,6 +539,7 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
491
539
  property: name,
492
540
  dispid: dispidFlag?.dispid ?? null,
493
541
  marshal,
542
+ marshalAsync,
494
543
  requiredArguments: required,
495
544
  inputArguments: inputs.length,
496
545
  params: Object.freeze(infos),
@@ -1,11 +1,12 @@
1
1
  import { DISPATCH_METHOD, DISPATCH_PROPERTYGET, DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, VT_CY, VT_TYPEMASK } from "./automation/constants.js";
2
- import { getIDsOfNames, invoke } from "./automation/dispatch.js";
2
+ import { getIDsOfNames, invoke, invokeAsync } from "./automation/dispatch.js";
3
3
  import { NamedArguments } from "./automation/named.js";
4
4
  import { ByRef, Typed, borrowReference, safeArray, typed } from "./automation/variant.js";
5
5
  import { classifyParamType, resolveParamInterface, wrapOutput } from "./commethod.js";
6
6
  import { COMError } from "./errors.js";
7
7
  import { DISP_E_MEMBERNOTFOUND } from "./hresult.js";
8
8
  import { derivesFrom } from "./interface.js";
9
+ import { linkOperation } from "./executor/operations.js";
9
10
  import { COMPointer } from "./pointer.js";
10
11
  const PARAM_FLAGS = new Set(["in", "out", "retval", "lcid", "optional"]);
11
12
  function parameters(member, params) {
@@ -72,7 +73,8 @@ function makeCall(member, dispid, kind, infos, valueType) {
72
73
  const kinds = infos.map((info) => classifyParamType(info.type));
73
74
  const resultKind = valueType === null ? null : classifyParamType(valueType);
74
75
  const inputs = infos.filter((info) => info.input);
75
- return (pointer, args, self, put) => {
76
+ // Converts the arguments: positional values with declared types and defaults, named arguments.
77
+ const convert = (pointer, args, put) => {
76
78
  let positional = [...args];
77
79
  let named;
78
80
  const last = positional[positional.length - 1];
@@ -100,6 +102,10 @@ function makeCall(member, dispid, kind, infos, valueType) {
100
102
  else if (!info.optional && !named)
101
103
  throw new TypeError(`${member}: missing argument ${info.name}`);
102
104
  }
105
+ return { converted, named, writing };
106
+ };
107
+ const call = (pointer, args, self, put) => {
108
+ const { converted, named, writing } = convert(pointer, args, put);
103
109
  const dispatch = pointer;
104
110
  if (writing) {
105
111
  const value = converted[converted.length - 1];
@@ -118,6 +124,19 @@ function makeCall(member, dispid, kind, infos, valueType) {
118
124
  const value = invoke(dispatch, dispid, flags, converted, { named, name: member });
119
125
  return valueType === null ? undefined : wrapOutput(result(resultKind, value, self));
120
126
  };
127
+ const callAsync = (pointer, args, self) => {
128
+ let prepared;
129
+ try {
130
+ prepared = convert(pointer, args, false);
131
+ }
132
+ catch (error) {
133
+ return Promise.reject(error);
134
+ }
135
+ const flags = kind === "propget" ? DISPATCH_PROPERTYGET : DISPATCH_METHOD;
136
+ const pending = invokeAsync(pointer, dispid, flags, prepared.converted, { named: prepared.named, name: member });
137
+ return linkOperation(pending.then((value) => (valueType === null ? undefined : wrapOutput(result(resultKind, value, self)))), pending);
138
+ };
139
+ return { call, callAsync };
121
140
  }
122
141
  /**
123
142
  * A method of a dispinterface, called through `IDispatch::Invoke`.
@@ -143,6 +162,7 @@ export function DISPMETHOD(idlflags, restype, name, ...params) {
143
162
  const dispid = dispidOf(name, idlflags);
144
163
  const infos = parameters(name, params);
145
164
  const inputs = infos.filter((info) => info.input);
165
+ const calls = makeCall(name, dispid, kind, infos, restype);
146
166
  return Object.freeze({
147
167
  name: kind === "propget" ? `_get_${name}` : kind === "propput" ? `_set_${name}` : kind === "propputref" ? `_setref_${name}` : name,
148
168
  restype: null,
@@ -154,7 +174,8 @@ export function DISPMETHOD(idlflags, restype, name, ...params) {
154
174
  marshal: null,
155
175
  requiredArguments: inputs.filter((info) => !info.optional).length,
156
176
  inputArguments: inputs.length,
157
- dispatch: makeCall(name, dispid, kind, infos, restype),
177
+ dispatch: calls.call,
178
+ dispatchAsync: kind === "method" ? calls.callAsync : null,
158
179
  writable: false,
159
180
  params: Object.freeze(infos),
160
181
  valueType: restype,
@@ -174,8 +195,8 @@ export function DISPPROPERTY(idlflags, type, name) {
174
195
  throw new TypeError("DISPPROPERTY requires a name");
175
196
  const dispid = dispidOf(name, idlflags);
176
197
  const writable = !idlflags.includes("readonly");
177
- const get = makeCall(name, dispid, "propget", [], type);
178
- const set = makeCall(name, dispid, "method", [], type);
198
+ const get = makeCall(name, dispid, "propget", [], type).call;
199
+ const set = makeCall(name, dispid, "method", [], type).call;
179
200
  return Object.freeze({
180
201
  name: `_get_${name}`,
181
202
  restype: null,
@@ -0,0 +1,32 @@
1
+ import { GUID } from "../guid.ts";
2
+ /**
3
+ * Apartment of the home thread: `mta` (explicit or implicit: shared with the
4
+ * executor), `sta` (single-threaded, also NA/main STA), or `none` when COM is
5
+ * not initialized there (objects are then called on the home thread).
6
+ */
7
+ export declare function homeApartment(): "mta" | "sta" | "none";
8
+ /** A standard proxy (to another apartment or process): answered locally by the proxy manager. */
9
+ export declare function isProxy(address: bigint): boolean;
10
+ /** Callable from any apartment: `IAgileObject`, or marshaled by the free-threaded marshaler. */
11
+ export declare function isAgile(address: bigint): boolean;
12
+ /** Release a reference owned by the executor thread, after the calls already queued. */
13
+ export declare function releaseOnExecutor(address: bigint, generation: number): void;
14
+ /**
15
+ * A reference to the home pointer `address` usable on the executor (owned by
16
+ * the executor), through the Global Interface Table; `null` when the
17
+ * interface cannot be marshaled (no proxy/stub).
18
+ */
19
+ export declare function referenceForExecutor(address: bigint, iid: GUID): Promise<bigint | null>;
20
+ /** Memory receiving an interface result: an `out` interface pointer, a VARIANT or a `SAFEARRAY*`. */
21
+ export interface ResultLocation {
22
+ readonly location: bigint;
23
+ readonly kind: "pointer" | "variant" | "safearray";
24
+ /** Interface of a `pointer` result. */
25
+ readonly iid?: GUID;
26
+ }
27
+ /**
28
+ * Hand the interface results of a call made on the executor over to a
29
+ * single-threaded home apartment: each location then holds a reference owned
30
+ * by the home thread (the same one for agile objects).
31
+ */
32
+ export declare function handOver(results: readonly ResultLocation[]): Promise<void>;
@@ -0,0 +1,226 @@
1
+ // Apartments of the JavaScript ("home") thread and of the COM executor.
2
+ // Pointers belong to the apartment that obtained them: the executor (in the
3
+ // multithreaded apartment) can use a home pointer directly only when the home
4
+ // thread is in the MTA too or the object is agile; otherwise it gets its own
5
+ // reference through the Global Interface Table. Interface results of calls
6
+ // made on the executor are handed back to a single-threaded home the same way.
7
+ import * as ctypes from "node-ctypes";
8
+ import { VT_ARRAY, VT_BYREF, VT_DISPATCH, VT_UNKNOWN, VT_VARIANT } from "../automation/constants.js";
9
+ import { APTTYPE_MTA, CLSCTX_INPROC_SERVER } from "../constants.js";
10
+ import { COMError } from "../errors.js";
11
+ import { GUID } from "../guid.js";
12
+ import { CO_E_NOTINITIALIZED } from "../hresult.js";
13
+ import { ole32, oleaut32 } from "../low-level/native.js";
14
+ import { functionCache, rawQueryInterface, rawRelease, vtableEntry } from "../low-level/vtable.js";
15
+ import { apartmentGeneration } from "../tracking.js";
16
+ import { executorAlive, executorGeneration, executorTarget } from "./executor.js";
17
+ const { c_int32, c_uint16, c_uint32, c_void_p } = ctypes;
18
+ const CLSID_StdGlobalInterfaceTable = new GUID("{00000323-0000-0000-C000-000000000046}");
19
+ const IID_IGlobalInterfaceTable = new GUID("{00000146-0000-0000-C000-000000000046}");
20
+ const IID_IAgileObject = new GUID("{94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90}");
21
+ const IID_IMarshal = new GUID("{00000003-0000-0000-C000-000000000046}");
22
+ const IID_IClientSecurity = new GUID("{0000013D-0000-0000-C000-000000000046}");
23
+ const IID_IDispatch = new GUID("{00020400-0000-0000-C000-000000000046}");
24
+ const IID_IUnknown = new GUID("{00000000-0000-0000-C000-000000000046}");
25
+ const CLSID_InProcFreeMarshaler = new GUID("{0000033A-0000-0000-C000-000000000046}");
26
+ const MSHCTX_INPROC = 3;
27
+ const MSHLFLAGS_NORMAL = 0;
28
+ const RegisterAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_void_p));
29
+ const RevokeAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_uint32));
30
+ const GetAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_uint32, c_void_p, c_void_p));
31
+ const QueryInterfaceAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p));
32
+ const ReleaseAt = functionCache(() => ctypes.WINFUNCTYPE(c_uint32, c_void_p));
33
+ const GetUnmarshalClassAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_uint32, c_void_p, c_uint32, c_void_p));
34
+ /**
35
+ * Apartment of the home thread: `mta` (explicit or implicit: shared with the
36
+ * executor), `sta` (single-threaded, also NA/main STA), or `none` when COM is
37
+ * not initialized there (objects are then called on the home thread).
38
+ */
39
+ export function homeApartment() {
40
+ const type = new c_int32();
41
+ const qualifier = new c_int32();
42
+ const hr = ole32().CoGetApartmentType(ctypes.byref(type), ctypes.byref(qualifier));
43
+ if (hr === CO_E_NOTINITIALIZED || hr < 0)
44
+ return "none";
45
+ return type.value === APTTYPE_MTA ? "mta" : "sta";
46
+ }
47
+ function supports(address, iid) {
48
+ const [hr, pointer] = rawQueryInterface(address, iid);
49
+ return hr >= 0 && pointer ? pointer : null;
50
+ }
51
+ /** A standard proxy (to another apartment or process): answered locally by the proxy manager. */
52
+ export function isProxy(address) {
53
+ const security = supports(address, IID_IClientSecurity);
54
+ if (security)
55
+ rawRelease(security);
56
+ return security !== null;
57
+ }
58
+ /** Callable from any apartment: `IAgileObject`, or marshaled by the free-threaded marshaler. */
59
+ export function isAgile(address) {
60
+ const agile = supports(address, IID_IAgileObject);
61
+ if (agile) {
62
+ rawRelease(agile);
63
+ return true;
64
+ }
65
+ const marshal = supports(address, IID_IMarshal);
66
+ if (!marshal)
67
+ return false;
68
+ try {
69
+ const clsid = new GUID();
70
+ const hr = GetUnmarshalClassAt(vtableEntry(marshal, 3))(marshal, IID_IUnknown._buffer, address, MSHCTX_INPROC, null, MSHLFLAGS_NORMAL, clsid._buffer);
71
+ return hr >= 0 && clsid.equals(CLSID_InProcFreeMarshaler);
72
+ }
73
+ finally {
74
+ rawRelease(marshal);
75
+ }
76
+ }
77
+ // The Global Interface Table of the home thread, per apartment generation.
78
+ let homeTable = null;
79
+ function homeGlobalTable() {
80
+ const generation = apartmentGeneration();
81
+ if (homeTable?.generation === generation)
82
+ return homeTable.address;
83
+ const out = new c_void_p();
84
+ const hr = ole32().CoCreateInstance(CLSID_StdGlobalInterfaceTable._buffer, null, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable._buffer, ctypes.byref(out));
85
+ if (hr < 0 || !out.value)
86
+ throw new COMError(hr, { method: "CoCreateInstance(StdGlobalInterfaceTable)" });
87
+ homeTable = { address: out.value, generation };
88
+ return out.value;
89
+ }
90
+ // The executor's own table, per executor generation (created on the executor).
91
+ let executorTable = null;
92
+ function executorGlobalTable() {
93
+ const target = executorTarget();
94
+ const generation = executorGeneration();
95
+ if (executorTable?.generation === generation)
96
+ return executorTable.address;
97
+ const out = new c_void_p();
98
+ const address = ole32()
99
+ .CoCreateInstance.callOn(target, CLSID_StdGlobalInterfaceTable._buffer, null, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable._buffer, ctypes.byref(out))
100
+ .then((hr) => {
101
+ if (hr < 0 || !out.value)
102
+ throw new COMError(hr, { method: "CoCreateInstance(StdGlobalInterfaceTable)" });
103
+ return out.value;
104
+ });
105
+ executorTable = { address, generation };
106
+ return address;
107
+ }
108
+ /** Release a reference owned by the executor thread, after the calls already queued. */
109
+ export function releaseOnExecutor(address, generation) {
110
+ // An executor that has stopped took its references with its apartment.
111
+ if (!executorAlive(generation))
112
+ return;
113
+ ReleaseAt(vtableEntry(address, 2))
114
+ .callOn(executorTarget(), address)
115
+ .catch(() => undefined);
116
+ }
117
+ /**
118
+ * A reference to the home pointer `address` usable on the executor (owned by
119
+ * the executor), through the Global Interface Table; `null` when the
120
+ * interface cannot be marshaled (no proxy/stub).
121
+ */
122
+ export async function referenceForExecutor(address, iid) {
123
+ const table = homeGlobalTable();
124
+ const cookie = new c_uint32();
125
+ if (RegisterAt(vtableEntry(table, 3))(table, address, iid._buffer, ctypes.byref(cookie)) < 0)
126
+ return null;
127
+ try {
128
+ const executorTableAddress = await executorGlobalTable();
129
+ const out = new c_void_p();
130
+ const hr = await GetAt(vtableEntry(executorTableAddress, 5)).callOn(executorTarget(), executorTableAddress, cookie.value, iid._buffer, ctypes.byref(out));
131
+ return hr >= 0 && out.value ? out.value : null;
132
+ }
133
+ finally {
134
+ RevokeAt(vtableEntry(table, 4))(table, cookie.value);
135
+ }
136
+ }
137
+ const VARIANT_POINTER_OFFSET = 8;
138
+ /** Hand the interface pointer at `location + offset` over from the executor to the home apartment, in place. */
139
+ async function handOverPointer(location, offset, interfaceId) {
140
+ const address = ctypes.readValue(location, c_void_p, offset);
141
+ if (!address)
142
+ return;
143
+ const target = executorTarget();
144
+ // Agile objects are valid in both apartments: the reference stays as it is.
145
+ const agile = new c_void_p();
146
+ if ((await QueryInterfaceAt(vtableEntry(address, 0)).callOn(target, address, IID_IAgileObject._buffer, ctypes.byref(agile))) >= 0 && agile.value) {
147
+ void ReleaseAt(vtableEntry(agile.value, 2))
148
+ .callOn(target, agile.value)
149
+ .catch(() => undefined);
150
+ return;
151
+ }
152
+ const executorTableAddress = await executorGlobalTable();
153
+ const cookie = new c_uint32();
154
+ const registered = await RegisterAt(vtableEntry(executorTableAddress, 3)).callOn(target, executorTableAddress, address, interfaceId._buffer, ctypes.byref(cookie));
155
+ // The executor's reference is no longer needed: the table holds its own.
156
+ void ReleaseAt(vtableEntry(address, 2))
157
+ .callOn(target, address)
158
+ .catch(() => undefined);
159
+ if (registered < 0) {
160
+ ctypes.writeValue(location, c_void_p, null, offset);
161
+ throw new COMError(registered, { method: "IGlobalInterfaceTable::RegisterInterfaceInGlobal" });
162
+ }
163
+ const table = homeGlobalTable();
164
+ const out = new c_void_p();
165
+ const hr = GetAt(vtableEntry(table, 5))(table, cookie.value, interfaceId._buffer, ctypes.byref(out));
166
+ RevokeAt(vtableEntry(table, 4))(table, cookie.value);
167
+ ctypes.writeValue(location, c_void_p, hr >= 0 ? out.value : null, offset);
168
+ if (hr < 0)
169
+ throw new COMError(hr, { method: "IGlobalInterfaceTable::GetInterfaceFromGlobal" });
170
+ }
171
+ /** Hand over the objects of a SAFEARRAY (of interfaces or VARIANTs), element by element. */
172
+ async function handOverArray(psa) {
173
+ if (!psa)
174
+ return;
175
+ const api = oleaut32();
176
+ const type = new c_uint16();
177
+ if (api.SafeArrayGetVartype(psa, ctypes.byref(type)) < 0)
178
+ return;
179
+ const elements = type.value === VT_DISPATCH ? { kind: "pointer", iid: IID_IDispatch } : type.value === VT_UNKNOWN ? { kind: "pointer", iid: IID_IUnknown } : type.value === VT_VARIANT ? { kind: "variant" } : null;
180
+ if (!elements)
181
+ return;
182
+ let count = 1;
183
+ const bound = new c_int32();
184
+ for (let dimension = 1; dimension <= api.SafeArrayGetDim(psa); dimension++) {
185
+ api.SafeArrayGetLBound(psa, dimension, ctypes.byref(bound));
186
+ const lower = bound.value;
187
+ api.SafeArrayGetUBound(psa, dimension, ctypes.byref(bound));
188
+ count *= bound.value - lower + 1;
189
+ }
190
+ const size = api.SafeArrayGetElemsize(psa);
191
+ const data = new c_void_p();
192
+ if (count <= 0 || api.SafeArrayAccessData(psa, ctypes.byref(data)) < 0 || !data.value)
193
+ return;
194
+ try {
195
+ const base = data.value;
196
+ await handOver(Array.from({ length: count }, (_, index) => ({ location: base + BigInt(index * size), ...elements })));
197
+ }
198
+ finally {
199
+ api.SafeArrayUnaccessData(psa);
200
+ }
201
+ }
202
+ /** Hand one interface result over from the executor to the home apartment, in place. */
203
+ async function handOverOne({ location, kind, iid }) {
204
+ if (kind === "pointer")
205
+ return handOverPointer(location, 0, iid ?? IID_IUnknown);
206
+ if (kind === "safearray")
207
+ return handOverArray(ctypes.readValue(location, c_void_p));
208
+ const vt = ctypes.readValue(location, c_uint16);
209
+ if (vt & VT_BYREF)
210
+ return;
211
+ if (vt & VT_ARRAY)
212
+ return handOverArray(ctypes.readValue(location, c_void_p, VARIANT_POINTER_OFFSET));
213
+ if (vt === VT_DISPATCH || vt === VT_UNKNOWN)
214
+ return handOverPointer(location, VARIANT_POINTER_OFFSET, vt === VT_DISPATCH ? IID_IDispatch : IID_IUnknown);
215
+ }
216
+ /**
217
+ * Hand the interface results of a call made on the executor over to a
218
+ * single-threaded home apartment: each location then holds a reference owned
219
+ * by the home thread (the same one for agile objects).
220
+ */
221
+ export async function handOver(results) {
222
+ const outcomes = await Promise.allSettled(results.map((result) => handOverOne(result)));
223
+ const failure = outcomes.find((outcome) => outcome.status === "rejected");
224
+ if (failure)
225
+ throw failure.reason;
226
+ }
@@ -0,0 +1,10 @@
1
+ export declare function markLocalClass(clsid: {
2
+ toString(): string;
3
+ }): void;
4
+ export declare function unmarkLocalClass(clsid: {
5
+ toString(): string;
6
+ }): void;
7
+ /** Whether this thread registered a class object for `clsid`. */
8
+ export declare function isLocalClass(clsid: {
9
+ toString(): string;
10
+ }): boolean;
@@ -0,0 +1,18 @@
1
+ // Classes whose class objects this thread registered (`registerClassObject`):
2
+ // their objects are implemented in JavaScript and are created on this thread.
3
+ const classes = new Map();
4
+ const key = (clsid) => clsid.toString().toUpperCase();
5
+ export function markLocalClass(clsid) {
6
+ classes.set(key(clsid), (classes.get(key(clsid)) ?? 0) + 1);
7
+ }
8
+ export function unmarkLocalClass(clsid) {
9
+ const count = (classes.get(key(clsid)) ?? 0) - 1;
10
+ if (count > 0)
11
+ classes.set(key(clsid), count);
12
+ else
13
+ classes.delete(key(clsid));
14
+ }
15
+ /** Whether this thread registered a class object for `clsid`. */
16
+ export function isLocalClass(clsid) {
17
+ return classes.has(key(clsid));
18
+ }
@@ -0,0 +1,76 @@
1
+ import * as ctypes from "node-ctypes";
2
+ import type { COMErrorDetails } from "../errors.ts";
3
+ import type { GUIDLike } from "../guid.ts";
4
+ import type { Operation } from "./operations.ts";
5
+ /** Counters of the COM executor (`stats()`). */
6
+ export interface ExecutorStats {
7
+ /** Whether the executor thread is running. */
8
+ readonly running: boolean;
9
+ /** Operations queued or running. */
10
+ readonly pending: number;
11
+ /** Operations settled by the current executor. */
12
+ readonly completed: number;
13
+ /** Incremented each time a new executor starts: references owned by an earlier one are gone. */
14
+ readonly generation: number;
15
+ }
16
+ export interface NativeCall {
17
+ /** Function address (e.g. a vtable entry). */
18
+ readonly fn: bigint;
19
+ readonly restype: ctypes.FFIType | null;
20
+ /** Native argument types; keep the same array for the same signature (bindings are cached by it). */
21
+ readonly argtypes: readonly ctypes.FFIType[];
22
+ readonly args: readonly unknown[];
23
+ /** On an HRESULT failure, read IErrorInfo for `object` and interface `iid` (when it supports error info). */
24
+ readonly errorInfo?: {
25
+ readonly object: bigint;
26
+ readonly iid: GUIDLike;
27
+ };
28
+ }
29
+ export interface NativeResult {
30
+ readonly value: unknown;
31
+ /** IErrorInfo details read on the executor thread, for a failed HRESULT. */
32
+ readonly details: COMErrorDetails | null;
33
+ }
34
+ export interface CallOptions {
35
+ /** Cancels the call while it is still queued: the promise rejects with `signal.reason`. */
36
+ readonly signal?: AbortSignal;
37
+ /** Records the call in this operation, which `run()` can cancel (used by node-comtypes' own calls). */
38
+ readonly operation?: Operation;
39
+ }
40
+ /** The running executor (started on demand), for code that queues its own calls. */
41
+ export declare function executorTarget(): ctypes.Executor;
42
+ /** Counters of the COM executor. Python equivalent: node-python's `python.stats()`. */
43
+ export declare function stats(): ExecutorStats;
44
+ /** Whether references owned by executor `generation` are still alive (its executor is running). */
45
+ export declare function executorAlive(generation: number): boolean;
46
+ /** Generation of the current executor (0 before the first one starts). */
47
+ export declare function executorGeneration(): number;
48
+ /**
49
+ * Drain the operations already accepted by the COM executor, leave its
50
+ * apartment and stop its thread; resolves once their promises have settled. Called automatically on a normal
51
+ * `beforeExit`. A later asynchronous operation starts a new executor.
52
+ */
53
+ export declare function finalize(): Promise<void>;
54
+ /** A callOn target that receives the id of its call in `_job` (0 when it was not queued). */
55
+ export interface CallTarget {
56
+ readonly executor: ctypes.Executor;
57
+ readonly signal?: AbortSignal;
58
+ _job: number;
59
+ }
60
+ /** Id of the last call submitted to `target`: another call was submitted after a call whose id is lower. */
61
+ export declare function lastJob(target: ctypes.Executor): number;
62
+ /** Remove call `job` from the queue of `target` if it has not started: its promise rejects with `reason`. */
63
+ export declare function cancelJob(target: ctypes.Executor, job: number, reason: unknown): boolean;
64
+ /**
65
+ * Run a raw native call (e.g. a vtable entry, with `this` as the first
66
+ * argument) on the COM executor thread. Memory passed by address stays
67
+ * referenced until the call completes; for HRESULT failures, `errorInfo`
68
+ * reads `IErrorInfo` on the executor thread.
69
+ *
70
+ * As Python comtypes, `GetErrorInfo` runs only after a failure, and it must
71
+ * be the next call on the executor thread: a later call could replace or clear
72
+ * the error object. That holds when nothing was submitted after the failed
73
+ * call (code that awaits each call); otherwise, e.g. in a burst of calls
74
+ * already queued, the failure has no details.
75
+ */
76
+ export declare function executorCall(call: NativeCall, options?: CallOptions): Promise<NativeResult>;