@nativescript/windows-quickjs 0.1.0-next.2026-08-03-30819078286 → 1.0.0-beta.7

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 (28) hide show
  1. package/framework/__PROJECT_NAME__/App.xaml.cs +3 -2
  2. package/framework/__PROJECT_NAME__/CrashDiagnostics.cs +3 -3
  3. package/framework/__PROJECT_NAME__/RuntimeHost.cs +149 -24
  4. package/framework/__PROJECT_NAME__/__PROJECT_NAME__.csproj +35 -41
  5. package/framework/dotnet-bridge/BinaryProtocol.cs +18 -0
  6. package/framework/dotnet-bridge/Bridge.BinaryDispatch.cs +83 -8
  7. package/framework/dotnet-bridge/Bridge.Dispatch.cs +40 -35
  8. package/framework/dotnet-bridge/Bridge.JsDelegate.cs +115 -59
  9. package/framework/dotnet-bridge/Bridge.Proxy.cs +158 -230
  10. package/framework/dotnet-bridge/Bridge.TaskHelper.cs +2 -1
  11. package/framework/dotnet-bridge/Bridge.cs +45 -5
  12. package/framework/dotnet-bridge/DotNetBridge.csproj +8 -0
  13. package/framework/libs/x64/nativescript.dll +0 -0
  14. package/framework/tools/ManifestMerger/ManifestMerger.dll +0 -0
  15. package/framework/tools/ManifestMerger/ManifestMerger.pdb +0 -0
  16. package/framework/tools/dotnet-tool-x64.exe +0 -0
  17. package/framework/tools/dotnet-tool.exe +0 -0
  18. package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.dll +0 -0
  19. package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.exe +0 -0
  20. package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.pdb +0 -0
  21. package/framework/tools/nsbundle_pack-x64.exe +0 -0
  22. package/framework/tools/nsbundle_pack.exe +0 -0
  23. package/framework/tools/typings-generator-x64.exe +0 -0
  24. package/framework/tools/typings-generator.exe +0 -0
  25. package/package.json +1 -1
  26. package/framework/tools/sbg-arm64.exe +0 -0
  27. package/framework/tools/sbg-x64.exe +0 -0
  28. package/framework/tools/sbg.exe +0 -0
@@ -14,9 +14,9 @@ namespace NativeScriptBridge;
14
14
 
15
15
  public static partial class Bridge
16
16
  {
17
- // Cache for dynamically generated proxy types (dev-only fallback). Keyed by base type PLUS
18
- // the exact set of interfaces/members a given JS `overrides` object asked for, so different
19
- // JS subclasses of the same base type (different override sets) get distinct emitted types.
17
+ // The types behind JS subclasses, emitted at runtime. Keyed by base type PLUS the exact set of
18
+ // interfaces/members a JS class asked for, so different JS subclasses of the same base type
19
+ // (different override sets) get distinct emitted types.
20
20
  private readonly record struct ProxyTypeKey(Type BaseType, string InterfaceKey, string MemberKey);
21
21
  private static readonly ConcurrentDictionary<ProxyTypeKey, Type> s_dynamicProxyCache = new();
22
22
  private static int s_dynamicProxyTypeCounter = 0;
@@ -51,9 +51,7 @@ public static partial class Bridge
51
51
  public static T InvokeMethodTyped<T>(object instance, string methodName, object[] args)
52
52
  {
53
53
  var result = ProxyInvokeMethod(instance, methodName, args);
54
- if (result is null) return default!;
55
- if (result is T t) return t;
56
- return (T)Convert.ChangeType(result, typeof(T), CultureInfo.InvariantCulture);
54
+ return (T)ConvertJsResult(result, typeof(T))!;
57
55
  }
58
56
 
59
57
  public static object? InvokeMethod(object instance, string methodName, object[] args)
@@ -69,9 +67,7 @@ public static partial class Bridge
69
67
  public static T GetProperty<T>(object instance, string propertyName)
70
68
  {
71
69
  var result = ProxyGetProperty(instance, propertyName);
72
- if (result is null) return default!;
73
- if (result is T t) return t;
74
- return (T)Convert.ChangeType(result, typeof(T), CultureInfo.InvariantCulture);
70
+ return (T)ConvertJsResult(result, typeof(T))!;
75
71
  }
76
72
 
77
73
  public static void SetProperty(object instance, string propertyName, object? value)
@@ -79,98 +75,19 @@ public static partial class Bridge
79
75
  ProxySetProperty(instance, propertyName, value);
80
76
  }
81
77
  }
