@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
@@ -55,11 +55,12 @@ import { COMError } from "../errors.js";
55
55
  import { DISP_E_BADPARAMCOUNT, DISP_E_MEMBERNOTFOUND, DISP_E_PARAMNOTOPTIONAL, DISP_E_TYPEMISMATCH, DISP_E_UNKNOWNNAME, E_INVALIDARG, S_OK } from "../hresult.js";
56
56
  import { derivesFrom } from "../interface.js";
57
57
  import { IDispatch, IEnumVARIANT } from "../interfaces/dispatch.js";
58
- import { COMPointer } from "../pointer.js";
58
+ import { COMPointer, invokeSlotAsync, sync } from "../pointer.js";
59
+ import { linkOperation } from "../executor/operations.js";
59
60
  import { DISPATCH_METHOD, DISPATCH_PROPERTYGET, DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, DISPID_NEWENUM, DISPID_VALUE } from "../automation/constants.js";
60
- import { getIDsOfNames, invoke } from "../automation/dispatch.js";
61
+ import { getIDsOfNames, invoke, invokeAsync } from "../automation/dispatch.js";
61
62
  import { dispatchTypeInfo, documentation, typeMembers } from "../automation/members.js";
62
- import { VARIANT, borrowReference, comPointer } from "../automation/variant.js";
63
+ import { VARIANT, VARIANT_SIZE, borrowReference, clearVariant, comPointer, readVariant } from "../automation/variant.js";
63
64
  import { checkHRESULT } from "../errors.js";
64
65
  import { rawQueryInterface } from "../low-level/vtable.js";
65
66
  import { NamedArguments } from "../automation/named.js";
@@ -130,9 +131,10 @@ function wrap(value) {
130
131
  return value.map(wrap);
131
132
  return value;
132
133
  }
