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

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 +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
@@ -57,7 +57,7 @@ namespace __PROJECT_NAME__
57
57
  try
58
58
  {
59
59
  var panicLogPath = System.IO.Path.Combine(
60
- ApplicationData.Current.LocalFolder.Path, "nativescript-panic.log");
60
+ RuntimeHost.LocalFolderPath, "nativescript-panic.log");
61
61
  if (System.IO.File.Exists(panicLogPath))
62
62
  {
63
63
  var content = System.IO.File.ReadAllText(panicLogPath);
@@ -121,7 +121,8 @@ namespace __PROJECT_NAME__
121
121
  {
122
122
  StopPump();
123
123
  _runtimeHost.NotifyAppEvent((int)AppEventKind.Exit, null);
124
- ApplicationData.Current.LocalSettings.Values[LastLaunchArgsKey] = string.Empty;
124
+ try { ApplicationData.Current.LocalSettings.Values[LastLaunchArgsKey] = string.Empty; }
125
+ catch (InvalidOperationException) { } // unpackaged: no ApplicationData
125
126
  _runtimeHost.Dispose();
126
127
  }
127
128
 
@@ -101,7 +101,7 @@ namespace __PROJECT_NAME__
101
101
  // Include panic log from previous or current run
102
102
  try
103
103
  {
104
- var panicLog = Path.Combine(ApplicationData.Current.LocalFolder.Path, "nativescript-panic.log");
104
+ var panicLog = Path.Combine(RuntimeHost.LocalFolderPath, "nativescript-panic.log");
105
105
  if (File.Exists(panicLog))
106
106
  {
107
107
  var content = File.ReadAllText(panicLog, Encoding.UTF8).Trim();
@@ -130,7 +130,7 @@ namespace __PROJECT_NAME__
130
130
 
131
131
  public static string CrashLogPath()
132
132
  {
133
- try { return Path.Combine(ApplicationData.Current.LocalFolder.Path, "nativescript-crash.log"); }
133
+ try { return Path.Combine(RuntimeHost.LocalFolderPath, "nativescript-crash.log"); }
134
134
  catch { return null; }
135
135
  }
136
136
 
@@ -272,7 +272,7 @@ namespace __PROJECT_NAME__
272
272
  {
273
273
  try
274
274
  {
275
- var logPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "nativescript-crash.log");
275
+ var logPath = Path.Combine(RuntimeHost.LocalFolderPath, "nativescript-crash.log");
276
276
  File.AppendAllText(logPath, content, Encoding.UTF8);
277
277
  }
278
278
  catch { }
@@ -33,7 +33,7 @@ namespace __PROJECT_NAME__
33
33
  private static extern void runtime_set_local_folder([MarshalAs(UnmanagedType.LPUTF8Str)] string localFolder);
34
34
 
35
35
  // Escape hatch for apps packed with `nsbundle_pack --key-hex <hex>` (custom-key
36
- // app.nsbundle containers). Must be called before runtime_init if used at all — apps
36
+ // app.nsbundle containers). Must be called before runtime_init if used at all: apps
37
37
  // packed with the default pepper (no --key-hex) never need to call this. Not wired to a
38
38
  // default call site here; an app author supplies their own key material and calls this
39
39
  // from Initialize() before runtime_init(...).
@@ -53,6 +53,7 @@ namespace __PROJECT_NAME__
53
53
  private static extern void runtime_free_js_error(IntPtr ptr);
54
54
 
55
55
  [DllImport(NativeScriptLibrary, EntryPoint = nameof(runtime_has_devtools))]
56
+ [return: MarshalAs(UnmanagedType.U1)]
56
57
  private static extern bool runtime_has_devtools();
57
58
 
58
59
  [DllImport(NativeScriptLibrary, EntryPoint = nameof(runtime_pump_timers))]
@@ -69,6 +70,18 @@ namespace __PROJECT_NAME__
69
70
  }
70
71
 
71
72
  #if DEBUG
73
+ // Engine runtimes (@nativescript/windows-<engine>) only: a debug host always allows
74
+ // dev-server modules (Vite HMR). The classic runtime derives this from its devtools build
75
+ // and doesn't export it.
76
+ [DllImport(NativeScriptLibrary, EntryPoint = nameof(runtime_set_debug_build))]
77
+ private static extern void runtime_set_debug_build(int debug);
78
+
79
+ private static void TrySetDebugBuild()
80
+ {
81
+ try { runtime_set_debug_build(1); }
82
+ catch (EntryPointNotFoundException) { }
83
+ }
84
+
72
85
  [DllImport(NativeScriptLibrary, EntryPoint = nameof(ns_set_log_to_console))]
73
86
  private static extern int ns_set_log_to_console(int enabled);
74
87
 
@@ -98,6 +111,21 @@ namespace __PROJECT_NAME__
98
111
  [DllImport(NativeScriptLibrary, EntryPoint = nameof(runtime_free_string))]
99
112
  private static extern void runtime_free_string(IntPtr ptr);
100
113
 
114
+ [DllImport(NativeScriptLibrary, EntryPoint = nameof(runtime_devtools_wait_for_debugger))]
115
+ [return: MarshalAs(UnmanagedType.U1)]
116
+ private static extern bool runtime_devtools_wait_for_debugger(long runtime, uint timeoutMs);
117
+
118
+ // iOS uses 41000 and Android 42000.
119
+ private const ushort DevtoolsPort = 43000;
120
+ private const uint DebuggerWaitTimeoutMs = 30000;
121
+
122
+ // LocalFolder sentinel files shared with the CLI's WindowsApplicationManager.
123
+ private const string InspectorMarker = "ns-inspector";
124
+ private const string DebugBreakMarker = "ns-debugbreak";
125
+ private const string DebuggerStartedMarker = "ns-debugger-started";
126
+
127
+ private bool _waitForDebugger;
128
+
101
129
  public string DevtoolsFrontendUrl { get; private set; }
102
130
 
103
131
  private bool _devtoolsAvailable;
@@ -118,7 +146,7 @@ namespace __PROJECT_NAME__
118
146
  IntPtr urlPtr = IntPtr.Zero;
119
147
  try
120
148
  {
121
- urlPtr = runtime_devtools_start(_runtime, 42000);
149
+ urlPtr = runtime_devtools_start(_runtime, DevtoolsPort);
122
150
  if (urlPtr == IntPtr.Zero) return;
123
151
  var wsUrl = Marshal.PtrToStringUTF8(urlPtr);
124
152
  DevtoolsFrontendUrl = wsUrl != null
@@ -127,6 +155,8 @@ namespace __PROJECT_NAME__
127
155
  if (DevtoolsFrontendUrl != null)
128
156
  {
129
157
  _devtoolsAvailable = true;
158
+ // The server may fall back to the next free port.
159
+ WriteMarker(DebuggerStartedMarker, new Uri(wsUrl).Port.ToString());
130
160
  System.Diagnostics.Debug.WriteLine($"[NativeScript DevTools] {DevtoolsFrontendUrl}");
131
161
  }
132
162
  }
@@ -145,15 +175,41 @@ namespace __PROJECT_NAME__
145
175
  private long _runtime;
146
176
  private bool _initialized;
147
177
 
178
+ private static string _localFolderPath;
179
+
180
+ /// The app's local data folder: ApplicationData's LocalFolder for a packaged app, or
181
+ /// %LOCALAPPDATA%\<AssemblyName> for an unpackaged one (WindowsPackageType=None), which has
182
+ /// no package identity and therefore no ApplicationData.
183
+ internal static string LocalFolderPath
184
+ {
185
+ get
186
+ {
187
+ if (_localFolderPath != null) return _localFolderPath;
188
+ try
189
+ {
190
+ _localFolderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
191
+ }
192
+ catch (InvalidOperationException)
193
+ {
194
+ var name = Assembly.GetEntryAssembly()?.GetName().Name ?? "NativeScriptApp";
195
+ _localFolderPath = Path.Combine(
196
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), name);
197
+ Directory.CreateDirectory(_localFolderPath);
198
+ }
199
+ return _localFolderPath;
200
+ }
201
+ }
202
+
148
203
  public void Initialize()
149
204
  {
150
205
  if (_initialized) return;
151
206
  bool attached = false;
152
207
  try { attached = AttachConsole(ATTACH_PARENT_PROCESS); } catch { }
153
208
  runtime_install_ctrlc_handler(0);
154
- runtime_set_local_folder(Windows.Storage.ApplicationData.Current.LocalFolder.Path);
209
+ runtime_set_local_folder(LocalFolderPath);
155
210
  _runtime = runtime_init(AppContext.BaseDirectory);
156
211
  #if DEBUG
212
+ TrySetDebugBuild();
157
213
  var trySet = TrySetLogToConsole(true);
158
214
  System.Diagnostics.Debug.WriteLine($"[NativeScript] TrySetLogToConsole returned={trySet}");
159
215
 
@@ -178,37 +234,54 @@ namespace __PROJECT_NAME__
178
234
  }
179
235
  }