82
- private sealed class ProxyCallbackHolder { public int CallbackId; public int HandleId; public ProxyCallbackHolder(int cb) { CallbackId = cb; HandleId = 0; } }
83
-
84
- private static readonly ConditionalWeakTable<object, ProxyCallbackHolder> s_proxyCallbacks = new();
85
- private static readonly ThreadLocal<int?> s_pendingProxyCallbackId = new(() => null);
86
- private static readonly object s_proxyRegisterLock = new();
87
- private static bool s_proxyDispatcherRegistered = false;
88
-
89
- private static void EnsureProxyDispatcherCallbacksRegistered()
78
+ // Ties a JS-backed instance to its JS dispatcher (and the handle its JS object holds). Lives as
79
+ // long as the instance (ConditionalWeakTable value); when the instance is collected the runtime
80
+ // is told to unpin the dispatcher.
81
+ private sealed class ProxyCallbackHolder(int callbackId)
90
82
  {
91
- if (s_proxyDispatcherRegistered) return;
92
- lock (s_proxyRegisterLock)
93
- {
94
- if (s_proxyDispatcherRegistered) return;
95
-
96
- Type? pdType = null;
97
- foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
98
- {
99
- try
100
- {
101
- pdType = asm.GetType("NativeScriptGeneratedProxies.ProxyDispatcher")
102
- ?? asm.GetType("NSWinRTProxies.ProxyDispatcher")
103
- ?? asm.GetType("NativeScriptGeneratedProxies.ProxyDispatcher");
104
- if (pdType != null) break;
105
- }
106
- catch { }
107
- }
83
+ public readonly int CallbackId = callbackId;
84
+ public int HandleId;
108
85
 
109
- if (pdType != null)
110
- {
111
- // Properties generated by SBG
112
- var p1 = pdType.GetProperty("JsInvokeMethod", BindingFlags.Public | BindingFlags.Static);
113
- p1?.SetValue(null, new Func<object, string, object[], object?>(ProxyInvokeMethod));
114
-
115
- var p2 = pdType.GetProperty("JsInvokeVoid", BindingFlags.Public | BindingFlags.Static);
116
- p2?.SetValue(null, new Action<object, string, object[]>(ProxyInvokeVoid));
117
-
118
- var p3 = pdType.GetProperty("JsGetProperty", BindingFlags.Public | BindingFlags.Static);
119
- p3?.SetValue(null, new Func<object, string, object?>(ProxyGetProperty));
120
-
121
- var p4 = pdType.GetProperty("JsSetProperty", BindingFlags.Public | BindingFlags.Static);
122
- p4?.SetValue(null, new Action<object, string, object?>(ProxySetProperty));
123
-
124
- var p5 = pdType.GetProperty("JsInitializeInstance", BindingFlags.Public | BindingFlags.Static);
125
- p5?.SetValue(null, new Action<object, string>(ProxyInitializeInstance));
126
- }
127
-
128
- s_proxyDispatcherRegistered = true;
129
- }
130
- }
131
-
132
- private static bool DynamicProxiesEnabled()
133
- {
134
- // Always allow dynamic proxies in dev when Reflection.Emit is available.
135
- return s_dynamicModule != null;
86
+ ~ProxyCallbackHolder() => ReleaseJsCallback(CallbackId);
136
87
  }
137
88
 
138
- private static Type? FindGeneratedProxyType(string typeName)
139
- {
140
- if (string.IsNullOrEmpty(typeName)) return null;
141
- var lastDot = typeName.LastIndexOf('.');
142
- var shortName = lastDot >= 0 ? typeName[(lastDot + 1)..] : typeName;
143
- foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
144
- {
145
- try
146
- {
147
- // Only consider assemblies that look like generated proxy assemblies
148
- var asmName = asm.GetName().Name ?? "";
149
- if (!string.Equals(asmName, "NativeScriptGeneratedProxies", StringComparison.Ordinal)
150
- && !string.Equals(asmName, "NSWinRTProxies", StringComparison.Ordinal))
151
- {
152
- // Also check for candidate full-type names in any assembly
153
- var candidates = new[] { $"NativeScriptGeneratedProxies.{shortName}", $"NSWinRTProxies.{shortName}" };
154
- foreach (var cn in candidates)
155
- {
156
- var t = asm.GetType(cn);
157
- if (t is not null) return t;
158
- }
159
- continue;
160
- }
161
-
162
- // If this is a generated proxies assembly, look up the proxy type name.
163
- var genCandidates = new[] { $"NativeScriptGeneratedProxies.{shortName}", $"NSWinRTProxies.{shortName}" };
164
- foreach (var cn in genCandidates)
165
- {
166
- var t = asm.GetType(cn);
167
- if (t is not null) return t;
168
- }
169
- }
170
- catch { }
171
- }
172
- return null;
173
- }
89
+ private static readonly ConditionalWeakTable<object, ProxyCallbackHolder> s_proxyCallbacks = new();
90
+ private static readonly ThreadLocal<int?> s_pendingProxyCallbackId = new(() => null);
174
91
 