133
- function call(current, name, dispid, flags, args) {
134
+ /** Positional arguments and named arguments (with their DISPIDs) of a call. */
135
+ function splitArguments(current, name, args) {
134
136
  let positional = args;
135
- let namedArguments;
137
+ let named;
136
138
  const last = args[args.length - 1];
137
139
  if (last instanceof NamedArguments) {
138
140
  positional = args.slice(0, -1);
@@ -141,10 +143,26 @@ function call(current, name, dispid, flags, args) {
141
143
  if (name === null)
142
144
  throw new TypeError("Named arguments require a member name");
143
145
  const ids = getIDsOfNames(current.pointer, [name, ...names]);
144
- namedArguments = { dispids: ids.slice(1), values: names.map((key) => last.values[key]) };
146
+ named = { dispids: ids.slice(1), values: names.map((key) => last.values[key]) };
145
147
  }
146
148
  }
147
- return wrap(invoke(current.pointer, dispid, flags, positional, { named: namedArguments, name: name ?? undefined }));
149
+ return { positional, named };
150
+ }
151
+ function call(current, name, dispid, flags, args) {
152
+ const { positional, named } = splitArguments(current, name, args);
153
+ return wrap(invoke(current.pointer, dispid, flags, positional, { named, name: name ?? undefined }));
154
+ }
155
+ /** `call` on the COM executor. */
156
+ function callAsync(current, name, dispid, flags, args) {
157
+ let split;
158
+ try {
159
+ split = splitArguments(current, name, args);
160
+ }
161
+ catch (error) {
162
+ return Promise.reject(error);
163
+ }
164
+ const pending = invokeAsync(current.pointer, dispid, flags, split.positional, { named: split.named, name: name ?? undefined });
165
+ return linkOperation(pending.then(wrap), pending);
148
166
  }
149
167
  function isObject(value) {
150
168
  if (value instanceof COMPointer)
@@ -153,15 +171,20 @@ function isObject(value) {
153
171
  return value[comPointer] instanceof COMPointer;
154
172
  return false;
155
173
  }
156
- function getMember(current, name) {
174
+ function getMember(current, name, synchronous) {
157
175
  const dispid = dispidOf(current, name);
158
176
  const member = memberOf(current, dispid);
159
- const caller = (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
177
+ const syncCaller = (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
178
+ // Methods run on the COM executor (synchronously on a sync() view).
179
+ const caller = synchronous ? syncCaller : (...args) => callAsync(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
160
180
  if (member) {
161
181
  if (member.get && member.getArguments === 0)
162
182
  return call(current, name, dispid, DISPATCH_PROPERTYGET, []);
163
- if (member.method || member.get)
183
+ if (member.method)
164
184
  return caller;
185
+ // A parameterized property: read synchronously.
186
+ if (member.get)
187
+ return syncCaller;
165
188
  return undefined;
166
189
  }
167
190
  try {
@@ -201,6 +224,77 @@ function putMember(current, name, dispid, args) {
201
224
  function iterate(current) {
202
225
  return iterateNewEnum(current.pointer, wrap);
203
226
  }
227
+ /** `IEnumVARIANT::Next` calls queued together by `for await`. */
228
+ const ASYNC_BATCH = 32;
229
+ /**
230
+ * Values of a collection through `_NewEnum` and `IEnumVARIANT::Next` on the
231
+ * COM executor, converted by `convert` (`for await`). Each call fetches one
232
+ * item (some enumerators, e.g. Shell `FolderItems`, repeat the same item when
233
+ * asked for more), a batch of calls queued at once.
234
+ */
235
+ export async function* iterateNewEnumAsync(pointer, convert) {
236
+ const result = await invokeAsync(pointer, DISPID_NEWENUM, DISPATCH_METHOD | DISPATCH_PROPERTYGET, [], { name: "_NewEnum" });
237
+ if (!(result instanceof COMPointer))
238
+ throw new TypeError("_NewEnum did not return an object");
239
+ let enumerator;
240
+ try {
241
+ enumerator = result.QueryInterface(IEnumVARIANT);
242
+ }
243
+ finally {
244
+ result.Release();
245
+ }
246
+ const items = Buffer.alloc(VARIANT_SIZE * ASYNC_BATCH);
247
+ const item = (index) => items.subarray(index * VARIANT_SIZE, (index + 1) * VARIANT_SIZE);
248
+ const fetched = Array.from({ length: ASYNC_BATCH }, () => new ctypes.c_uint32());
249
+ const slot = IEnumVARIANT.methodIndex.get("Next");
250
+ // Objects among the items are handed back to a single-threaded home.
251
+ const results = Array.from({ length: ASYNC_BATCH }, (_, index) => [{ location: ctypes.addressof(items) + BigInt(index * VARIANT_SIZE), kind: "variant" }]);
252
+ let next = 0;
253
+ let count = 0;
254
+ try {
255
+ for (;;) {
256
+ const calls = fetched.map((counter, index) => {
257
+ counter.value = 0;
258
+ return invokeSlotAsync(enumerator, slot, [1, item(index), ctypes.byref(counter)], { results: results[index] });
259
+ });
260
+ const outcomes = await Promise.allSettled(calls);
261
+ // The items fetched before the end of the collection (or a failure).
262
+ count = fetched.findIndex((counter, index) => outcomes[index].status === "rejected" || outcomes[index].value !== S_OK || counter.value !== 1);
263
+ if (count === -1)
264
+ count = ASYNC_BATCH;
265
+ // Items fetched past a failure are not yielded.
266
+ for (let index = count; index < ASYNC_BATCH; index++)
267
+ if (fetched[index].value === 1)
268
+ clearVariant(item(index));
269
+ const failure = outcomes.slice(0, count + 1).find((outcome) => outcome.status === "rejected");
270
+ if (failure) {
271
+ for (let index = 0; index < count; index++)
272
+ clearVariant(item(index));
273
+ count = 0;
274
+ throw failure.reason;
275
+ }
276
+ for (next = 0; next < count;) {
277
+ let value;
278
+ try {
279
+ value = convert(readVariant(item(next)));
280
+ }
281
+ finally {
282
+ clearVariant(item(next));
283
+ next++;
284
+ }
285
+ yield value;
286
+ }
287
+ if (count < ASYNC_BATCH)
288
+ return;
289
+ }
290
+ }
291
+ finally {
292
+ // Stopped early (break): free the items not yielded.
293
+ for (; next < count; next++)
294
+ clearVariant(item(next));
295
+ enumerator.Release();
296
+ }
297
+ }
204
298
  /** Values of a collection through `_NewEnum` (`DISPID_NEWENUM`) and `IEnumVARIANT`, converted by `convert`. */
205
299
  export function* iterateNewEnum(pointer, convert) {
206
300
  const result = invoke(pointer, DISPID_NEWENUM, DISPATCH_METHOD | DISPATCH_PROPERTYGET, [], { name: "_NewEnum" });
@@ -219,7 +313,7 @@ export function* iterateNewEnum(pointer, convert) {
219
313
  const item = __addDisposableResource(env_2, new VARIANT(), false);
220
314
  const fetched = new ctypes.c_uint32();
221
315
  for (;;) {
222
- const hr = enumerator.Next(1, item, ctypes.byref(fetched));
316
+ const hr = sync(enumerator).Next(1, item, ctypes.byref(fetched));
223
317
  if (hr !== S_OK || fetched.value === 0)
224
318
  return;
225
319
  let value;
@@ -250,8 +344,8 @@ function describe(current) {
250
344
  loadTypeInfo(current);
251
345
  return `[Dispatch ${current.typeName ?? "object"}]`;
252
346
  }
253
- function createProxy(pointer) {
254
- const current = { pointer, dispids: new Map(), members: undefined, typeName: undefined };
347
+ function createProxy(pointer, shared, synchronous = false) {
348
+ const current = shared ?? { pointer, dispids: new Map(), members: undefined, typeName: undefined };
255
349
  const target = (() => undefined);
256
350
  // util.inspect does not go through proxy traps: it reads the target.
257
351
  Object.defineProperty(target, inspect, { value: () => describe(current) });
@@ -263,6 +357,8 @@ function createProxy(pointer) {
263
357
  return current.pointer;
264
358
  case Symbol.iterator:
265
359
  return () => iterate(current);
360
+ case Symbol.asyncIterator:
361
+ return () => iterateNewEnumAsync(current.pointer, wrap);
266
362
  case Symbol.dispose:
267
363
  return () => {
268
364
  if (!current.pointer.released)
@@ -279,7 +375,7 @@ function createProxy(pointer) {
279
375
  // Not a thenable: `await obj` must not invoke a COM member named "then".
280
376
  if (property === "then")
281
377
  return undefined;
282
- return getMember(current, property);
378
+ return getMember(current, property, synchronous);
283
379
  },
284
380
  set(_target, property, value) {
285
381
  if (typeof property === "symbol")
@@ -289,7 +385,7 @@ function createProxy(pointer) {
289
385
  },
290
386
  has(_target, property) {
291
387
  if (typeof property === "symbol")
292
- return property === comPointer || property === Symbol.iterator || property === Symbol.dispose;
388
+ return property === comPointer || property === Symbol.iterator || property === Symbol.asyncIterator || property === Symbol.dispose;
293
389
  try {
294
390
  dispidOf(current, property);
295
391
  return true;
@@ -301,7 +397,11 @@ function createProxy(pointer) {
301
397
  }
302
398
  },
303
399
  apply(_target, _this, args) {
304
- return call(current, null, DISPID_VALUE, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
400
+ // The default member: a property (synchronous) or a method.
401
+ const member = memberOf(current, DISPID_VALUE);
402
+ if (synchronous || (member && member.get && !member.method))
403
+ return call(current, null, DISPID_VALUE, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
404
+ return callAsync(current, null, DISPID_VALUE, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
305
405
  },
306
406
  ownKeys() {
307
407
  return [];
@@ -335,6 +435,11 @@ export function Dispatch(object) {
335
435
  export function adoptDispatch(pointer) {
336
436
  return createProxy(pointer);
337
437
  }
438
+ /** The synchronous view of a dispatch object: methods called synchronously, same reference. */
439
+ export function syncDispatch(object) {
440
+ const current = state(object);
441
+ return (current.view ??= createProxy(current.pointer, current, true));
442
+ }
338
443
  export function isDispatch(value) {
339
444
  return typeof value === "function" && states.has(value);
340
445
  }
@@ -367,10 +472,10 @@ export function putRefProperty(object, name, ...argsAndValue) {
367
472
  const current = state(object);
368
473
  call(current, name, dispidOf(current, name), DISPATCH_PROPERTYPUTREF, argsAndValue);
369
474
  }
370
- /** Method call (`DISPATCH_METHOD` only). */
475
+ /** Method call (`DISPATCH_METHOD` only), on the COM executor. */
371
476
  export function invokeMethod(object, name, ...args) {
372
477
  const current = state(object);
373
- return call(current, name, dispidOf(current, name), DISPATCH_METHOD, args);
478
+ return callAsync(current, name, dispidOf(current, name), DISPATCH_METHOD, args);
374
479
  }
375
480
  /** Member information from the type library, when available. */
376
481
  export function memberInfo(object, name) {
@@ -63,7 +63,7 @@ import { GUIDKIND_DEFAULT_SOURCE_DISP_IID, IConnectionPointContainer, IProvideCl
63
63
  import { IDispatch } from "../interfaces/dispatch.js";
64
64
  import { IProvideClassInfo, ITypeInfo, ITypeLib } from "../interfaces/typeinfo.js";
65
65
  import { IUnknown } from "../interfaces/unknown.js";
66
- import { COMPointer } from "../pointer.js";
66
+ import { COMPointer, sync } from "../pointer.js";
67
67
  import { COMObject } from "../server/comobject.js";
68
68
  function sourcePointer(source) {
69
69
  const borrowed = borrowReference(source);
@@ -73,7 +73,7 @@ function sourcePointer(source) {
73
73
  }
74
74
  function typeInfoFromReference(typeInfo, reference) {
75
75
  const out = new ctypes.c_void_p();
76
- typeInfo.GetRefTypeInfo(reference, ctypes.byref(out));
76
+ sync(typeInfo).GetRefTypeInfo(reference, ctypes.byref(out));
77
77
  return COMPointer.fromAddress(out.value, ITypeInfo);
78
78
  }
79
79
  /** Default source interface of a coclass type info. */
@@ -81,11 +81,11 @@ function defaultSourceOf(coclass) {
81
81
  const count = withTypeAttr(coclass, (attr) => attr.cImplTypes);
82
82
  for (let index = 0; index < count; index++) {
83
83
  const flags = new ctypes.c_int32();
84
- coclass.GetImplTypeFlags(index, ctypes.byref(flags));
84
+ sync(coclass).GetImplTypeFlags(index, ctypes.byref(flags));
85
85
  if ((flags.value & (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) !== (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE))
86
86
  continue;
87
87
  const reference = new ctypes.c_uint32();
88
- coclass.GetRefTypeOfImplType(index, ctypes.byref(reference));
88
+ sync(coclass).GetRefTypeOfImplType(index, ctypes.byref(reference));
89
89
  return typeInfoFromReference(coclass, reference.value);
90
90
  }
91
91
  return null;
@@ -107,7 +107,7 @@ function eventTypeInfo(source, iid) {
107
107
  const env_2 = { stack: [], error: void 0, hasError: false };
108
108
  try {
109
109
  const owned = __addDisposableResource(env_2, provider, false);
110
- const coclass = __addDisposableResource(env_2, attempt(() => owned.GetClassInfo()), false);
110
+ const coclass = __addDisposableResource(env_2, attempt(() => sync(owned).GetClassInfo()), false);
111
111
  if (coclass) {
112
112
  const fromCoclass = attempt(() => defaultSourceOf(coclass));
113
113
  if (fromCoclass && (!iid || withTypeAttr(fromCoclass, (attr) => attr.guid.equals(iid))))
@@ -150,10 +150,10 @@ function typeInfoInLibrary(typeInfo, iid) {
150
150
  try {
151
151
  const library = new ctypes.c_void_p();
152
152
  const index = new ctypes.c_uint32();
153
- typeInfo.GetContainingTypeLib(ctypes.byref(library), ctypes.byref(index));
153
+ sync(typeInfo).GetContainingTypeLib(ctypes.byref(library), ctypes.byref(index));
154
154
  const typeLib = __addDisposableResource(env_3, COMPointer.fromAddress(library.value, ITypeLib), false);
155
155
  const out = new ctypes.c_void_p();
156
- typeLib.GetTypeInfoOfGuid(iid, ctypes.byref(out));
156
+ sync(typeLib).GetTypeInfoOfGuid(iid, ctypes.byref(out));
157
157
  return COMPointer.fromAddress(out.value, ITypeInfo);
158
158
  }
159
159
  catch (e_3) {
@@ -186,7 +186,7 @@ function resolveInterface(source, option) {
186
186
  const env_5 = { stack: [], error: void 0, hasError: false };
187
187
  try {
188
188
  const owned = __addDisposableResource(env_5, provider, false);
189
- iid = attempt(() => owned.GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID));
189
+ iid = attempt(() => sync(owned).GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID));
190
190
  }
191
191
  catch (e_4) {
192
192
  env_5.error = e_4;
@@ -284,14 +284,14 @@ export function GetEvents(source, handler, options = {}) {
284
284
  const pointer = __addDisposableResource(env_6, sourcePointer(source), false);
285
285
  const { definition, names } = resolveInterface(pointer, options.interface);
286
286
  const container = __addDisposableResource(env_6, pointer.QueryInterface(IConnectionPointContainer), false);
287
- const point = container.FindConnectionPoint(definition.iid);
287
+ const point = sync(container).FindConnectionPoint(definition.iid);
288
288
  if (!point)
289
289
  throw new COMError(E_NOINTERFACE, { text: "FindConnectionPoint returned NULL" });
290
290
  const Sink = sinkClassFor(definition);
291
291
  const sink = new Sink(handler, names);
292
292
  let cookie;
293
293
  try {
294
- cookie = point.Advise(sink);
294
+ cookie = sync(point).Advise(sink);
295
295
  }
296
296
  catch (error) {
297
297
  point.Release();
@@ -303,7 +303,7 @@ export function GetEvents(source, handler, options = {}) {
303
303
  return;
304
304
  connected = false;
305
305
  try {
306
- point.Unadvise(cookie);
306
+ sync(point).Unadvise(cookie);
307
307
  }
308
308
  finally {
309
309
  point.Release();
@@ -1,5 +1,7 @@
1
1
  import { GUID } from "../guid.ts";
2
2
  import type { InterfaceDef, InterfacePointer } from "../interface.ts";
3
+ import { COMPointer } from "../pointer.ts";
4
+ import type { SyncPointer } from "../interface.ts";
3
5
  import type { CoClass } from "../typelib/coclass.ts";
4
6
  import type { AutomationObject, DispatchObject } from "./dynamic.ts";
5
7
  export { Dispatch, adoptDispatch, dispatchPointer, enumerate, getProperty, invokeMethod, isDispatch, memberInfo, putProperty, putRefProperty, release, typeName } from "./dynamic.ts";
@@ -13,11 +15,27 @@ export type { EventConnection, GetEventsOptions } from "./events.ts";
13
15
  export type ClassLike = GUID | string;
14
16
  /** CLSID of a ProgID or CLSID string. */
15
17
  export declare function classID(value: ClassLike): GUID;
18
+ /**
19
+ * A view whose methods run synchronously on the home thread: of a typed
20
+ * pointer (sharing its reference) or of a dynamic dispatch object. For event
21
+ * handlers, COM servers and code that needs the lowest latency.
22
+ */
23
+ export declare function sync<I extends InterfaceDef<any>>(pointer: COMPointer<I> | InterfacePointer<I>): SyncPointer<I>;
24
+ export declare function sync(object: DispatchObject): DispatchObject;
16
25
  export interface ObjectOptions<T extends InterfaceDef | undefined = undefined> {
17
26
  /** Return this interface. */
18
27
  readonly interface?: T;
19
28
  /** Return a dynamic dispatch object (`GetIDsOfNames` + `Invoke`, no type library). Python: `dynamic=True`. */
20
29
  readonly dynamic?: boolean;
30
+ /**
31
+ * Obtain the object on the home thread instead of the COM executor: an
32
+ * in-process object then lives in the home apartment, called directly
33
+ * (no marshaling, no executor) but always on the home thread. Needed in a
34
+ * single-threaded home for objects whose interfaces cannot be marshaled
35
+ * (e.g. ADSI `IDirectorySearch`); a multithreaded home shares objects with
36
+ * the executor anyway.
37
+ */
38
+ readonly home?: boolean;
21
39
  }
22
40
  export interface CreateObjectOptions<T extends InterfaceDef | undefined = undefined> extends ObjectOptions<T> {
23
41
  /** Default `CLSCTX_SERVER`. */
@@ -26,45 +44,47 @@ export interface CreateObjectOptions<T extends InterfaceDef | undefined = undefi
26
44
  readonly machine?: string;
27
45
  }
28
46
  /**
29
- * Create a COM object. Python equivalent: `comtypes.client.CreateObject`.
47
+ * Create a COM object on the COM executor. Python equivalent:
48
+ * `comtypes.client.CreateObject`.
30
49
  *
31
50
  * ```ts
32
- * using dict = CreateObject("Scripting.Dictionary"); // IDictionary, typed from scrrun.dll
33
- * dict.Add("a", 1);
34
- * using dynamic = CreateObject("Scripting.Dictionary", { dynamic: true }); // IDispatch, late bound
35
- * using typed = CreateObject(Scripting.Dictionary); // coclass: statically typed default interface
51
+ * using dict = await CreateObject("Scripting.Dictionary"); // IDictionary, typed from scrrun.dll
52
+ * await dict.Add("a", 1);
53
+ * using dynamic = await CreateObject("Scripting.Dictionary", { dynamic: true }); // IDispatch, late bound
54
+ * using typed = await CreateObject(Scripting.Dictionary); // coclass: statically typed default interface
36
55
  * ```
37
56
  */
38
57
  export declare function CreateObject<T extends InterfaceDef<any>>(coclass: CoClass<T>, options?: Omit<CreateObjectOptions, "interface" | "dynamic"> & {
39
58
  readonly dynamic?: false;
40
- }): InterfacePointer<T>;
59
+ }): Promise<InterfacePointer<T>>;
41
60
  export declare function CreateObject(progid: ClassLike | CoClass, options: CreateObjectOptions & {
42
61
  readonly dynamic: true;
43
- }): DispatchObject;
62
+ }): Promise<DispatchObject>;
44
63
  export declare function CreateObject<T extends InterfaceDef<any>>(progid: ClassLike | CoClass, options: CreateObjectOptions<T> & {
45
64
  readonly interface: T;
46
- }): InterfacePointer<T>;
47
- export declare function CreateObject(progid: ClassLike, options?: CreateObjectOptions): AutomationObject;
65
+ }): Promise<InterfacePointer<T>>;
66
+ export declare function CreateObject(progid: ClassLike, options?: CreateObjectOptions): Promise<AutomationObject>;
48
67
  export type GetObjectOptions<T extends InterfaceDef | undefined = undefined> = ObjectOptions<T>;
49
68
  /**
50
- * A running object registered in the Running Object Table. Python
51
- * equivalent: `comtypes.client.GetActiveObject`.
69
+ * A running object registered in the Running Object Table, obtained on the
70
+ * COM executor. Python equivalent: `comtypes.client.GetActiveObject`.
52
71
  */
53
72
  export declare function GetActiveObject(progid: ClassLike, options: GetObjectOptions & {
54
73
  readonly dynamic: true;
55
- }): DispatchObject;
74
+ }): Promise<DispatchObject>;
56
75
  export declare function GetActiveObject<T extends InterfaceDef>(progid: ClassLike, options: GetObjectOptions<T> & {
57
76
  readonly interface: T;
58
- }): InterfacePointer<T>;
59
- export declare function GetActiveObject(progid: ClassLike, options?: GetObjectOptions): AutomationObject;
77
+ }): Promise<InterfacePointer<T>>;
78
+ export declare function GetActiveObject(progid: ClassLike, options?: GetObjectOptions): Promise<AutomationObject>;
60
79
  /**
61
- * Bind to an object by display name (`CoGetObject`), e.g. `"winmgmts:"` or a
62
- * file moniker. Python equivalent: `comtypes.client.GetObject`.
80
+ * Bind to an object by display name (`CoGetObject`) on the COM executor,
81
+ * e.g. `"winmgmts:"` or a file moniker. Python equivalent:
82
+ * `comtypes.client.GetObject`.
63
83
  */
64
84
  export declare function GetObject(displayName: string, options: GetObjectOptions & {
65
85
  readonly dynamic: true;
66
- }): DispatchObject;
86
+ }): Promise<DispatchObject>;
67
87
  export declare function GetObject<T extends InterfaceDef>(displayName: string, options: GetObjectOptions<T> & {
68
88
  readonly interface: T;
69
- }): InterfacePointer<T>;
70
- export declare function GetObject(displayName: string, options?: GetObjectOptions): AutomationObject;
89
+ }): Promise<InterfacePointer<T>>;
90
+ export declare function GetObject(displayName: string, options?: GetObjectOptions): Promise<AutomationObject>;
@@ -51,15 +51,23 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
51
51
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
52
  });
53
53
  import * as ctypes from "node-ctypes";
54
- import { checkHRESULT } from "../errors.js";
54
+ import { CLSCTX_INPROC_SERVER, CLSCTX_SERVER } from "../constants.js";
55
+ import { COMError, checkHRESULT } from "../errors.js";
56
+ import { handOver, homeApartment } from "../executor/apartment.js";
57
+ import { isLocalClass } from "../executor/classes.js";
58
+ import { executorTarget } from "../executor/executor.js";
59
+ import { operation } from "../executor/operations.js";
55
60
  import { GUID } from "../guid.js";
61
+ import { E_POINTER } from "../hresult.js";
56
62
  import { IDispatch } from "../interfaces/dispatch.js";
57
63
  import { IUnknown } from "../interfaces/unknown.js";
58
64
  import { ole32, oleaut32 } from "../low-level/native.js";
59
- import { COMPointer } from "../pointer.js";
65
+ import { COSERVERINFO, MULTI_QI } from "../low-level/types.js";
66
+ import { COMPointer, sync as syncPointer } from "../pointer.js";
60
67
  import { CoCreateInstance, CoCreateInstanceEx } from "../runtime.js";
61
- import { GetBestInterface } from "./best.js";
62
- import { adoptDispatch } from "./dynamic.js";
68
+ import { queryOrDispatch } from "./dual.js";
69
+ import { GetBestInterface, loadBestModule } from "./best.js";
70
+ import { adoptDispatch, isDispatch, syncDispatch } from "./dynamic.js";
63
71
  import { isCoClass } from "../typelib/coclass.js";
64
72
  export { Dispatch, adoptDispatch, dispatchPointer, enumerate, getProperty, invokeMethod, isDispatch, memberInfo, putProperty, putRefProperty, release, typeName } from "./dynamic.js";
65
73
  export { GetBestInterface, wrap } from "./best.js";
@@ -73,6 +81,9 @@ export function classID(value) {
73
81
  throw new TypeError("Expected a ProgID, a CLSID string or a GUID");
74
82
  return GUID.isGUIDString(value) ? new GUID(value) : GUID.fromProgID(value);
75
83
  }
84
+ export function sync(object) {
85
+ return isDispatch(object) ? syncDispatch(object) : syncPointer(object);
86
+ }
76
87
  /**
77
88
  * The object as requested: `interface`, a dynamic dispatch object, or its best
78
89
  * interface (dynamic when it has no type information). Takes over `pointer`.
@@ -101,22 +112,118 @@ function manage(pointer, options) {
101
112
  __disposeResources(env_1);
102
113
  }
103
114
  }
115
+ /**
116
+ * {@link manage}, after loading the type library of the object's best interface
117
+ * asynchronously: the first object of a large library does not block the
118
+ * event loop while its definitions are built.
119
+ */
120
+ async function manageLoaded(pointer, options) {
121
+ if (!options.interface && !options.dynamic) {
122
+ try {
123
+ await loadBestModule(pointer);
124
+ }
125
+ catch (error) {
126
+ pointer.Release();
127
+ throw error;
128
+ }
129
+ }
130
+ return manage(pointer, options);
131
+ }
132
+ /**
133
+ * `iface` of `unknown`; a dispinterface (or a dual interface whose vtable cannot
134
+ * be marshaled across apartments) is reached through `IDispatch`.
135
+ */
136
+ function queryInterface(unknown, iface) {
137
+ return queryOrDispatch(unknown, iface) ?? unknown.QueryInterface(iface);
138
+ }
139
+ /**
140
+ * Obtain an object on the COM executor: `start` queues the call whose out
141
+ * parameter `out` receives an `IUnknown`. The object lives in the
142
+ * multithreaded apartment (or in COM's host apartment for single-threaded
143
+ * classes); a single-threaded home receives its own reference.
144
+ */
145
+ async function obtain(method, current, start) {
146
+ const out = new ctypes.c_void_p();
147
+ if (current.aborted)
148
+ throw current.reason;
149
+ const target = { executor: executorTarget(), _job: 0 };
150
+ const pending = start(target, out);
151
+ if (target._job !== 0)
152
+ current.queued(target.executor, target._job);
153
+ checkHRESULT((await pending), method);
154
+ if (!out.value)
155
+ throw new COMError(E_POINTER, { method });
156
+ if (homeApartment() === "sta")
157
+ await handOver([{ location: ctypes.addressof(out), kind: "pointer", iid: IUnknown.iid }]);
158
+ return COMPointer.fromAddress(out.value, IUnknown);
159
+ }
160
+ /** `IUnknown` from a call made on the home thread (`home: true`). */
161
+ function obtainHome(method, call) {
162
+ const out = new ctypes.c_void_p();
163
+ checkHRESULT(call(out), method);
164
+ if (!out.value)
165
+ throw new COMError(E_POINTER, { method });
166
+ return COMPointer.fromAddress(out.value, IUnknown);
167
+ }
168
+ /** `CoCreateInstanceEx` for `IUnknown` on the executor (remote machines). */
169
+ function createInstanceEx(target, clsid, clsctx, machine, out) {
170
+ const name = ctypes.create_unicode_buffer(machine);
171
+ const server = new COSERVERINFO();
172
+ server.pwszName = ctypes.addressof(name);
173
+ const result = new MULTI_QI();
174
+ result.pIID = ctypes.addressof(IUnknown.iid);
175
+ return ole32()
176
+ .CoCreateInstanceEx.callOn(target, clsid._buffer, null, clsctx, server._buffer, 1, result._buffer)
177
+ .then((hr) => {
178
+ void name;
179
+ if (hr < 0)
180
+ return hr;
181
+ out.value = result.pItf;
182
+ return result.hr;
183
+ });
184
+ }
104
185
  export function CreateObject(progid, options = {}) {
105
- // A coclass from a type library: its default interface, typed.
106
- const coclass = isCoClass(progid) ? progid : null;
107
- const clsid = coclass ? coclass.clsid : classID(progid);
108
- const iface = options.interface ?? (options.dynamic ? IDispatch : (coclass?.defaultInterface ?? IUnknown));
109
- const pointer = options.machine ? CoCreateInstanceEx(clsid, iface, { clsctx: options.clsctx, machine: options.machine }) : CoCreateInstance(clsid, iface, { clsctx: options.clsctx });
110
- return options.interface || (coclass && !options.dynamic) ? pointer : manage(pointer, options);
186
+ return operation(async (current) => {
187
+ // A coclass from a type library: its default interface, typed.
188
+ const coclass = isCoClass(progid) ? progid : null;
189
+ const clsid = coclass ? coclass.clsid : classID(progid);
190
+ const clsctx = options.clsctx ?? (options.machine ? CLSCTX_SERVER & ~CLSCTX_INPROC_SERVER : CLSCTX_SERVER);
191
+ const unknown = options.home || isLocalClass(clsid)
192
+ ? options.machine
193
+ ? CoCreateInstanceEx(clsid, IUnknown, { clsctx, machine: options.machine })
194
+ : CoCreateInstance(clsid, IUnknown, { clsctx })
195
+ : await obtain(options.machine ? "CoCreateInstanceEx" : "CoCreateInstance", current, (target, out) => options.machine ? createInstanceEx(target, clsid, clsctx, options.machine, out) : ole32().CoCreateInstance.callOn(target, clsid._buffer, null, clsctx, IUnknown.iid._buffer, ctypes.byref(out)));
196
+ if (options.interface || (coclass && !options.dynamic)) {
197
+ const env_2 = { stack: [], error: void 0, hasError: false };
198
+ try {
199
+ const owned = __addDisposableResource(env_2, unknown, false);
200
+ return queryInterface(owned, options.interface ?? coclass.defaultInterface);
201
+ }
202
+ catch (e_2) {
203
+ env_2.error = e_2;
204
+ env_2.hasError = true;
205
+ }
206
+ finally {
207
+ __disposeResources(env_2);
208
+ }
209
+ }
210
+ return manageLoaded(unknown, options);
211
+ });
111
212
  }
112
213
  export function GetActiveObject(progid, options = {}) {
113
- const out = new ctypes.c_void_p();
114
- checkHRESULT(oleaut32().GetActiveObject(classID(progid)._buffer, null, ctypes.byref(out)), "GetActiveObject");
115
- return manage(COMPointer.fromAddress(out.value, IUnknown), options);
214
+ return operation(async (current) => {
215
+ const clsid = classID(progid);
216
+ const unknown = options.home
217
+ ? obtainHome("GetActiveObject", (out) => oleaut32().GetActiveObject(clsid._buffer, null, ctypes.byref(out)))
218
+ : await obtain("GetActiveObject", current, (target, out) => oleaut32().GetActiveObject.callOn(target, clsid._buffer, null, ctypes.byref(out)));
219
+ return manageLoaded(unknown, options);
220
+ });
116
221
  }
117
222
  export function GetObject(displayName, options = {}) {
118
- const iface = options.interface ?? (options.dynamic ? IDispatch : IUnknown);
119
- const out = new ctypes.c_void_p();
120
- checkHRESULT(ole32().CoGetObject(displayName, null, iface.iid._buffer, ctypes.byref(out)), "CoGetObject");
121
- return manage(COMPointer.fromAddress(out.value, iface), options);
223
+ return operation(async (current) => {
224
+ const unknown = options.home
225
+ ? obtainHome("CoGetObject", (out) => ole32().CoGetObject(displayName, null, IUnknown.iid._buffer, ctypes.byref(out)))
226
+ : await obtain("CoGetObject", current, (target, out) => ole32().CoGetObject.callOn(target, displayName, null, IUnknown.iid._buffer, ctypes.byref(out)));
227
+ return manageLoaded(unknown, options);
228
+ });
122
229
  }