@nativescript/windows-quickjs 0.1.0-next.2026-08-05-31006577517 → 1.0.0-beta.10

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 +107 -17
  4. package/framework/__PROJECT_NAME__/__PROJECT_NAME__.csproj +29 -40
  5. package/framework/dotnet-bridge/BinaryProtocol.cs +18 -0
  6. package/framework/dotnet-bridge/Bridge.BinaryDispatch.cs +75 -8
  7. package/framework/dotnet-bridge/Bridge.Dispatch.cs +36 -35
  8. package/framework/dotnet-bridge/Bridge.JsDelegate.cs +115 -59
  9. package/framework/dotnet-bridge/Bridge.Proxy.cs +141 -86
  10. package/framework/dotnet-bridge/Bridge.TaskHelper.cs +2 -1
  11. package/framework/dotnet-bridge/Bridge.cs +9 -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
@@ -115,7 +115,7 @@ public static partial class Bridge
115
115
  var built = BuildArgs(args, parameters);
116
116
  try
117
117
  {
118
- var res = AwaitIfTask(m.Invoke(target, built));
118
+ var res = (m.Invoke(target, built));
119
119
  return Box(res);
120
120
  }
121
121
  catch (TargetInvocationException tie) when (IsMarshaledForDifferentThread(tie.InnerException))
@@ -123,7 +123,7 @@ public static partial class Bridge
123
123
  if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected wrong-thread COM error; retrying {type.FullName}.{m.Name} on UI thread");
124
124
  try
125
125
  {
126
- var res = InvokeOnUIThread(() => AwaitIfTask(m.Invoke(target, built)));
126
+ var res = InvokeOnUIThread(() => (m.Invoke(target, built)));
127
127
  return Box(res);
128
128
  }
129
129
  catch { /* retry failed — try next candidate */ }
@@ -133,7 +133,7 @@ public static partial class Bridge
133
133
  if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected COMException wrong-thread; retrying {type.FullName}.{m.Name} on UI thread");
134
134
  try
135
135
  {
136
- var res = InvokeOnUIThread(() => AwaitIfTask(m.Invoke(target, built)));
136
+ var res = InvokeOnUIThread(() => (m.Invoke(target, built)));
137
137
  return Box(res);
138
138
  }
139
139
  catch { /* retry failed — try next candidate */ }
@@ -148,19 +148,19 @@ public static partial class Bridge
148
148
  try {
149
149
  try
150
150
  {
151
- var res = AwaitIfTask(dispEntry.Invoke(target, builtArgs));
151
+ var res = (dispEntry.Invoke(target, builtArgs));
152
152
  return Box(res);
153
153
  }
154
154
  catch (TargetInvocationException tie) when (IsMarshaledForDifferentThread(tie.InnerException))
155
155
  {
156
156
  if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected wrong-thread COM error; retrying {type.FullName}.{method} on UI thread");
157
- var res = InvokeOnUIThread(() => AwaitIfTask(dispEntry.Invoke(target, builtArgs)));
157
+ var res = InvokeOnUIThread(() => (dispEntry.Invoke(target, builtArgs)));
158
158
  return Box(res);
159
159
  }
160
160
  catch (System.Runtime.InteropServices.COMException ce) when (IsMarshaledForDifferentThread(ce))
161
161
  {
162
162
  if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected COMException wrong-thread; retrying {type.FullName}.{method} on UI thread");
163
- var res = InvokeOnUIThread(() => AwaitIfTask(dispEntry.Invoke(target, builtArgs)));
163
+ var res = InvokeOnUIThread(() => (dispEntry.Invoke(target, builtArgs)));
164
164
  return Box(res);
165
165
  }
166
166
  }
@@ -263,34 +263,6 @@ public static partial class Bridge
263
263
  return el.Deserialize(targetType, s_coerceOpts);
264
264
  }
265
265
 