175
92
  private static Type GetOrCreateDynamicProxyType(Type baseType, string[] interfaceNames, string[] memberNames)
176
93
  {
@@ -204,20 +121,17 @@ public static partial class Bridge
204
121
 
205
122
  var tb = s_dynamicModule.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class, baseType);
206
123
 
207
- // Mirror public base constructors and ensure at least a parameterless
208
- // ctor exists on the derived type. If the base type has no parameterless
209
- // ctor, emit a parameterless ctor that forwards default(T) values to the
210
- // first available base ctor (dev-only convenience).
211
- var baseCtors = baseType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
212
- .Where(c => !c.IsGenericMethod)
124
+ // Mirror the public and protected base constructors: a JS subclass can call either through
125
+ // super(...), and abstract classes / composable WinRT classes (Panel, Control) only have
126
+ // protected ones.
127
+ var baseCtors = baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
128
+ .Where(c => !c.IsGenericMethod && (c.IsPublic || c.IsFamily || c.IsFamilyOrAssembly))
213
129
  .ToArray();
214
130
 
215
- ConstructorInfo? chosenBaseForDefault = null;
216
131
  foreach (var bc in baseCtors)
217
132
  {
218
133
  var parameters = bc.GetParameters();
219
134
  if (parameters.Any(p => p.ParameterType.IsByRef)) continue;
220
- chosenBaseForDefault ??= bc;
221
135
 
222
136
  // Define a matching ctor on the derived type that forwards args to base.
223
137
  var paramTypes = parameters.Select(p => p.ParameterType).ToArray();
@@ -241,47 +155,6 @@ public static partial class Bridge
241
155
  ilg.Emit(OpCodes.Ret);
242
156
  }
243
157
 
244
- // If we didn't define a parameterless ctor, emit one that forwards
245
- // default(T) values to the chosen base ctor (if any), otherwise call
246
- // System.Object..ctor.
247
- if (!baseCtors.Any(c => c.GetParameters().Length == 0))
248
- {
249
- var paramless = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
250
- var ilg = paramless.GetILGenerator();
251
- if (chosenBaseForDefault is not null)
252
- {
253
- ilg.Emit(OpCodes.Ldarg_0);
254
- var parameters = chosenBaseForDefault.GetParameters();
255
- // For each param, emit default value (null for ref types, initobj local for value types)
256
- for (int i = 0; i < parameters.Length; i++)
257
- {
258
- var ptype = parameters[i].ParameterType;
259
- if (ptype.IsByRef) throw new InvalidOperationException("Cannot forward byref parameters in dynamic ctor");
260
- if (ptype.IsValueType)
261
- {
262
- var temp = ilg.DeclareLocal(ptype);
263
- ilg.Emit(OpCodes.Ldloca_S, temp);
264
- ilg.Emit(OpCodes.Initobj, ptype);
265
- ilg.Emit(OpCodes.Ldloc, temp);
266
- }
267
- else
268
- {
269
- ilg.Emit(OpCodes.Ldnull);
270
- }
271
- }
272
- ilg.Emit(OpCodes.Call, chosenBaseForDefault);
273
- ilg.Emit(OpCodes.Ret);
274
- }
275
- else
276
- {
277
- // No public base ctors (rare); call Object..ctor
278
- var objCtor = typeof(object).GetConstructor(Type.EmptyTypes)!;
279
- ilg.Emit(OpCodes.Ldarg_0);
280
- ilg.Emit(OpCodes.Call, objCtor);
281
- ilg.Emit(OpCodes.Ret);
282
- }
283
- }
284
-
285
158
  // Shared by both loops below, keyed by "Name(Param1FullName,Param2FullName,...)" so a
286
159
  // member that's both an overridden base virtual and a requested interface member (e.g.
287
160
  // the base class already implements that interface) reuses one emitted body instead of
@@ -293,8 +166,12 @@ public static partial class Bridge
293
166
  // Override only the base virtuals JS actually asked for (memberSet). Anything not in
294
167
  // that set is simply never touched, so the base implementation stays live in the vtable —
295
168
  // no "call base" IL needed. (Skip ref/out and generic methods — unsupported.)
169
+ // Abstract members are always implemented (dispatching to JS, which reports a missing
170
+ // implementation as an error) — a type with an unimplemented abstract member can't be created.
296
171
  var virtualMethods = baseType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
