@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.
- package/framework/__PROJECT_NAME__/App.xaml.cs +3 -2
- package/framework/__PROJECT_NAME__/CrashDiagnostics.cs +3 -3
- package/framework/__PROJECT_NAME__/RuntimeHost.cs +149 -24
- package/framework/__PROJECT_NAME__/__PROJECT_NAME__.csproj +35 -41
- package/framework/dotnet-bridge/BinaryProtocol.cs +18 -0
- package/framework/dotnet-bridge/Bridge.BinaryDispatch.cs +83 -8
- package/framework/dotnet-bridge/Bridge.Dispatch.cs +40 -35
- package/framework/dotnet-bridge/Bridge.JsDelegate.cs +115 -59
- package/framework/dotnet-bridge/Bridge.Proxy.cs +158 -230
- package/framework/dotnet-bridge/Bridge.TaskHelper.cs +2 -1
- package/framework/dotnet-bridge/Bridge.cs +45 -5
- package/framework/dotnet-bridge/DotNetBridge.csproj +8 -0
- package/framework/libs/x64/nativescript.dll +0 -0
- package/framework/tools/ManifestMerger/ManifestMerger.dll +0 -0
- package/framework/tools/ManifestMerger/ManifestMerger.pdb +0 -0
- package/framework/tools/dotnet-tool-x64.exe +0 -0
- package/framework/tools/dotnet-tool.exe +0 -0
- package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.dll +0 -0
- package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.exe +0 -0
- package/framework/tools/dotnet-typings-gen/dotnet-typings-gen.pdb +0 -0
- package/framework/tools/nsbundle_pack-x64.exe +0 -0
- package/framework/tools/nsbundle_pack.exe +0 -0
- package/framework/tools/typings-generator-x64.exe +0 -0
- package/framework/tools/typings-generator.exe +0 -0
- package/package.json +1 -1
- package/framework/tools/sbg-arm64.exe +0 -0
- package/framework/tools/sbg-x64.exe +0 -0
- package/framework/tools/sbg.exe +0 -0
|
@@ -92,6 +92,14 @@ public static partial class Bridge
|
|
|
92
92
|
return DispatchResult.Void;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
// A JS subclass instance whose JS object was collected: its dispatcher makes a new one
|
|
96
|
+
// for this handle.
|
|
97
|
+
if (method == JsSelfMember && target is not null && s_proxyCallbacks.TryGetValue(target, out var jsHolder))
|
|
98
|
+
{
|
|
99
|
+
CallJsCallback(jsHolder.CallbackId, [new HandleRef(handle), JsSelfMember], expectsResult: false);
|
|
100
|
+
return DispatchResult.Void;
|
|
101
|
+
}
|
|
102
|
+
|
|
95
103
|
return DispatchCallBin(target, type, method, args, isStatic: false);
|
|
96
104
|
}
|
|
97
105
|
|
|
@@ -116,7 +124,8 @@ public static partial class Bridge
|
|
|
116
124
|
for (int i = 0; i < memberCount; i++) memberNames[i] = r.ReadString16();
|
|
117
125
|
|
|
118
126
|
var callbackId = r.ReadI32();
|
|
119
|
-
|
|
127
|
+
var ctorArgs = r.HasMore ? r.ReadArgs() : [];
|
|
128
|
+
return CreateJsSubclass(NullIfEmpty(assembly), typeName, callbackId, interfaceNames, memberNames, ctorArgs);
|
|
120
129
|
}
|
|
121
130
|
|
|
122
131
|
if (op == 0x0B) // get CLR-only property by raw IInspectable ptr (CLR reflection fallback)
|
|
@@ -176,7 +185,35 @@ public static partial class Bridge
|
|
|
176
185
|
}
|
|
177
186
|
}
|
|
178
187
|
|
|
188
|
+
// Overloads with the same parameter count (Describe(Animal) / Describe(Shape)): pick the
|
|
189
|
+
// first whose parameter types the arguments convert to.
|
|
190
|
+
var overloads = GetOverloads(type, method, args.Length, flags);
|
|
191
|
+
if (overloads.Length > 1)
|
|
192
|
+
{
|
|
193
|
+
foreach (var overload in overloads)
|
|
194
|
+
{
|
|
195
|
+
var ps = overload.GetParameters();
|
|
196
|
+
object?[] built;
|
|
197
|
+
try { built = BuildArgsBinExact(args, ps); }
|
|
198
|
+
catch { continue; }
|
|
199
|
+
if (!ArgsFit(built, ps)) continue;
|
|
200
|
+
return Box(overload.Invoke(target, built));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
179
204
|
var entry = GetCachedMethod(type, method, args.Length, flags);
|
|
205
|
+
if (entry.Invoke is null && target is not null && IsJsBacked(target))
|
|
206
|
+
{
|
|
207
|
+
// A JS subclass may call the protected members it inherits.
|
|
208
|
+
var protectedFlags = BindingFlags.Instance | BindingFlags.NonPublic;
|
|
209
|
+
var inherited = type.GetMethods(protectedFlags)
|
|
210
|
+
.FirstOrDefault(m => m.Name == method && (m.IsFamily || m.IsFamilyOrAssembly) && m.GetParameters().Length == args.Length);
|
|
211
|
+
if (inherited is not null)
|
|
212
|
+
{
|
|
213
|
+
var built = BuildArgsBinExact(args, inherited.GetParameters());
|
|
214
|
+
return Box(inherited.Invoke(target, built));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
180
217
|
if (entry.Invoke is null)
|
|
181
218
|
{
|
|
182
219
|
var candidates = type.GetMethods(flags).Where(m => m.Name == method && !m.IsSpecialName);
|
|
@@ -186,7 +223,7 @@ public static partial class Bridge
|
|
|
186
223
|
var built = BuildArgsBin(args, parameters);
|
|
187
224
|
try
|
|
188
225
|
{
|
|
189
|
-
var res =
|
|
226
|
+
var res = (m.Invoke(target, built));
|
|
190
227
|
return Box(res);
|
|
191
228
|
}
|
|
192
229
|
catch (TargetInvocationException tie) when (IsMarshaledForDifferentThread(tie.InnerException))
|
|
@@ -194,7 +231,7 @@ public static partial class Bridge
|
|
|
194
231
|
if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected wrong-thread COM error; retrying {type.FullName}.{m.Name} on UI thread");
|
|
195
232
|
try
|
|
196
233
|
{
|
|
197
|
-
var res = InvokeOnUIThread(() =>
|
|
234
|
+
var res = InvokeOnUIThread(() => (m.Invoke(target, built)));
|
|
198
235
|
return Box(res);
|
|
199
236
|
}
|
|
200
237
|
catch { /* retry failed — try next candidate */ }
|
|
@@ -204,7 +241,7 @@ public static partial class Bridge
|
|
|
204
241
|
if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected COMException wrong-thread; retrying {type.FullName}.{m.Name} on UI thread");
|
|
205
242
|
try
|
|
206
243
|
{
|
|
207
|
-
var res = InvokeOnUIThread(() =>
|
|
244
|
+
var res = InvokeOnUIThread(() => (m.Invoke(target, built)));
|
|
208
245
|
return Box(res);
|
|
209
246
|
}
|
|
210
247
|
catch { /* retry failed — try next candidate */ }
|
|
@@ -219,25 +256,33 @@ public static partial class Bridge
|
|
|
219
256
|
try {
|
|
220
257
|
try
|
|
221
258
|
{
|
|
222
|
-
var res =
|
|
259
|
+
var res = (entry.Invoke(target, builtArgs));
|
|
223
260
|
return Box(res);
|
|
224
261
|
}
|
|
225
262
|
catch (TargetInvocationException tie) when (IsMarshaledForDifferentThread(tie.InnerException))
|
|
226
263
|
{
|
|
227
264
|
if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected wrong-thread COM error; retrying {type.FullName}.{method} on UI thread");
|
|
228
|
-
var res = InvokeOnUIThread(() =>
|
|
265
|
+
var res = InvokeOnUIThread(() => (entry.Invoke(target, builtArgs)));
|
|
229
266
|
return Box(res);
|
|
230
267
|
}
|
|
231
268
|
catch (System.Runtime.InteropServices.COMException ce) when (IsMarshaledForDifferentThread(ce))
|
|
232
269
|
{
|
|
233
270
|
if (Bridge.IsLogToConsole()) Console.Error.WriteLine($"[Bridge] Detected COMException wrong-thread; retrying {type.FullName}.{method} on UI thread");
|
|
234
|
-
var res = InvokeOnUIThread(() =>
|
|
271
|
+
var res = InvokeOnUIThread(() => (entry.Invoke(target, builtArgs)));
|
|
235
272
|
return Box(res);
|
|
236
273
|
}
|
|
237
274
|
}
|
|
238
275
|
finally { if (builtArgs.Length > 0) ReturnArgs(builtArgs); }
|
|
239
276
|
}
|
|
240
277
|
|
|
278
|
+
private static readonly System.Collections.Concurrent.ConcurrentDictionary<MethodKey, MethodInfo[]> s_overloadCache = new();
|
|
279
|
+
|
|
280
|
+
private static MethodInfo[] GetOverloads(Type type, string name, int argCount, BindingFlags flags)
|
|
281
|
+
=> s_overloadCache.GetOrAdd(new MethodKey(type, name, argCount, flags), static k =>
|
|
282
|
+
k.Type.GetMethods(k.Flags)
|
|
283
|
+
.Where(m => m.Name == k.Name && !m.IsGenericMethodDefinition && m.GetParameters().Length == k.ArgCount)
|
|
284
|
+
.ToArray());
|
|
285
|
+
|
|
241
286
|
private static object?[] BuildArgsBin(object?[] binArgs, ParameterInfo[] parameters)
|
|
242
287
|
{
|
|
243
288
|
if (parameters.Length == 0) return [];
|
|
@@ -256,6 +301,16 @@ public static partial class Bridge
|
|
|
256
301
|
return result;
|
|
257
302
|
}
|
|
258
303
|
|
|
304
|
+
// Plain JS objects <-> .NET structs/records: public fields count (Windows.Foundation.Size and most
|
|
305
|
+
// interop structs are fields), member names match case-insensitively.
|
|
306
|
+
internal static readonly System.Text.Json.JsonSerializerOptions s_jsJsonOptions = new()
|
|
307
|
+
{
|
|
308
|
+
IncludeFields = true,
|
|
309
|
+
PropertyNameCaseInsensitive = true,
|
|
310
|
+
NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString
|
|
311
|
+
| System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals,
|
|
312
|
+
};
|
|
313
|
+
|
|
259
314
|
private static object? CoerceBin(object? value, Type targetType)
|
|
260
315
|
{
|
|
261
316
|
if (value is null) return null;
|
|
@@ -319,8 +374,28 @@ public static partial class Bridge
|
|
|
319
374
|
throw;
|
|
320
375
|
}
|
|
321
376
|
}
|
|
377
|
+
if (value is JsJsonValue json)
|
|
378
|
+
{
|
|
379
|
+
if (targetType == typeof(string)) return json.Json;
|
|
380
|
+
var target = targetType == typeof(object) ? typeof(System.Text.Json.JsonElement) : targetType;
|
|
381
|
+
return System.Text.Json.JsonSerializer.Deserialize(json.Json, target, s_jsJsonOptions);
|
|
382
|
+
}
|
|
383
|
+
if (value is JsFunctionRef fn)
|
|
384
|
+
{
|
|
385
|
+
var delegateType = typeof(Delegate).IsAssignableFrom(targetType)
|
|
386
|
+
&& targetType != typeof(Delegate) && targetType != typeof(MulticastDelegate)
|
|
387
|
+
? targetType
|
|
388
|
+
: typeof(Action);
|
|
389
|
+
return MakeJsDelegate(delegateType, fn.Id);
|
|
390
|
+
}
|
|
322
391
|
if (value.GetType() == targetType) return value;
|
|
323
|
-
|
|
392
|
+
var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType;
|
|
393
|
+
if (underlying.IsEnum)
|
|
394
|
+
{
|
|
395
|
+
try { return Enum.ToObject(underlying, Convert.ToInt64(value)); }
|
|
396
|
+
catch { return value; }
|
|
397
|
+
}
|
|
398
|
+
try { return Convert.ChangeType(value, underlying); }
|
|
324
399
|
catch { return value; }
|
|
325
400
|
}
|
|
326
401
|
|
|
@@ -115,7 +115,7 @@ public static partial class Bridge
|
|
|
115
115
|
var built = BuildArgs(args, parameters);
|
|
116
116
|
try
|
|
117
117
|
{
|
|
118
|
-
var res =
|
|
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(() =>
|
|
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(() =>
|
|
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 =
|
|
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(() =>
|
|
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(() =>
|
|
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,10 +293,18 @@ 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 holds, so the
|
|
297
|
+
// runtime hands out that same JS object. If that object was collected (its handle released),
|
|
298
|
+
// the instance gets a new handle below, recorded for the JS object the runtime revives.
|
|
299
|
+
var jsHolder = JsBackedHolder(value, out var jsHandleLive);
|
|
300
|
+
if (jsHolder is not null && jsHandleLive)
|
|
301
|
+
return DispatchResult.Handle(jsHolder.HandleId, t.FullName ?? t.Name);
|
|
302
|
+
|
|
324
303
|
|
|
325
304
|
|
|
326
305
|
var id = Interlocked.Increment(ref s_nextHandle);
|
|
327
306
|
s_handles[id] = value;
|
|
307
|
+
if (jsHolder is not null) jsHolder.HandleId = id;
|
|
328
308
|
|
|
329
309
|
// Try to obtain a canonical IInspectable/IUnknown pointer for COM/WinRT objects
|
|
330
310
|
// so the runtime can call native vtable methods directly.
|
|
@@ -351,7 +331,7 @@ public static partial class Bridge
|
|
|
351
331
|
: DispatchResult.Handle(id, typeName);
|
|
352
332
|
}
|
|
353
333
|
|
|
354
|
-
private static bool IsAwaitable(object value, Type t)
|
|
334
|
+
private static bool IsAwaitable(object? value, Type t)
|
|
355
335
|
{
|
|
356
336
|
if (value is Task || value is ValueTask) return true;
|
|
357
337
|
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ValueTask<>)) return true;
|
|
@@ -363,6 +343,31 @@ public static partial class Bridge
|
|
|
363
343
|
null, Type.EmptyTypes, null) is not null;
|
|
364
344
|
}
|
|
365
345
|
|
|
346
|
+
/// "interface", "abstract", "static", "sealed", "class", "struct", "enum", "delegate", or ""
|
|
347
|
+
/// when the type isn't found.
|
|
348
|
+
/// Lets JS decide between `new Interface({...})`, subclassing and plain construction.
|
|
349
|
+
public static string TypeKind(string typeName)
|
|
350
|
+
{
|
|
351
|
+
var t = ResolveType(null, typeName);
|
|
352
|
+
if (t is null) return "";
|
|
353
|
+
if (t.IsInterface) return "interface";
|
|
354
|
+
if (t.IsEnum) return "enum";
|
|
355
|
+
if (typeof(Delegate).IsAssignableFrom(t)) return "delegate";
|
|
356
|
+
if (t.IsValueType) return "struct";
|
|
357
|
+
if (t.IsAbstract && t.IsSealed) return "static";
|
|
358
|
+
if (t.IsAbstract) return "abstract";
|
|
359
|
+
if (t.IsSealed) return "sealed";
|
|
360
|
+
return "class";
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/// `value instanceof SomeType` for a .NET object that was not constructed from JS.
|
|
364
|
+
public static bool IsInstanceOf(object? value, string typeName)
|
|
365
|
+
{
|
|
366
|
+
if (value is null) return false;
|
|
367
|
+
var t = ResolveType(null, typeName);
|
|
368
|
+
return t is not null && t.IsInstanceOfType(value);
|
|
369
|
+
}
|
|
370
|
+
|
|
366
371
|
internal static DispatchResult BuildMembersResult(Type t)
|
|
367
372
|
{
|
|
368
373
|
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,
|
|
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
|
-
|
|
26
|
-
|
|
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
|
-
|
|
29
|
-
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
42
|
-
|
|
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
|
-
|
|
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
|
-
|
|
52
|
-
|
|
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
|
-
|
|
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
|
-
|
|
77
|
-
il.Emit(OpCodes.
|
|
78
|
-
il.Emit(OpCodes.
|
|
79
|
-
il.Emit(OpCodes.Call,
|
|
80
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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
|
|
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
|
-
|
|
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);
|