266
- private static object? AwaitIfTask(object? value)
267
- {
268
- if (value is null) return null;
269
-
270
- if (value is Task task)
271
- {
272
- task.GetAwaiter().GetResult();
273
- return TaskResultCache.GetResult(task);
274
- }
275
-
276
- if (value is ValueTask vt)
277
- {
278
- vt.AsTask().GetAwaiter().GetResult();
279
- return null;
280
- }
281
-
282
- var type = value.GetType();
283
- if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ValueTask<>))
284
- {
285
- var innerTask = ValueTaskAsTaskCache.AsTask(type, value);
286
- innerTask.GetAwaiter().GetResult();
287
- if (innerTask.IsFaulted) throw innerTask.Exception!.InnerException ?? innerTask.Exception;
288
- return TaskResultCache.GetResult(innerTask);
289
- }
290
-
291
- return value;
292
- }
293
-
294
266
  private static DispatchResult Box(object? value)
295
267
  {
296
268
  if (value is null) return DispatchResult.Void;
@@ -321,6 +293,11 @@ public static partial class Bridge
321
293
  return DispatchResult.Primitive(Convert.ChangeType(value, ut), ut);
322
294
  }
323
295
 
296
+ // An instance of a JS subclass goes back to JS as the handle its JS object was created
297
+ // with, so the runtime hands out that same JS object (identity, fields, overrides).
298
+ if (TryGetJsBackedHandle(value, out var jsHandle))
299
+ return DispatchResult.Handle(jsHandle, t.FullName ?? t.Name);
300
+
324
301
 
325
302
 
326
303
  var id = Interlocked.Increment(ref s_nextHandle);
@@ -351,7 +328,7 @@ public static partial class Bridge
351
328
  : DispatchResult.Handle(id, typeName);
352
329
  }
353
330
 
354
- private static bool IsAwaitable(object value, Type t)
331
+ private static bool IsAwaitable(object? value, Type t)
355
332
  {
356
333
  if (value is Task || value is ValueTask) return true;
357
334
  if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ValueTask<>)) return true;
@@ -363,6 +340,30 @@ public static partial class Bridge
363
340
  null, Type.EmptyTypes, null) is not null;
364
341
  }
365
342
 
343
+ /// "interface", "abstract", "sealed", "class", "struct", "enum", "delegate" or "" (not found).
344
+ /// Lets JS decide between `new Interface({...})`, subclassing and plain construction.
345
+ public static string TypeKind(string typeName)
346
+ {
347
+ var t = ResolveType(null, typeName);
348
+ if (t is null) return "";
349
+ if (t.IsInterface) return "interface";
350
+ if (t.IsEnum) return "enum";
351
+ if (typeof(Delegate).IsAssignableFrom(t)) return "delegate";
352
+ if (t.IsValueType) return "struct";
353
+ if (t.IsAbstract && t.IsSealed) return "static";
354
+ if (t.IsAbstract) return "abstract";
355
+ if (t.IsSealed) return "sealed";
356
+ return "class";
357
+ }
358
+
359
+ /// `value instanceof SomeType` for a .NET object that was not constructed from JS.
360
+ public static bool IsInstanceOf(object? value, string typeName)
361
+ {
362
+ if (value is null) return false;
363
+ var t = ResolveType(null, typeName);
364
+ return t is not null && t.IsInstanceOfType(value);
365
+ }
366
+
366
367
  internal static DispatchResult BuildMembersResult(Type t)