297
- .Where(m => m.IsVirtual && !m.IsFinal && !m.IsGenericMethod && !m.IsConstructor && memberSet.Contains(m.Name))
172
+ .Where(m => m.IsVirtual && !m.IsFinal && !m.IsGenericMethod && !m.IsConstructor
173
+ && (m.IsPublic || m.IsFamily || m.IsFamilyOrAssembly)
174
+ && (memberSet.Contains(m.Name) || m.IsAbstract))
298
175
  .ToArray();
299
176
 
300
177
  foreach (var mi in virtualMethods)
@@ -310,6 +187,11 @@ public static partial class Bridge
310
187
  MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig,
311
188
  mi.CallingConvention, mi.ReturnType, paramTypes, mi.Name);
312
189
  definedSignatures[sigKey] = mb;
190
+
191
+ // `super.Name(...)` from JS: a public, non-virtual entry point to the base
192
+ // implementation (a plain call, so it can't dispatch back into the override).
193
+ if (!mi.IsAbstract)
194
+ EmitBaseCallMethod(tb, mi, paramTypes);
313
195
  }
314
196
 
315
197
  tb.DefineMethodOverride(mb, mi);
@@ -359,6 +241,21 @@ public static partial class Bridge
359
241
  return tb.CreateTypeInfo()!.AsType();
360
242
  }
361
243
 
244
+ internal const string BaseCallPrefix = "__ns_base_";
245
+ internal const string JsSelfMember = "__ns_js_self";
246
+
247
+ private static void EmitBaseCallMethod(TypeBuilder tb, MethodInfo baseMethod, Type[] paramTypes)
248
+ {
249
+ var mb = tb.DefineMethod(BaseCallPrefix + baseMethod.Name,
250
+ MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis,
251
+ baseMethod.ReturnType, paramTypes);
252
+ var il = mb.GetILGenerator();
253
+ il.Emit(OpCodes.Ldarg_0);
254
+ for (int i = 0; i < paramTypes.Length; i++) il.Emit(OpCodes.Ldarg, i + 1);
255
+ il.Emit(OpCodes.Call, baseMethod);
256
+ il.Emit(OpCodes.Ret);
257
+ }
258
+
362
259
  // Shared IL body for both base-virtual overrides and interface-member implementations: box
363
260
  // args into an object[], forward to ProxyRuntime.InvokeVoid/InvokeMethodTyped<T> by name.