180
236
  catch { }
181
- if (ConsumeDebugBreakMarker())
237
+ DeleteMarker(DebuggerStartedMarker);
238
+ var debugBreak = ConsumeMarker(DebugBreakMarker);
239
+ if (ConsumeMarker(InspectorMarker) || debugBreak)
240
+ {
182
241
  StartDevtoolsSafely();
242
+ _waitForDebugger = debugBreak && _devtoolsAvailable;
243
+ }
183
244
  #endif
184
245
  _initialized = true;
185
246
  }
186
247
 
187
248
  #if DEBUG
188
- /// <summary>
189
- /// Returns true and deletes the marker if the CLI wrote ns-debugbreak to LocalFolder,
190
- /// matching the Android sentinel-file pattern used by the NativeScript CLI.
191
- /// </summary>
192
- private static bool ConsumeDebugBreakMarker()
249
+ private static string MarkerPath(string name) =>
250
+ Path.Combine(LocalFolderPath, name);
251
+
252
+ private static bool ConsumeMarker(string name)
193
253
  {
194
254
  try
195
255
  {
196
- var markerPath = System.IO.Path.Combine(
197
- Windows.Storage.ApplicationData.Current.LocalFolder.Path,
198
- "ns-debugbreak");
199
- if (!System.IO.File.Exists(markerPath))
256
+ var markerPath = MarkerPath(name);
257
+ if (!File.Exists(markerPath))
200
258
  return false;
201
- System.IO.File.Delete(markerPath);
259
+ File.Delete(markerPath);
202
260
  return true;
203
261
  }
204
262
  catch { return false; }
205
263
  }