367
368
  {
368
369
  const BindingFlags inst = BindingFlags.Public | BindingFlags.Instance;
@@ -12,91 +12,129 @@ namespace NativeScriptBridge;
12
12
  public static partial class Bridge
13
13
  {
14
14
  // opcode 0x09: given a delegate type name (or "" for System.Action) and a
15
- // JS callback id, compile a .NET delegate that serialises its parameters as
16
- // binary and calls back into V8 via the s_jsInvoker function pointer.
17
-
15
+ // JS callback id, create a .NET delegate that calls back into V8.
18
16
  private static DispatchResult CreateJsDelegate(string typeName, int callbackId)
19
17
  {
20
18
  var delegateType = string.IsNullOrEmpty(typeName)
21
19
  ? typeof(Action)
22
20
  : ResolveType(null, typeName)
23
21
  ?? throw new TypeLoadException($"Delegate type not found: {typeName}");
22
+ return Box(MakeJsDelegate(delegateType, callbackId));
23
+ }
24
24
 
25
- var invokeMethod = delegateType.GetMethod("Invoke")
26
- ?? throw new MissingMethodException($"No Invoke method on {delegateType}");
25
+ // The target a JS-backed delegate is bound to. When the delegate is collected the finalizer
26
+ // tells the runtime, which then drops its reference to the JS function.
27
+ internal sealed class JsCallbackTarget(int callbackId)
28
+ {
29
+ public readonly int CallbackId = callbackId;
30
+
31
+ public object? Invoke(object?[] args) => CallJsCallback(CallbackId, args, expectsResult: true);
32
+
33
+ public void InvokeVoid(object?[] args) => CallJsCallback(CallbackId, args, expectsResult: false);
34
+
35
+ ~JsCallbackTarget()
36
+ {
37
+ ReleaseJsCallback(CallbackId);
38
+ }
39
+ }
27
40
 
28
- var parameters = invokeMethod.GetParameters();
29
- var returnType = invokeMethod.ReturnType;
41
+ // Function pointer registered by the runtime (RegisterJsCallbackRelease) to drop a JS function
42
+ // whose delegate was collected. Called from the finalizer thread; the runtime queues the id.
43
+ internal static unsafe delegate* unmanaged[Cdecl]<int, void> s_jsCallbackRelease;
30
44
 
31
- // Build a dynamic method that marshals parameters into an object[] and
32
- // calls back into JS via CallJsCallback/CallJsCallbackVoid. Expression
33
- // compilation occasionally generates incorrect code for some delegate
34
- // shapes; emitting IL here is reliable across signatures.
35
- var paramTypes = parameters.Select(p => p.ParameterType).ToArray();
36
-
37
- var dm = new DynamicMethod($"__ns_js_delegate_{callbackId}",
38
- returnType, paramTypes, typeof(Bridge).Module, skipVisibility: true);
45
+ [UnmanagedCallersOnly(EntryPoint = "RegisterJsCallbackRelease",
46
+ CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
47
+ public static unsafe int RegisterJsCallbackRelease(delegate* unmanaged[Cdecl]<int, void> release)
48
+ {
49
+ s_jsCallbackRelease = release;
50
+ return 0;
51
+ }
52
+
53
+ internal static unsafe void ReleaseJsCallback(int callbackId)
54
+ {
55
+ var release = s_jsCallbackRelease;
56
+ if (release == null) return;
57
+ try { release(callbackId); } catch { }
58
+ }
59
+
60
+ // One invoker per delegate type: (JsCallbackTarget target, <delegate params>) -> <delegate return>.
61
+ // It packs the arguments into object[] and calls target.Invoke/InvokeVoid; a delegate instance is
62
+ // that invoker closed over its target, so creating a delegate emits no code.
63
+ private static readonly System.Collections.Concurrent.ConcurrentDictionary<Type, DynamicMethod> s_jsDelegateInvokers = new();
39
64
 
65
+ internal static Delegate MakeJsDelegate(Type delegateType, int callbackId)
66
+ {
67
+ var invoker = s_jsDelegateInvokers.GetOrAdd(delegateType, BuildJsDelegateInvoker);
68
+ return invoker.CreateDelegate(delegateType, new JsCallbackTarget(callbackId));
69
+ }
70
+
71
+ private static DynamicMethod BuildJsDelegateInvoker(Type delegateType)
72
+ {
73
+ var invokeMethod = delegateType.GetMethod("Invoke")
74
+ ?? throw new MissingMethodException($"No Invoke method on {delegateType}");
75
+ var paramTypes = invokeMethod.GetParameters().Select(p => p.ParameterType).ToArray();
76
+ var returnType = invokeMethod.ReturnType;
77
+
78
+ // Emitting IL (rather than compiling an expression tree) is reliable across delegate shapes.
79
+ var dm = new DynamicMethod($"__ns_js_delegate_{delegateType.Name}", returnType,
80
+ [typeof(JsCallbackTarget), .. paramTypes], typeof(Bridge).Module, skipVisibility: true);
40
81
  var il = dm.GetILGenerator();
41
- // local: object[] argsArray
42
- var argsLocal = il.DeclareLocal(typeof(object[]));
82
+
83
+ il.Emit(OpCodes.Ldarg_0);
43
84
  il.Emit(OpCodes.Ldc_I4, paramTypes.Length);
44
85
  il.Emit(OpCodes.Newarr, typeof(object));
45
- il.Emit(OpCodes.Stloc, argsLocal);
46
-
47
86
  for (int i = 0; i < paramTypes.Length; i++)
48
87
  {
49
- il.Emit(OpCodes.Ldloc, argsLocal);
88
+ var paramType = paramTypes[i].IsByRef ? paramTypes[i].GetElementType()! : paramTypes[i];
89
+ il.Emit(OpCodes.Dup);
50
90
  il.Emit(OpCodes.Ldc_I4, i);
51
- // load argument (Ldarg_0..)
52
- switch (i + 1)
53
- {
54
- case 1: il.Emit(OpCodes.Ldarg_0); break;
55
- case 2: il.Emit(OpCodes.Ldarg_1); break;
56
- case 3: il.Emit(OpCodes.Ldarg_2); break;
57
- case 4: il.Emit(OpCodes.Ldarg_3); break;
58
- default: il.Emit(OpCodes.Ldarg, i + 1); break;
59
- }
60
- if (paramTypes[i].IsValueType) il.Emit(OpCodes.Box, paramTypes[i]);
91
+ il.Emit(OpCodes.Ldarg, i + 1);
92
+ if (paramTypes[i].IsByRef) il.Emit(OpCodes.Ldobj, paramType);
93
+ if (paramType.IsValueType) il.Emit(OpCodes.Box, paramType);
61
94
  il.Emit(OpCodes.Stelem_Ref);
62
95
  }
63
96
 
64
-
65
-
66
97
  if (returnType == typeof(void))
67
98
  {
68
- var callVoid = typeof(Bridge).GetMethod(nameof(CallJsCallbackVoid), BindingFlags.Static | BindingFlags.NonPublic)!;
69
- il.Emit(OpCodes.Ldc_I4, callbackId);
70
- il.Emit(OpCodes.Ldloc, argsLocal);
71
- il.Emit(OpCodes.Call, callVoid);
72
- il.Emit(OpCodes.Ret);
99
+ il.Emit(OpCodes.Call, typeof(JsCallbackTarget).GetMethod(nameof(JsCallbackTarget.InvokeVoid))!);
73
100
  }
74
101
  else
75
102
  {
76
- var callObj = typeof(Bridge).GetMethod(nameof(CallJsCallback), BindingFlags.Static | BindingFlags.NonPublic)!;
77
- il.Emit(OpCodes.Ldc_I4, callbackId);
78
- il.Emit(OpCodes.Ldloc, argsLocal);
79
- il.Emit(OpCodes.Call, callObj);
80
- // ignore returned object and return default(returnType)
81
- if (returnType.IsValueType)
82
- {
83
- var loc = il.DeclareLocal(returnType);
84
- il.Emit(OpCodes.Ldloca_S, loc);
85
- il.Emit(OpCodes.Initobj, returnType);
86
- il.Emit(OpCodes.Ldloc, loc);
87
- }
88
- else
89
- {
90
- il.Emit(OpCodes.Ldnull);
91
- }
92
- il.Emit(OpCodes.Ret);
103
+ il.Emit(OpCodes.Call, typeof(JsCallbackTarget).GetMethod(nameof(JsCallbackTarget.Invoke))!);
104
+ il.Emit(OpCodes.Ldtoken, returnType);
105
+ il.Emit(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle))!);
106
+ il.Emit(OpCodes.Call, typeof(Bridge).GetMethod(nameof(ConvertJsResult), BindingFlags.Static | BindingFlags.NonPublic)!);
107
+ il.Emit(OpCodes.Unbox_Any, returnType);
93
108
  }
109
+ il.Emit(OpCodes.Ret);
110
+ return dm;
111
+ }
94
112
 
95
- var del = dm.CreateDelegate(delegateType);
96
- return Box(del);
113
+ // A JS callback's result, converted to the type the managed caller expects (a delegate's return
114
+ // type or an overridden member's).
115
+ internal static object? ConvertJsResult(object? value, Type returnType)
116
+ {
117
+ if (value is null)
118
+ return returnType.IsValueType && Nullable.GetUnderlyingType(returnType) is null
119
+ ? Activator.CreateInstance(returnType)
120
+ : null;
121
+ var coerced = CoerceBin(value, returnType);
122
+ if (coerced is null || returnType.IsInstanceOfType(coerced)) return coerced;
123
+ var underlying = Nullable.GetUnderlyingType(returnType) ?? returnType;
124
+ try { return Convert.ChangeType(coerced, underlying); }
125
+ catch (Exception e)
126
+ {
127
+ throw new InvalidCastException(
128
+ $"JavaScript returned {coerced.GetType().Name}, which can't be converted to {returnType.FullName}", e);
129
+ }
97
130
  }
98
131
 
99
- internal static unsafe object? CallJsCallback(int id, object?[] args)
132
+ internal static object? CallJsCallback(int id, object?[] args) => CallJsCallback(id, args, expectsResult: true);
133
+
134
+ // Calls the JS function registered under `id`. When it throws, a caller that expects a result
135
+ // gets a JsException (a delegate with a return value, an overridden member); a void delegate or
136
+ // event just returns, the error having been reported as an uncaught JS error.
137
+ internal static unsafe object? CallJsCallback(int id, object?[] args, bool expectsResult)
100
138
  {
101
139
  if (s_jsInvoker == null) return null;
102
140
 
@@ -116,16 +154,21 @@ public static partial class Bridge
116
154
  // Response is only set for non-void delegates; parse and free when present.
117
155
  if (respPtr != null && respLen > 0)
118
156
  {
157
+ string? jsError = null;
119
158
  try
120
159
  {
121
160
  var span = new ReadOnlySpan<byte>(respPtr, respLen);
122
- result = ParseCallbackResponse(span);
161
+ if (span[0] == 0x0F)
162
+ jsError = span.Length > 5 ? new BinReader(span[1..]).ReadString32() : "the JavaScript callback could not run";
163
+ else
164
+ result = ParseCallbackResponse(span);
123
165
  }
124
166
  catch { result = null; }
125
167
  finally
126
168
  {
127
169
  Marshal.FreeHGlobal((IntPtr)respPtr);
128
170
  }
171
+ if (jsError != null && expectsResult) throw new JsException(jsError);
129
172
  }
130
173
 
131
174
  return result;
@@ -176,6 +219,15 @@ public static partial class Bridge
176
219
  if (arg is float f) { w.WriteByte(0x04); w.WriteF64((double)f); return; }
177
220
  if (arg is double d){ w.WriteByte(0x04); w.WriteF64(d); return; }
178
221
  if (arg is string s){ w.WriteByte(0x05); w.WriteString32(s); return; }
222
+ if (arg is Enum e) { w.WriteByte(0x04); w.WriteF64(Convert.ToDouble(e)); return; }
223
+ if (arg is decimal m){ w.WriteByte(0x04); w.WriteF64((double)m); return; }
224
+ // A struct (Windows.Foundation.Size, a C# record struct, ...) arrives as a plain JS object.
225
+ if (arg.GetType().IsValueType && !arg.GetType().IsPrimitive)
226
+ {
227
+ string? json = null;
228
+ try { json = System.Text.Json.JsonSerializer.Serialize(arg, arg.GetType(), s_jsJsonOptions); } catch { }
229
+ if (json != null) { w.WriteByte(0x0D); w.WriteString32(json); return; }
230
+ }
179
231
 
180
232
  // Object: box in the handle map and send as a handle reference.
181
233
  // The JS side receives {__handle, __type} which can be turned into a
@@ -209,6 +261,7 @@ public static partial class Bridge
209
261
  case 0x05: return (object)r.ReadString32();
210
262
  case 0x06: return (object)new HandleRef(r.ReadI32());
211
263
  case 0x0A: return (object)new WinRtRef(r.ReadI64());
264
+ case 0x0D: return new JsJsonValue(r.ReadString32());
212
265
  case 0x07: // array: u32 count + N tagged items
213
266
  {
214
267
  var count = (int)r.ReadU32();
@@ -237,8 +290,11 @@ public static partial class Bridge
237
290
 
238
291
  internal static unsafe void CallJsCallbackVoid(int id, object?[] args)
239
292
  {
240
- CallJsCallback(id, args);
293
+ CallJsCallback(id, args, expectsResult: false);
241
294
  }
242
295
 
243
296
 
244
297
  }
298
+
299
+ /// Thrown into managed code when a JavaScript callback that was expected to return a value threw.
300
+ public sealed class JsException(string message) : Exception(message);