364
261
  private static MethodBuilder EmitProxyMethodBody(
@@ -406,83 +303,106 @@ public static partial class Bridge
406
303
 
407
304
  private static DispatchResult CreateJsSubclass(
408
305
  string? assemblyName, string typeName, int callbackId, string[] interfaceNames, string[] memberNames)
409
- {
410
- EnsureProxyDispatcherCallbacksRegistered();
306
+ => CreateJsSubclass(assemblyName, typeName, callbackId, interfaceNames, memberNames, []);
411
307
 
412
- s_pendingProxyCallbackId.Value = callbackId;
413
-
414
- // Try to find a statically-generated proxy type first (Mechanism A: sbg-compiled into
415
- // the app itself — already has any requested interfaces baked into real C# source).
416
- Type? t = FindGeneratedProxyType(typeName);
417
- if (t is null)
308
+ // Creates an instance of a JS subclass: a dynamic subclass of the base type (or of System.Object
309
+ // when the "base" is an interface being implemented) whose overridden virtuals and interface
310
+ // members call the JS object registered under `callbackId`. `ctorArgs` select and feed the
311
+ // base constructor, as `super(...)` arguments do on Android/iOS.
312
+ private static DispatchResult CreateJsSubclass(
313
+ string? assemblyName, string typeName, int callbackId, string[] interfaceNames, string[] memberNames, object?[] ctorArgs)
314
+ {
315
+ // `typeName` is the base type; older runtimes passed an auto-generated proxy name there and
316
+ // the base type in `assemblyName`.
317
+ var baseType = ResolveType(null, typeName)
318
+ ?? (string.IsNullOrEmpty(assemblyName) ? null : ResolveType(null, assemblyName))
319
+ ?? throw new TypeLoadException($"Type not found: {typeName}");
320
+
321
+ var interfaces = interfaceNames.ToList();
322
+ if (baseType.IsInterface)
418
323
  {
419
- // When typeName is an auto-generated proxy name (com.tns.gen.winrt.*),
420
- // the caller puts the real base type name in assemblyName so we can
421
- // look up or dynamically emit a proxy for the correct base class.
422
- string? resolveFrom = typeName;
423
- if (!string.IsNullOrEmpty(assemblyName)
424
- && typeName != null
425
- && typeName.StartsWith("com.tns.gen.winrt.", StringComparison.Ordinal))
426
- {
427
- resolveFrom = assemblyName;
428
- }
324
+ interfaces.Insert(0, baseType.FullName!);
325
+ baseType = typeof(object);
326
+ }
327
+ if (baseType.IsSealed)
328
+ throw new InvalidOperationException($"{baseType.FullName} is sealed and can't be extended.");
429
329
 
430
- // Resolve the WinRT/base type and optionally emit a dynamic proxy (Mechanism B fallback).
431
- var baseType = ResolveType(null, resolveFrom)
432
- ?? ResolveType(assemblyName, typeName)
433
- ?? throw new TypeLoadException($"Type not found: {resolveFrom} (proxy: {typeName}, assembly: {assemblyName})");
330
+ var proxyType = GetOrCreateDynamicProxyType(baseType, interfaces.ToArray(), memberNames);
434
331
 
435
- if (baseType.IsClass && !baseType.IsSealed)
436
- {
437
- try { t = GetOrCreateDynamicProxyType(baseType, interfaceNames, memberNames); }
438
- catch (Exception) { t = baseType; }
439
- }
440
- else
332
+ // Pick the constructor by argument count, preferring one whose parameters the arguments
333
+ // convert to.
334
+ var ctors = proxyType.GetConstructors().Where(c => c.GetParameters().Length == ctorArgs.Length).ToArray();
335
+ if (ctors.Length == 0)
336
+ throw new MissingMethodException($"{baseType.FullName} has no constructor taking {ctorArgs.Length} argument(s).");
337
+ object? instance = null;
338
+ Exception? lastError = null;
339
+ s_pendingProxyCallbackId.Value = callbackId;
340
+ try
341
+ {
342
+ foreach (var ctor in ctors)
441
343
  {
442
- t = baseType;
344
+ object?[] built;
345
+ try { built = BuildArgsBinExact(ctorArgs, ctor.GetParameters()); }
346
+ catch (Exception e) { lastError = e; continue; }
347
+ if (!ArgsFit(built, ctor.GetParameters())) continue;
348
+ instance = ctor.Invoke(built);
349
+ break;
443
350
  }
351
+ if (instance is null)
352
+ throw lastError ?? new MissingMethodException(
353
+ $"No constructor of {baseType.FullName} accepts the given {ctorArgs.Length} argument(s).");
354
+ RegisterJsBacked(instance, callbackId);
355
+ }
356
+ catch (TargetInvocationException tie) when (tie.InnerException is not null)
357
+ {
358
+ throw tie.InnerException;
359
+ }
360
+ finally
361
+ {
362
+ s_pendingProxyCallbackId.Value = null;
444
363
  }
445
-
446
- // Create the managed instance. Generated classes should call
447
- // ProxyDispatcher.InitializeInstance(this, typeName) in their constructor,
448
- // which will invoke our ProxyInitializeInstance and capture the pending callback id.
449
- object? instance = Activator.CreateInstance(t);
450
- if (instance is null)
451
- throw new InvalidOperationException($"Failed to instantiate proxy type {t.FullName}.");
452
-
453
- // Ensure there's a mapping for this instance immediately to avoid any
454
- // early virtual calls from constructors reaching the JS side before
455
- // the handle is registered. Call our initializer directly to register
456
- // the pending callback id when dynamic proxies don't call it.
457
- try { ProxyInitializeInstance(instance, typeName); } catch { }
458
364
 
459
365
  // Force COM CCW vtable creation for any implemented WinRT interfaces now, rather than
460
366
  // relying on it happening implicitly the first time the instance crosses the ABI boundary.
461
- // Best-effort/reflection-only — no-ops cleanly when CsWinRT isn't loaded (e.g. xunit host).
462
- if (interfaceNames.Length > 0)
463
- {
464
- TryActivateWinRTInterfaces(instance);
465
- }
367
+ if (interfaces.Count > 0) TryActivateWinRTInterfaces(instance);
466
368
 
467
- // Box the instance into a handle to return to the runtime.
468
- var result = Box(instance);
369
+ return Box(instance);
370
+ }
469
371
 
470
- // Populate holder with handle id now that a handle exists.
471
- if (s_proxyCallbacks.TryGetValue(instance, out var holder))
472
- {
473
- try { holder.HandleId = result.HandleId(); } catch { holder.HandleId = 0; }
474
- }
475
- else
372
+ private static bool ArgsFit(object?[] built, ParameterInfo[] parameters)
373
+ {
374
+ for (int i = 0; i < parameters.Length; i++)
476
375
  {
477
- // If the generated proxy did not call InitializeInstance, create mapping now.
478
- int hid = 0;
479
- try { hid = result.HandleId(); } catch { hid = 0; }
480
- var newHolder = new ProxyCallbackHolder(callbackId) { HandleId = hid };
481
- s_proxyCallbacks.Add(instance, newHolder);
376
+ var p = parameters[i].ParameterType;
377
+ if (built[i] is null) { if (p.IsValueType && Nullable.GetUnderlyingType(p) is null) return false; continue; }
378
+ if (!p.IsInstanceOfType(built[i])) return false;
482
379
  }
380
+ return true;
381
+ }
483
382
 
484
- s_pendingProxyCallbackId.Value = null;
485
- return result;
383
+ private static void RegisterJsBacked(object instance, int callbackId)
384
+ {
385
+ if (!s_proxyCallbacks.TryGetValue(instance, out _))
386
+ s_proxyCallbacks.Add(instance, new ProxyCallbackHolder(callbackId));
387
+ }
388
+
389
+ internal static bool IsJsBacked(object instance) => s_proxyCallbacks.TryGetValue(instance, out _);
390
+
391
+ // The live handle of a JS-backed instance, or null when it has none (its JS object was collected
392
+ // and released the handle); Box then gives it a new one.
393
+ private static ProxyCallbackHolder? JsBackedHolder(object instance, out bool handleLive)
394
+ {
395
+ handleLive = false;
396
+ if (!s_proxyCallbacks.TryGetValue(instance, out var holder)) return null;
397
+ handleLive = holder.HandleId != 0
398
+ && s_handles.TryGetValue(holder.HandleId, out var current) && ReferenceEquals(current, instance);
399
+ return holder;
400
+ }
401
+
402
+ private static int EnsureJsHandle(object instance, ProxyCallbackHolder holder)
403
+ {
404
+ JsBackedHolder(instance, out var live);
405
+ return live ? holder.HandleId : Box(instance).HandleId();
486
406
  }
487
407
 
488
408
  // Locates CsWinRT's ComWrappersSupport via reflection (same style as the WinRT.IWinRTObject
@@ -529,45 +449,53 @@ public static partial class Bridge
529
449
  catch { /* best-effort only */ }
530
450
  }
531
451
 
532
- private static void ProxyInitializeInstance(object instance, string typeName)
452
+ // The holder for a JS-backed instance. A virtual the base constructor calls runs before
453
+ // CreateJsSubclass has registered the instance, so fall back to the pending callback id.
454
+ private static ProxyCallbackHolder JsHolderFor(object instance)
533
455
  {
534
- var cb = s_pendingProxyCallbackId.Value;
535
- if (cb.HasValue)
456
+ if (s_proxyCallbacks.TryGetValue(instance, out var holder)) return holder;
457
+ var pending = s_pendingProxyCallbackId.Value;
458
+ if (pending.HasValue)
536
459
  {
537
- var holder = new ProxyCallbackHolder(cb.Value);
538
- s_proxyCallbacks.Add(instance, holder);
460
+ RegisterJsBacked(instance, pending.Value);
461
+ if (s_proxyCallbacks.TryGetValue(instance, out holder)) return holder;
539
462
  }
463
+ throw new InvalidOperationException("No JS callback registered for proxy instance.");
464
+ }
465
+
466
+ // Payload for the JS dispatcher: (self handle, member name, ...args). The arguments are sent
467
+ // individually so each arrives as its JS value (numbers, strings, structs as plain objects,
468
+ // objects as handles).
469
+ private static object?[] DispatchPayload(object instance, ProxyCallbackHolder holder, string memberName, object?[] args)
470
+ {
471
+ var payload = new object?[args.Length + 2];
472
+ payload[0] = new HandleRef(EnsureJsHandle(instance, holder));
473
+ payload[1] = memberName;
474
+ Array.Copy(args, 0, payload, 2, args.Length);
475
+ return payload;
540
476
  }
541
477
 
542
478
  private static object? ProxyInvokeMethod(object instance, string methodName, object[] args)
543
479
  {
544
- if (!s_proxyCallbacks.TryGetValue(instance, out var holder)) throw new InvalidOperationException("No JS callback registered for proxy instance.");
545
- var payload = new object?[] { new HandleRef(holder.HandleId), methodName, args };
546
- return CallJsCallback(holder.CallbackId, payload);
480
+ var holder = JsHolderFor(instance);
481
+ return CallJsCallback(holder.CallbackId, DispatchPayload(instance, holder, methodName, args), expectsResult: true);
547
482
  }
548
483
 
549
484
  private static void ProxyInvokeVoid(object instance, string methodName, object[] args)
550
485
  {
551
- if (!s_proxyCallbacks.TryGetValue(instance, out var holder)) throw new InvalidOperationException("No JS callback registered for proxy instance.");
552
-
553
- var payload = new object?[] { new HandleRef(holder.HandleId), methodName, args };
554
- CallJsCallback(holder.CallbackId, payload);
486
+ var holder = JsHolderFor(instance);
487
+ CallJsCallback(holder.CallbackId, DispatchPayload(instance, holder, methodName, args), expectsResult: false);
555
488
  }
556
489
 
557
490
  private static object? ProxyGetProperty(object instance, string propertyName)
558
491
  {
559
- if (!s_proxyCallbacks.TryGetValue(instance, out var holder)) throw new InvalidOperationException("No JS callback registered for proxy instance.");
560
- // Tag "get:" prefix so the JS dispatcher can distinguish getter from method call.
561
- var payload = new object?[] { new HandleRef(holder.HandleId), "get:" + propertyName };
562
- return CallJsCallback(holder.CallbackId, payload);
492
+ var holder = JsHolderFor(instance);
493
+ return CallJsCallback(holder.CallbackId, DispatchPayload(instance, holder, "get_" + propertyName, []), expectsResult: true);
563
494
  }
564
495
 
565
496
  private static void ProxySetProperty(object instance, string propertyName, object? value)
566
497
  {
567
- if (!s_proxyCallbacks.TryGetValue(instance, out var holder)) throw new InvalidOperationException("No JS callback registered for proxy instance.");
568
- // Tag "set:" prefix so the JS dispatcher can distinguish setter from method call.
569
- var payload = new object?[] { new HandleRef(holder.HandleId), "set:" + propertyName, value };
570
- CallJsCallback(holder.CallbackId, payload);
498
+ var holder = JsHolderFor(instance);
499
+ CallJsCallback(holder.CallbackId, DispatchPayload(instance, holder, "set_" + propertyName, [value]), expectsResult: false);
571
500
  }
572
501
  }