264
+
265
+ private static void WriteMarker(string name, string contents)
266
+ {
267
+ try { File.WriteAllText(MarkerPath(name), contents); }
268
+ catch (Exception ex)
269
+ {
270
+ System.Diagnostics.Debug.WriteLine($"[NativeScript DevTools] Could not write {name}: {ex.Message}");
271
+ }
272
+ }
273
+
274
+ private static void DeleteMarker(string name)
275
+ {
276
+ try { File.Delete(MarkerPath(name)); }
277
+ catch { }
278
+ }
206
279
  #endif
207
280
 
208
281
  /// Reads a file that may live inside a sealed app.nsbundle instead of on disk: tries the
209
282
  /// protected-VFS native call first (cheap no-op when no bundle is loaded), falls back to
210
283
  /// the real filesystem. `path` is whatever candidate the caller already built for
211
- /// `File.Exists`/`File.ReadAllText` — the native side strips it down to the bundle's
284
+ /// `File.Exists`/`File.ReadAllText`: the native side strips it down to the bundle's
212
285
  /// virtual (app/App-relative) path itself, so no extra bookkeeping is needed here.
213
286
  private static string TryReadVirtual(string path)
214
287
  {
@@ -231,6 +304,15 @@ namespace __PROJECT_NAME__
231
304
  if (!_initialized)
232
305
  throw new InvalidOperationException("Runtime must be initialized before running scripts.");
233
306
 
307
+ #if DEBUG
308
+ if (_waitForDebugger)
309
+ {
310
+ // --debug-brk: hold the first script until DevTools attaches.
311
+ _waitForDebugger = false;
312
+ if (!runtime_devtools_wait_for_debugger(_runtime, DebuggerWaitTimeoutMs))
313
+ System.Diagnostics.Debug.WriteLine("[NativeScript DevTools] No debugger attached, continuing.");
314
+ }
315
+ #endif
234
316
  var entryPath = ResolveEntryScriptPath();
235
317
  if (entryPath == null)
236
318
  {
@@ -240,7 +322,11 @@ namespace __PROJECT_NAME__
240
322
 
241
323
  var dir = Path.GetDirectoryName(Path.GetFullPath(entryPath));
242
324
  var chunks = new List<string>();
243
- foreach (var chunkName in new[] { "runtime.js", "vendor.js" })
325
+ // An ES-module entry (Vite's bundle.mjs) imports its own chunks; webpack's classic
326
+ // runtime.js/vendor.js prelude must not run in front of it (a stale pair can be left
327
+ // in app/ after switching bundlers).
328
+ var isModuleEntry = entryPath.EndsWith(".mjs", StringComparison.OrdinalIgnoreCase);
329
+ foreach (var chunkName in isModuleEntry ? Array.Empty<string>() : new[] { "runtime.js", "vendor.js" })
244
330
  {
245
331
  var chunkPath = Path.Combine(dir, chunkName);
246
332
  if (VExists(chunkPath) &&
@@ -256,7 +342,11 @@ namespace __PROJECT_NAME__
256
342
  var script = VReadAllText(Path.GetFullPath(scriptPath));
257
343
  try
258
344
  {
259
- runtime_runscript(_runtime, script, Path.GetFileName(scriptPath));
345
+ // Modules resolve their imports (chunks, ~/ paths) relative to their own
346
+ // location, so they need the full path; classic scripts keep the short name
347
+ // their stack traces and code-cache keys have always used.
348
+ var name = isModuleEntry ? Path.GetFullPath(scriptPath) : Path.GetFileName(scriptPath);
349
+ runtime_runscript(_runtime, script, name);
260
350
  }
261
351
  catch (Exception ex)
262
352
  {
@@ -25,19 +25,14 @@
25
25
  <NSWindowsRoot>$(MSBuildProjectDirectory)\..</NSWindowsRoot>
26
26
  </PropertyGroup>
27
27
 
28
- <!-- Static Binding Generator (SBG) output folder and helper properties for integrating generated proxies. -->
29
28
  <PropertyGroup>
30
- <NSGenDir>$(BaseIntermediateOutputPath)_ns_\gen</NSGenDir>
31
- <SBG_OUTPUT_DIR>$(MSBuildProjectDirectory)\$(NSGenDir)</SBG_OUTPUT_DIR>
32
29
  <!-- Path to the windows-runtime repository root. Can be overridden by setting the environment
33
30
  variable `NS_WINDOWS_RUNTIME_ROOT` (useful when building an app that lives outside the
34
31
  runtime repo). If not set, fall back to the project parent directory (legacy behavior). -->
35
32
  <WindowsRuntimeRepoRoot Condition="'$(WindowsRuntimeRepoRoot)'=='' and '$(NS_WINDOWS_RUNTIME_ROOT)' != ''">$(NS_WINDOWS_RUNTIME_ROOT)</WindowsRuntimeRepoRoot>
36
33
  <WindowsRuntimeRepoRoot Condition="'$(WindowsRuntimeRepoRoot)'==''">$(MSBuildProjectDirectory)\..</WindowsRuntimeRepoRoot>
37
- <SBGMetadataSource>$(SBG_OUTPUT_DIR)\sbg_metadata.json</SBGMetadataSource>
38
34
  <!-- Resolve pre-built tool binaries shipped inside the npm package tools/ directory -->
39
35
  <NSToolsDir>$(NSWindowsRoot)\tools</NSToolsDir>
40
- <SbgExe Condition="Exists('$(NSToolsDir)\sbg.exe')">$(NSToolsDir)\sbg.exe</SbgExe>
41
36
  <DotNetToolExe Condition="Exists('$(NSToolsDir)\dotnet-tool.exe')">$(NSToolsDir)\dotnet-tool.exe</DotNetToolExe>
42
37
  </PropertyGroup>
43
38
 
@@ -96,8 +91,23 @@
96
91
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
97
92
  </Content>
98
93
 
99
- <!-- App_Resources: platform-specific assets (images, fonts, etc.) -->
100
- <Content Include="App_Resources\**\*" Condition="Exists('App_Resources')">
94
+ <!-- App_Resources: platform-specific assets (images, fonts, etc.). C# sources anywhere under
95
+ App_Resources\Windows (e.g. App_Resources\Windows\src\*.cs) and in plugins\<plugin>\ are
96
+ compiled into the app by the SDK's default Compile glob — the counterpart of Java/Kotlin in
97
+ App_Resources/Android/src and Objective-C/Swift in App_Resources/iOS/src — and JavaScript
98
+ reaches their types by namespace. Sources and MSBuild files aren't copied to the output. -->
99
+ <Content Include="App_Resources\**\*" Exclude="App_Resources\**\*.cs;App_Resources\**\*.csproj;App_Resources\**\*.props;App_Resources\**\*.targets" Condition="Exists('App_Resources')">
100
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
101
+ </Content>
102
+
103
+ <!-- The app's metadata filter (App_Resources/Windows/native-api-usage.json, which the CLI writes
104
+ out next to this project): the runtime reads it next to the exe. -->
105
+ <Content Include="$(NSWindowsRoot)\whitelist.mdg" Condition="Exists('$(NSWindowsRoot)\whitelist.mdg')">
106
+ <Link>whitelist.mdg</Link>
107
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
108
+ </Content>
109
+ <Content Include="$(NSWindowsRoot)\blacklist.mdg" Condition="Exists('$(NSWindowsRoot)\blacklist.mdg')">
110
+ <Link>blacklist.mdg</Link>
101
111
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
102
112
  </Content>
103
113
 
@@ -175,44 +185,23 @@
175
185
  SkipUnchangedFiles="true" />
176
186
  </Target>
177
187
 
178
- <!-- Run the Static Binding Generator (sbg) when project contains an sbg entry script
179
- or when pre-existing metadata is present. Generated proxies will be written
180
- into $(NSGenDir) and included in compilation. -->
181
- <Target Name="RunStaticBindingGenerator" BeforeTargets="CoreCompile">
182
- <MakeDir Directories="$(NSGenDir)" />
183
- <!-- Run dotnet-tool to auto-detect .NET usage and publish/copy DotNetBridge.
184
- Prefer the pre-built binary shipped in the npm package; fall back to cargo run for dev. -->
185
- <Exec Command="&quot;$(DotNetToolExe)&quot; --app-root &quot;$(MSBuildProjectDirectory)&quot; --dir App --sbg-output &quot;$(SBG_OUTPUT_DIR)&quot;"
188
+ <!-- A filter the app dropped must not stay in force from an earlier build's copy. -->
189
+ <Target Name="RemoveStaleMetadataFilter" BeforeTargets="CopyFilesToOutputDirectory">
190
+ <Delete Files="$(OutDir)whitelist.mdg" Condition="!Exists('$(NSWindowsRoot)\whitelist.mdg')" />
191
+ <Delete Files="$(OutDir)blacklist.mdg" Condition="!Exists('$(NSWindowsRoot)\blacklist.mdg')" />
192
+ </Target>
193
+
194
+ <!-- Run dotnet-tool to auto-detect .NET usage and publish/copy DotNetBridge. Prefer the pre-built
195
+ binary shipped in the npm package; fall back to cargo run for dev. JS subclasses of .NET and
196
+ WinRT classes need no generated code: the bridge creates their managed types at runtime. -->
197
+ <Target Name="RunDotNetTool" BeforeTargets="CoreCompile">
198
+ <Exec Command="&quot;$(DotNetToolExe)&quot; --app-root &quot;$(MSBuildProjectDirectory)&quot; --dir App"
186
199
  Condition="'$(DotNetToolExe)' != ''" />
187
200
  <Exec WorkingDirectory="$(WindowsRuntimeRepoRoot)"
188
- Command="cargo run --quiet --manifest-path &quot;$(WindowsRuntimeRepoRoot)\Cargo.toml&quot; -p dotnet-tool -- --app-root &quot;$(MSBuildProjectDirectory)&quot; --dir App --sbg-output &quot;$(SBG_OUTPUT_DIR)&quot;"
201
+ Command="cargo run --quiet --manifest-path &quot;$(WindowsRuntimeRepoRoot)\Cargo.toml&quot; -p dotnet-tool -- --app-root &quot;$(MSBuildProjectDirectory)&quot; --dir App"
189
202
  Condition="'$(DotNetToolExe)' == '' and Exists('$(WindowsRuntimeRepoRoot)\Cargo.toml')" />
190
- <!-- Run SBG to generate C# proxies from captured metadata.
191
- sbg_metadata.json is written by __nsProxyAutoCapture when the app runs
192
- with extensions that use .extend() / @Interfaces / @CSharpProxy.
193
- Search order: pre-built tools/ binary, then cargo run for dev. -->
194
- <Exec
195
- Command="&quot;$(SbgExe)&quot;"
196
- EnvironmentVariables="NSWINRT_AUTO_METADATA_PATH=$(SBGMetadataSource);SBG_OUTPUT_DIR=$(SBG_OUTPUT_DIR);SBG_METADATA_SOURCE=$(SBGMetadataSource);SBG_TARGET_FRAMEWORK=$(TargetFramework);SBG_TARGET_PLATFORM_MIN_VERSION=$(TargetPlatformMinVersion);SBG_USE_UWP=false;SBG_APP_CS_SOURCES_DIR=$(MSBuildProjectDirectory)"
197
- Condition="'$(SbgExe)' != '' and Exists('$(SBGMetadataSource)')" />
198
- <Exec WorkingDirectory="$(WindowsRuntimeRepoRoot)"
199
- Command="cargo run --quiet --manifest-path &quot;$(WindowsRuntimeRepoRoot)\Cargo.toml&quot; -p sbg"
200
- EnvironmentVariables="NSWINRT_AUTO_METADATA_PATH=$(SBGMetadataSource);SBG_OUTPUT_DIR=$(SBG_OUTPUT_DIR);SBG_METADATA_SOURCE=$(SBGMetadataSource);SBG_TARGET_FRAMEWORK=$(TargetFramework);SBG_TARGET_PLATFORM_MIN_VERSION=$(TargetPlatformMinVersion);SBG_USE_UWP=false;SBG_APP_CS_SOURCES_DIR=$(MSBuildProjectDirectory)"
201
- Condition="'$(SbgExe)' == '' and Exists('$(SBGMetadataSource)') and Exists('$(WindowsRuntimeRepoRoot)\Cargo.toml')" />
202
203
  </Target>
203
204
 
204
- <Target Name="CleanStaticBindingGeneratorOutput" AfterTargets="CoreClean">
205
- <RemoveDir Directories="$(NSGenDir)" Condition="Exists('$(NSGenDir)')" />
206
- </Target>
207
-
208
- <ItemGroup>
209
- <Compile Include="$(NSGenDir)\NSWinRTProxies\**\*.cs" Visible="false" Condition="Exists('$(NSGenDir)\NSWinRTProxies')" />
210
- <Compile Remove="$(NSGenDir)\NSWinRTProxies\obj\**\*.cs" Condition="Exists('$(NSGenDir)\NSWinRTProxies\obj')" />
211
- <Content Include="$(NSGenDir)\sbg-manifest.json" Link="sbg-manifest.json" CopyToOutputDirectory="PreserveNewest" Condition="Exists('$(NSGenDir)\sbg-manifest.json')" />
212
- <Content Include="$(NSGenDir)\NSWinRTProxies\bin\Release\**\NSWinRTProxies.dll" Link="NSWinRTProxies.dll" CopyToOutputDirectory="PreserveNewest" Condition="Exists('$(NSGenDir)\NSWinRTProxies\bin\Release')" />
213
- </ItemGroup>
214
-
215
-
216
205
  <!-- Ensure bridge files are included in the final `dotnet publish` output. -->
217
206
  <Target Name="CopyDotNetBridgeToPublishDir"
218
207
  AfterTargets="Publish"
@@ -17,6 +17,20 @@ internal readonly struct WinRtRef(long ptr)
17
17
  public readonly long Ptr = ptr;
18
18
  }
19
19
 
20
+ // A JS function passed where a delegate is expected (tag 0x0C): the runtime's callback id, wrapped
21
+ // in a delegate of the parameter's type when the call's arguments are coerced.
22
+ internal readonly struct JsFunctionRef(int id)
23
+ {
24
+ public readonly int Id = id;
25
+ }
26
+
27
+ // A plain JS object (tag 0x0D) as JSON, deserialized into the struct/record/class the parameter or
28
+ // return type expects (e.g. `{ Width: 120, Height: 40 }` for Windows.Foundation.Size).
29
+ internal sealed class JsJsonValue(string json)
30
+ {
31
+ public readonly string Json = json;
32
+ }
33
+
20
34
  internal ref struct BinReader(ReadOnlySpan<byte> buf)
21
35
  {
22
36
  private readonly ReadOnlySpan<byte> _buf = buf;
@@ -24,6 +38,8 @@ internal ref struct BinReader(ReadOnlySpan<byte> buf)
24
38
 
25
39
  public byte ReadByte() => _buf[_pos++];
26
40
 
41
+ public bool HasMore => _pos < _buf.Length;
42
+
27
43
  public int ReadI32()
28
44
  {
29
45
  var v = BinaryPrimitives.ReadInt32LittleEndian(_buf[_pos..]);
@@ -96,6 +112,8 @@ internal ref struct BinReader(ReadOnlySpan<byte> buf)
96
112
  0x05 => (object)ReadString16(),
97
113
  0x06 => (object)new HandleRef(ReadI32()),
98
114
  0x0A => (object)new WinRtRef(ReadI64()),
115
+ 0x0C => (object)new JsFunctionRef(ReadI32()),
116
+ 0x0D => (object)new JsJsonValue(ReadString32()),
99
117
  _ => null,
100
118
  };
101
119
  }
@@ -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
- return CreateJsSubclass(NullIfEmpty(assembly), typeName, callbackId, interfaceNames, memberNames);
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 = AwaitIfTask(m.Invoke(target, built));
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(() => AwaitIfTask(m.Invoke(target, built)));
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(() => AwaitIfTask(m.Invoke(target, built)));
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 = AwaitIfTask(entry.Invoke(target, builtArgs));
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(() => AwaitIfTask(entry.Invoke(target, builtArgs)));
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(() => AwaitIfTask(entry.Invoke(target, builtArgs)));
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
- try { return Convert.ChangeType(value, targetType); }
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