573
-
@@ -22,9 +22,10 @@ public static partial class Bridge
22
22
  $"Object of type {obj.GetType().FullName} is not awaitable. " +
23
23
  $"Expected Task<T>, ValueTask<T>, IAsyncOperation<T>, or any type implementing GetAwaiter().");
24
24
 
25
+ // The handle stays valid after completion (the JS proxy releases it when collected), so
26
+ // the same Task can be awaited again.
25
27
  task.ContinueWith(completed =>
26
28
  {
27
- s_handles.TryRemove(handleId, out _);
28
29
  try
29
30
  {
30
31
  if (completed.IsFaulted)
@@ -115,7 +115,7 @@ public static partial class Bridge
115
115
  var simple = Path.GetFileNameWithoutExtension(file);
116
116
  if (string.IsNullOrEmpty(simple)) continue;
117
117
 
118
- Assembly asm = AppDomain.CurrentDomain.GetAssemblies()
118
+ Assembly? asm = AppDomain.CurrentDomain.GetAssemblies()
119
119
  .FirstOrDefault(a => string.Equals(a.GetName().Name, simple, StringComparison.OrdinalIgnoreCase));
120
120
  if (asm is null)
121
121
  {
@@ -123,8 +123,12 @@ public static partial class Bridge
123
123
  catch { continue; }
124
124
  }
125
125
 
126
+ // The app's own assembly (C# sources compiled into the app) contributes
127
+ // its internal types too: they are reachable from JS (type resolution
128
+ // finds non-public types), so their namespaces must be as well.
126
129
  Type[] types;
127
- try { types = asm.GetExportedTypes(); }
130
+ try { types = asm == Assembly.GetEntryAssembly() ? asm.GetTypes() : asm.GetExportedTypes(); }
131
+ catch (ReflectionTypeLoadException e) { types = e.Types.Where(t => t != null).ToArray()!; }
128
132
  catch { types = Array.Empty<Type>(); }
129
133
 
130
134
  var assemblyName = asm.GetName().Name;
@@ -132,7 +136,7 @@ public static partial class Bridge
132
136
 
133
137
  foreach (var t in types)
134
138
  {
135
- if (string.IsNullOrEmpty(t.Namespace)) continue;
139
+ if (string.IsNullOrEmpty(t.Namespace) || t.Name.StartsWith('<')) continue;
136
140
  map[t.Namespace] = assemblyName;
137
141
  var root = t.Namespace.Split('.')[0];
138
142
  if (!map.ContainsKey(root)) map[root] = assemblyName;
@@ -540,7 +544,7 @@ public static partial class Bridge
540
544
  {
541
545
  var handlerType = ev.EventHandlerType;
542
546
  var method = typeof(Bridge).GetMethod(nameof(CoreApplicationUnhandledErrorHandler), BindingFlags.NonPublic | BindingFlags.Static);
543
- if (method != null)
547
+ if (handlerType != null && method != null)
544
548
  {
545
549
  var del = Delegate.CreateDelegate(handlerType, method);
546
550
  ev.AddEventHandler(null, del);
@@ -597,6 +601,12 @@ public static partial class Bridge
597
601
  // WinRT interfaces (e.g. IUIElement for a FlexboxLayout subclass).
598
602
  private static IntPtr ObtainNativePtr(object obj)
599
603
  {
604
+ // Path 0 — a JS subclass of a WinRT class: the composed object's outer (its C#/WinRT CCW).
605
+ // XAML holds and hands back the outer, so using it here lets the runtime map those objects
606
+ // back to the JS instance. The base class's interfaces resolve through the inner.
607
+ if (IsJsBacked(obj) && TryGetOuterInspectable(obj) is { } outer && outer != IntPtr.Zero)
608
+ return outer;
609
+
600
610
  // Path 1 — C#/WinRT IWinRTObject: use the projected inner object's pointer.
601
611
  // This gives the real native WinRT pointer, not the managed CCW, so
602
612
  // QueryInterface will succeed for all WinRT interfaces inherited by the type.
@@ -633,7 +643,7 @@ public static partial class Bridge
633
643
  try
634
644
  {
635
645
  var iidLocal = s_iidIInspectable;
636
- var hr = Marshal.QueryInterface(iunknown, ref iidLocal, out var inspectable);
646
+ var hr = Marshal.QueryInterface(iunknown, in iidLocal, out var inspectable);
637
647
  if (hr == 0 && inspectable != IntPtr.Zero)
638
648
  {
639
649
  Marshal.Release(iunknown);
@@ -646,6 +656,36 @@ public static partial class Bridge
646
656
  return iunknown;
647
657
  }
648
658
 
659
+ private static MethodInfo? s_marshalInspectableFromManaged;
660
+
661
+ // WinRT.MarshalInspectable<object>.FromManaged(obj), found by reflection (the bridge has no
662
+ // compile-time reference to C#/WinRT): an AddRef'd IInspectable of the object's CCW.
663
+ private static IntPtr? TryGetOuterInspectable(object obj)
664
+ {
665
+ if (obj.GetType().GetInterface("WinRT.IWinRTObject") is null) return null;
666
+ try
667
+ {
668
+ if (s_marshalInspectableFromManaged is null)
669
+ {
670
+ var open = AppDomain.CurrentDomain.GetAssemblies()
671
+ .Select(a => a.GetType("WinRT.MarshalInspectable`1"))
672
+ .FirstOrDefault(t => t is not null);
673
+ s_marshalInspectableFromManaged = open?.MakeGenericType(typeof(object))
674
+ .GetMethods(BindingFlags.Public | BindingFlags.Static)
675
+ .FirstOrDefault(m => m.Name == "FromManaged" && m.GetParameters() is { Length: > 0 } ps
676
+ && ps[0].ParameterType == typeof(object) && ps.Skip(1).All(p => p.IsOptional));
677
+ }
678
+ var method = s_marshalInspectableFromManaged;
679
+ if (method is null) return null;
680
+ var args = method.GetParameters().Select((p, i) => i == 0 ? obj : p.DefaultValue).ToArray();
681
+ return method.Invoke(null, args) as IntPtr?;
682
+ }
683
+ catch
684
+ {
685
+ return null;
686
+ }
687
+ }
688
+
649
689
  private static void OnAppDomainUnhandledException(object? sender, UnhandledExceptionEventArgs e)
650
690
  {
651
691
  try
@@ -16,6 +16,14 @@
16
16
  host process is already running on net10. LatestMajor accepts any version >= 9. -->
17
17
  <RollForward>LatestMajor</RollForward>
18
18
  </PropertyGroup>
19
+ <ItemGroup>
20
+ <!-- The bridge only runs inside a Windows host, but the TFM stays plain net9.0 so the
21
+ net9.0 test/benchmark projects can reference it. Declaring the platform here keeps
22
+ CA1416 quiet for the Marshal COM APIs. Skipped when an OS-specific TFM already emits it. -->
23
+ <AssemblyAttribute Include="System.Runtime.Versioning.SupportedOSPlatformAttribute" Condition="'$(TargetPlatformIdentifier)' == ''">
24
+ <_Parameter1>windows</_Parameter1>
25
+ </AssemblyAttribute>
26
+ </ItemGroup>
19
27
  <Target Name="WriteDotNetToolDone" AfterTargets="Publish">
20
28
  <PropertyGroup>
21
29
  <DotNetToolDoneFile>$(MSBuildProjectDirectory)\publish\.dotnet_tool_done</DotNetToolDoneFile>
Binary file
Binary file
Binary file