@nativescript/vite 8.0.0-alpha.67 → 8.0.0-alpha.68

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 (170) hide show
  1. package/configuration/angular.js +78 -182
  2. package/configuration/angular.js.map +1 -1
  3. package/configuration/base.js +10 -139
  4. package/configuration/base.js.map +1 -1
  5. package/helpers/app-css-state.d.ts +20 -0
  6. package/helpers/app-css-state.js.map +1 -1
  7. package/helpers/main-entry.js +44 -4
  8. package/helpers/main-entry.js.map +1 -1
  9. package/helpers/ns-core-external-urls.d.ts +32 -0
  10. package/helpers/ns-core-external-urls.js +107 -0
  11. package/helpers/ns-core-external-urls.js.map +1 -0
  12. package/helpers/typescript-check.js +2 -2
  13. package/helpers/typescript-check.js.map +1 -1
  14. package/helpers/workers.d.ts +0 -8
  15. package/helpers/workers.js +43 -381
  16. package/helpers/workers.js.map +1 -1
  17. package/hmr/client/framework-client-strategy.d.ts +17 -9
  18. package/hmr/client/framework-client-strategy.js +3 -4
  19. package/hmr/client/framework-client-strategy.js.map +1 -1
  20. package/hmr/client/hmr-pending-overlay.js +2 -21
  21. package/hmr/client/hmr-pending-overlay.js.map +1 -1
  22. package/hmr/client/index.d.ts +9 -1
  23. package/hmr/client/index.js +34 -2621
  24. package/hmr/client/index.js.map +1 -1
  25. package/hmr/client/overlay-driver.d.ts +10 -0
  26. package/hmr/client/overlay-driver.js +33 -0
  27. package/hmr/client/overlay-driver.js.map +1 -0
  28. package/hmr/client/protocol-dispatch.d.ts +8 -0
  29. package/hmr/client/protocol-dispatch.js +309 -0
  30. package/hmr/client/protocol-dispatch.js.map +1 -0
  31. package/hmr/client/root-reset.d.ts +15 -0
  32. package/hmr/client/root-reset.js +358 -0
  33. package/hmr/client/root-reset.js.map +1 -0
  34. package/hmr/client/strategy-loader.d.ts +24 -0
  35. package/hmr/client/strategy-loader.js +83 -0
  36. package/hmr/client/strategy-loader.js.map +1 -0
  37. package/hmr/client/update-pipeline.d.ts +27 -0
  38. package/hmr/client/update-pipeline.js +464 -0
  39. package/hmr/client/update-pipeline.js.map +1 -0
  40. package/hmr/client/utils.js +3 -2
  41. package/hmr/client/utils.js.map +1 -1
  42. package/hmr/client/ws-transport.d.ts +21 -0
  43. package/hmr/client/ws-transport.js +344 -0
  44. package/hmr/client/ws-transport.js.map +1 -0
  45. package/hmr/frameworks/angular/build/angular-linker.js +4 -0
  46. package/hmr/frameworks/angular/build/angular-linker.js.map +1 -1
  47. package/hmr/frameworks/angular/build/linker-stats.d.ts +18 -0
  48. package/hmr/frameworks/angular/build/linker-stats.js +29 -0
  49. package/hmr/frameworks/angular/build/linker-stats.js.map +1 -0
  50. package/hmr/frameworks/angular/build/ts-fallback-transform.d.ts +5 -0
  51. package/hmr/frameworks/angular/build/ts-fallback-transform.js +138 -0
  52. package/hmr/frameworks/angular/build/ts-fallback-transform.js.map +1 -0
  53. package/hmr/frameworks/angular/build/worker-url-preserve.d.ts +5 -0
  54. package/hmr/frameworks/angular/build/worker-url-preserve.js +140 -0
  55. package/hmr/frameworks/angular/build/worker-url-preserve.js.map +1 -0
  56. package/hmr/frameworks/angular/client/index.d.ts +3 -0
  57. package/hmr/frameworks/angular/client/index.js +28 -42
  58. package/hmr/frameworks/angular/client/index.js.map +1 -1
  59. package/hmr/frameworks/angular/server/ng-component-route.d.ts +43 -0
  60. package/hmr/frameworks/angular/server/ng-component-route.js +113 -0
  61. package/hmr/frameworks/angular/server/ng-component-route.js.map +1 -0
  62. package/hmr/frameworks/angular/server/strategy.js +15 -11
  63. package/hmr/frameworks/angular/server/strategy.js.map +1 -1
  64. package/hmr/frameworks/angular/server/websocket-angular-hot-update.d.ts +12 -0
  65. package/hmr/frameworks/angular/server/websocket-angular-hot-update.js +39 -0
  66. package/hmr/frameworks/angular/server/websocket-angular-hot-update.js.map +1 -1
  67. package/hmr/frameworks/react/client/strategy.d.ts +12 -0
  68. package/hmr/frameworks/react/client/strategy.js +27 -0
  69. package/hmr/frameworks/react/client/strategy.js.map +1 -0
  70. package/hmr/frameworks/solid/client/strategy.d.ts +7 -0
  71. package/hmr/frameworks/solid/client/strategy.js +391 -0
  72. package/hmr/frameworks/solid/client/strategy.js.map +1 -0
  73. package/hmr/frameworks/solid/server/strategy.js +2 -0
  74. package/hmr/frameworks/solid/server/strategy.js.map +1 -1
  75. package/hmr/frameworks/typescript/client/strategy.d.ts +7 -0
  76. package/hmr/frameworks/typescript/client/strategy.js +418 -0
  77. package/hmr/frameworks/typescript/client/strategy.js.map +1 -0
  78. package/hmr/frameworks/typescript/server/strategy.js +2 -0
  79. package/hmr/frameworks/typescript/server/strategy.js.map +1 -1
  80. package/hmr/frameworks/vue/client/index.d.ts +1 -1
  81. package/hmr/frameworks/vue/client/index.js +40 -319
  82. package/hmr/frameworks/vue/client/index.js.map +1 -1
  83. package/hmr/frameworks/vue/client/navigate-app.d.ts +3 -0
  84. package/hmr/frameworks/vue/client/navigate-app.js +178 -0
  85. package/hmr/frameworks/vue/client/navigate-app.js.map +1 -0
  86. package/hmr/frameworks/vue/client/strategy.d.ts +1 -1
  87. package/hmr/frameworks/vue/client/strategy.js +9 -14
  88. package/hmr/frameworks/vue/client/strategy.js.map +1 -1
  89. package/hmr/frameworks/vue/client/vue-sfc-update-overlay.js +2 -20
  90. package/hmr/frameworks/vue/client/vue-sfc-update-overlay.js.map +1 -1
  91. package/hmr/frameworks/vue/server/strategy.js +3 -0
  92. package/hmr/frameworks/vue/server/strategy.js.map +1 -1
  93. package/hmr/server/css-connect-sync.d.ts +28 -0
  94. package/hmr/server/css-connect-sync.js +78 -0
  95. package/hmr/server/css-connect-sync.js.map +1 -0
  96. package/hmr/server/framework-strategy.d.ts +30 -0
  97. package/hmr/server/websocket-hmr-pending.d.ts +0 -8
  98. package/hmr/server/websocket-hmr-pending.js +0 -22
  99. package/hmr/server/websocket-hmr-pending.js.map +1 -1
  100. package/hmr/server/websocket-hot-update.d.ts +3 -0
  101. package/hmr/server/websocket-hot-update.js +63 -36
  102. package/hmr/server/websocket-hot-update.js.map +1 -1
  103. package/hmr/server/websocket-module-bindings.js +23 -5
  104. package/hmr/server/websocket-module-bindings.js.map +1 -1
  105. package/hmr/server/websocket-module-specifiers.d.ts +0 -5
  106. package/hmr/server/websocket-module-specifiers.js +0 -28
  107. package/hmr/server/websocket-module-specifiers.js.map +1 -1
  108. package/hmr/server/websocket-ns-m-paths.d.ts +18 -0
  109. package/hmr/server/websocket-ns-m-paths.js +79 -0
  110. package/hmr/server/websocket-ns-m-paths.js.map +1 -1
  111. package/hmr/server/websocket-ns-m-request.d.ts +2 -1
  112. package/hmr/server/websocket-ns-m-request.js +3 -2
  113. package/hmr/server/websocket-ns-m-request.js.map +1 -1
  114. package/hmr/server/websocket-ns-m.js +100 -374
  115. package/hmr/server/websocket-ns-m.js.map +1 -1
  116. package/hmr/server/websocket-served-module-helpers.d.ts +7 -0
  117. package/hmr/server/websocket-served-module-helpers.js +93 -69
  118. package/hmr/server/websocket-served-module-helpers.js.map +1 -1
  119. package/hmr/server/websocket.d.ts +0 -1
  120. package/hmr/server/websocket.js +27 -2
  121. package/hmr/server/websocket.js.map +1 -1
  122. package/hmr/shared/ns-globals.d.ts +0 -1
  123. package/hmr/shared/ns-globals.js.map +1 -1
  124. package/hmr/shared/protocol.d.ts +14 -0
  125. package/hmr/shared/protocol.js.map +1 -1
  126. package/hmr/shared/runtime/dev-overlay-ios.d.ts +87 -0
  127. package/hmr/shared/runtime/dev-overlay-ios.js +521 -0
  128. package/hmr/shared/runtime/dev-overlay-ios.js.map +1 -0
  129. package/hmr/shared/runtime/dev-overlay-shared.d.ts +58 -0
  130. package/hmr/shared/runtime/dev-overlay-shared.js +116 -0
  131. package/hmr/shared/runtime/dev-overlay-shared.js.map +1 -0
  132. package/hmr/shared/runtime/dev-overlay-tree.d.ts +59 -0
  133. package/hmr/shared/runtime/dev-overlay-tree.js +712 -0
  134. package/hmr/shared/runtime/dev-overlay-tree.js.map +1 -0
  135. package/hmr/shared/runtime/dev-overlay.d.ts +15 -107
  136. package/hmr/shared/runtime/dev-overlay.js +19 -1336
  137. package/hmr/shared/runtime/dev-overlay.js.map +1 -1
  138. package/hmr/shared/runtime/overlay-flag.d.ts +9 -0
  139. package/hmr/shared/runtime/overlay-flag.js +34 -0
  140. package/hmr/shared/runtime/overlay-flag.js.map +1 -0
  141. package/hmr/shared/runtime/root-placeholder.js +3 -2
  142. package/hmr/shared/runtime/root-placeholder.js.map +1 -1
  143. package/hmr/shared/runtime/session-bootstrap.js +2 -1
  144. package/hmr/shared/runtime/session-bootstrap.js.map +1 -1
  145. package/hmr/shared/runtime/vendor-resolve.d.ts +22 -0
  146. package/hmr/shared/runtime/vendor-resolve.js +45 -0
  147. package/hmr/shared/runtime/vendor-resolve.js.map +1 -0
  148. package/hmr/shared/vendor/manifest-collect.js +0 -3
  149. package/hmr/shared/vendor/manifest-collect.js.map +1 -1
  150. package/package.json +1 -3
  151. package/runtime/core-aliases-early.js +3 -2
  152. package/runtime/core-aliases-early.js.map +1 -1
  153. package/helpers/module-runner-patch.d.ts +0 -3
  154. package/helpers/module-runner-patch.js +0 -63
  155. package/helpers/module-runner-patch.js.map +0 -1
  156. package/hmr/server/websocket-css-hot-update.d.ts +0 -33
  157. package/hmr/server/websocket-css-hot-update.js +0 -65
  158. package/hmr/server/websocket-css-hot-update.js.map +0 -1
  159. package/hmr/shared/runtime/http-only-boot.d.ts +0 -2
  160. package/hmr/shared/runtime/http-only-boot.js +0 -172
  161. package/hmr/shared/runtime/http-only-boot.js.map +0 -1
  162. package/hmr/vendor-bootstrap.d.ts +0 -1
  163. package/hmr/vendor-bootstrap.js +0 -30
  164. package/hmr/vendor-bootstrap.js.map +0 -1
  165. package/shims/react-reconciler-constants.d.ts +0 -14
  166. package/shims/react-reconciler-constants.js +0 -21
  167. package/shims/react-reconciler-constants.js.map +0 -1
  168. package/shims/react-reconciler.d.ts +0 -8
  169. package/shims/react-reconciler.js +0 -15
  170. package/shims/react-reconciler.js.map +0 -1
@@ -1,120 +1,49 @@
1
1
  /**
2
- * Robust HMR client for NativeScript.
2
+ * HMR client entry for NativeScript devices.
3
3
  *
4
4
  * Avoid importing from '@nativescript/core' and other framework modules here to prevent creating a second module realm via HTTP ESM.
5
5
  * Always resolve core classes and Application from the vendor realm or globalThis at runtime.
6
6
  * The HMR client is evaluated via HTTP ESM on device; static imports would create secondary instances.
7
+ *
8
+ * This entry owns boot-time side effects (core aliases, launch-notification
9
+ * bridge, CSS register) and wires the seams together:
10
+ * - `ws-transport.ts` — socket connect/reconnect + connection overlay
11
+ * - `protocol-dispatch.ts` — routes parsed wire messages
12
+ * - `update-pipeline.ts` — graph state + evict-then-reimport queue
13
+ * - `root-reset.ts` — root-view replacement
14
+ * - `strategy-loader.ts` — flavor detection + framework strategy loading
7
15
  */
8
- import { setHMRWsUrl, getHMRWsUrl, pendingModuleFetches, deriveHttpOrigin, setHttpOriginForVite, moduleFetchCache, requestModuleFromServer, getHttpOriginForVite, normalizeSpec, hmrMetrics, graph, setGraphVersion, getGraphVersion, getCurrentApp, getRootFrame, setCurrentApp, setRootFrame, getCore, hasExplicitEviction, invalidateModulesByUrls, buildEvictionUrls, emitHmrModeBannerOnce, ENV_VERBOSE } from './utils.js';
9
- import { applyCssText, handleCssUpdates } from './css-handler.js';
10
- import { buildCssApplyingDetail, buildCssAppliedDetail } from './css-update-overlay.js';
16
+ import { setHMRWsUrl, getHMRWsUrl, getCore, ENV_VERBOSE } from './utils.js';
17
+ import { applyCssText } from './css-handler.js';
11
18
  import { getGlobalScope } from '../shared/runtime/global-scope.js';
12
- import { markDevBootComplete } from '../shared/runtime/boot-complete.js';
13
19
  import { installLaunchNotificationBridge } from '../shared/runtime/launch-bridge.js';
14
- import { getNsHotRegistry } from './hot-context.js';
20
+ import { connectHmr, setHmrMessageHandler } from './ws-transport.js';
21
+ import { handleHmrMessage } from './protocol-dispatch.js';
22
+ import { ensureCoreAliasesOnGlobalThis, performResetRoot } from './root-reset.js';
23
+ import { CLIENT_STRATEGY_READY, getClientStrategy } from './strategy-loader.js';
15
24
  const VERBOSE = ENV_VERBOSE;
16
- function resolveTargetFlavor() {
17
- try {
18
- if (typeof __NS_TARGET_FLAVOR__ !== 'undefined' && __NS_TARGET_FLAVOR__) {
19
- return __NS_TARGET_FLAVOR__;
20
- }
21
- }
22
- catch { }
23
- try {
24
- const g = getGlobalScope();
25
- if (typeof g.__NS_TARGET_FLAVOR__ === 'string' && g.__NS_TARGET_FLAVOR__) {
26
- return g.__NS_TARGET_FLAVOR__;
27
- }
28
- if (typeof g.__NS_HMR_BROWSER_RUNTIME_TARGET_FLAVOR__ === 'string' && g.__NS_HMR_BROWSER_RUNTIME_TARGET_FLAVOR__) {
29
- return g.__NS_HMR_BROWSER_RUNTIME_TARGET_FLAVOR__;
30
- }
31
- if (typeof g.__reboot_ng_modules__ === 'function') {
32
- return 'angular';
33
- }
34
- if (g.__VUE_HMR_RUNTIME__ || g.__NS_HMR_VUE_SFC_REGISTRY__) {
35
- return 'vue';
36
- }
37
- }
38
- catch { }
39
- return undefined;
40
- }
41
- const TARGET_FLAVOR = resolveTargetFlavor();
42
- // React reuses the generic TypeScript HMR path on BOTH server and client: it has
43
- // no Fast Refresh, so a module edit drives a plain module reload / root reset
44
- // (the React tree re-renders), exactly like the `typescript` flavor. The server
45
- // strategy is `{ ...typescriptServerStrategy, flavor: 'react' }`; this mirrors that
46
- // on the client so the `typescript`-gated update branches also run for React
47
- // (otherwise a React edit is received but never applied — the overlay sticks).
48
- const TS_LIKE_FLAVOR = TARGET_FLAVOR === 'typescript' || TARGET_FLAVOR === 'react';
49
- try {
50
- if (TARGET_FLAVOR && !globalThis.__NS_TARGET_FLAVOR__) {
51
- globalThis.__NS_TARGET_FLAVOR__ = TARGET_FLAVOR;
52
- }
53
- }
54
- catch { }
55
- // Define substitution does NOT reach this file (served raw from node_modules),
56
- // so prefer the globalThis seed planted by the entry's defines-seed module —
57
- // the '/src' literal is a last-resort default and is WRONG for 'app/'-rooted
58
- // projects.
59
- const APP_ROOT_VIRTUAL = (typeof __NS_APP_ROOT_VIRTUAL__ === 'string' && __NS_APP_ROOT_VIRTUAL__) || (typeof getGlobalScope().__NS_APP_ROOT_VIRTUAL__ === 'string' && getGlobalScope().__NS_APP_ROOT_VIRTUAL__) || '/src';
60
- const APP_VIRTUAL_WITH_SLASH = APP_ROOT_VIRTUAL.endsWith('/') ? APP_ROOT_VIRTUAL : `${APP_ROOT_VIRTUAL}/`;
61
- const APP_MAIN_ENTRY_SPEC = `${APP_VIRTUAL_WITH_SLASH}app.ts`;
62
- // Policy: by default, let the app's own main entry mount initially; HMR client handles updates/remounts only.
63
- // Flip this to true via global __NS_HMR_ALLOW_INITIAL_MOUNT__ if you need the client to perform the first mount.
64
- const ALLOW_INITIAL_MOUNT = !!globalThis.__NS_HMR_ALLOW_INITIAL_MOUNT__;
65
- // Ensure core aliases are present on globalThis early so that /ns/rt exports resolve to functions
25
+ // Apply once on module evaluation so that /ns/rt exports resolve to functions
66
26
  // before any SFCs are evaluated during HTTP-only dev boot.
67
- function ensureCoreAliasesOnGlobalThis() {
68
- const g = globalThis;
69
- try {
70
- const F = getCore('Frame') || g.Frame;
71
- const A = getCore('Application') || g.Application;
72
- const P = getCore('Page') || g.Page;
73
- // Publish to globalThis if missing
74
- try {
75
- if (F && !g.Frame)
76
- g.Frame = F;
77
- }
78
- catch { }
79
- try {
80
- if (A && (!g.Application || typeof g.Application.run !== 'function' || typeof g.Application.on !== 'function' || typeof g.Application.resetRootView !== 'function')) {
81
- g.Application = A;
82
- }
83
- }
84
- catch { }
85
- try {
86
- if (P && !g.Page)
87
- g.Page = P;
88
- }
89
- catch { }
90
- }
91
- catch { }
92
- }
93
- // Apply once on module evaluation
94
27
  ensureCoreAliasesOnGlobalThis();
95
- // Late-registration bridge for one-shot iOS launch notifications.
28
+ // Late-registration bridge for one-shot iOS launch notifications
29
+ // (see shared/runtime/launch-bridge.ts).
96
30
  //
97
31
  // Under a webpack (or non-HMR vite) build the app bundle evaluates BEFORE
98
- // `UIApplicationMain` finishes launching, so app code that does
32
+ // `UIApplicationMain` finishes launching, so
99
33
  // `Application.ios.addNotificationObserver(UIApplicationDidFinishLaunchingNotification, cb)`
100
- // registers in time and `cb` fires. Under the HTTP dev session UIKit is fully
101
- // launched (the boot placeholder is on screen) long before the app graph
102
- // evaluates — those observers register AFTER the notification fired and are
103
- // never called. Real-world fallout: apps that gate SDK init (auth clients,
104
- // Firebase, Sentry) behind didFinishLaunching silently never initialize, and
105
- // only under HMR.
34
+ // registers in time. Under the HTTP dev session UIKit is fully launched long
35
+ // before the app graph evaluates — those observers register AFTER the
36
+ // notification fired and are never called, so apps that gate SDK init (auth,
37
+ // Firebase, Sentry) behind didFinishLaunching silently never initialize. The
38
+ // bridge wraps `addNotificationObserver` so a post-launch registration for
39
+ // Did/WillFinishLaunching still registers normally AND has its callback
40
+ // invoked on the next macrotask with a synthesized NSNotification.
106
41
  //
107
- // The bridge wraps `addNotificationObserver` so a post-launch registration
108
- // for Did/WillFinishLaunching still registers normally (harmless) AND has its
109
- // callback invoked on the next macrotask with a synthesized NSNotification.
110
- // This client module evaluates before the entry graph (session-bootstrap
111
- // imports it first), so the wrapper is in place before app code runs.
112
- // Launch-notification bridge (see shared/runtime/launch-bridge.ts): the
113
- // DETERMINISTIC install happens in the /__ns_dev__/client bootstrap wrapper
114
- // (it statically imports the /ns/core bridge + the shared installer and runs
115
- // before the app entry). This module-eval attempt and the global hook are
116
- // belt-and-braces for exotic boot paths — this client evaluates async and can
117
- // lose the race against the entry graph, so it must never be the only wrap.
42
+ // The DETERMINISTIC install happens in the /__ns_dev__/client bootstrap
43
+ // wrapper, which runs before the app entry. This module-eval attempt and the
44
+ // global hook are belt-and-braces for exotic boot paths — this client
45
+ // evaluates async and can lose the race against the entry graph, so it must
46
+ // never be the only wrap.
118
47
  function tryInstallLaunchNotificationBridge(attempts, explicitApplication) {
119
48
  let wrappedAny = false;
120
49
  try {
@@ -165,2510 +94,8 @@ function installCssRegister() {
165
94
  catch { }
166
95
  }
167
96
  installCssRegister();
168
- function getHmrOverlayApi() {
169
- try {
170
- return globalThis.__NS_HMR_DEV_OVERLAY__ || null;
171
- }
172
- catch { }
173
- return null;
174
- }
175
- function setConnectionOverlayStage(stage, detail) {
176
- try {
177
- const api = getHmrOverlayApi();
178
- if (api && typeof api.setConnectionStage === 'function') {
179
- api.setConnectionStage(stage, { detail });
180
- }
181
- }
182
- catch { }
183
- }
184
- function hideConnectionOverlay() {
185
- try {
186
- const api = getHmrOverlayApi();
187
- if (api && typeof api.hide === 'function') {
188
- api.hide('healthy');
189
- }
190
- }
191
- catch { }
192
- }
193
- function setUpdateOverlayStage(stage, info) {
194
- try {
195
- const api = getHmrOverlayApi();
196
- if (api && typeof api.setUpdateStage === 'function') {
197
- api.setUpdateStage(stage, info);
198
- }
199
- }
200
- catch { }
201
- }
202
- // Store the listener registry on globalThis (rather than in a module-private
203
- // closure) because in NativeScript the HMR client module and the user app
204
- // modules can resolve to different module instances depending on how the
205
- // dev runtime loads them (HTTP client URL vs. the bundled vendor realm).
206
- // A module-local Set would not be shared across instances; the global one
207
- // is.
208
- function getNsSolidHmrListenerSet() {
209
- const g = getGlobalScope();
210
- let set = g.__ns_solid_hmr_listener_set;
211
- if (!set) {
212
- set = new Set();
213
- g.__ns_solid_hmr_listener_set = set;
214
- }
215
- return set;
216
- }
217
- function nsSolidHmrSubscribe(fn) {
218
- const listeners = getNsSolidHmrListenerSet();
219
- listeners.add(fn);
220
- if (VERBOSE)
221
- console.log('[hmr][solid] subscribe — listeners=', listeners.size);
222
- return () => listeners.delete(fn);
223
- }
224
- function nsSolidHmrEmit(ev) {
225
- const listeners = getNsSolidHmrListenerSet();
226
- if (VERBOSE)
227
- console.log('[hmr][solid] emit listeners=', listeners.size, 'changedFiles=', ev.changedFiles);
228
- for (const fn of Array.from(listeners)) {
229
- try {
230
- fn(ev);
231
- }
232
- catch (err) {
233
- if (VERBOSE)
234
- console.warn('[hmr][solid] listener threw', err);
235
- }
236
- }
237
- }
238
- try {
239
- const g = getGlobalScope();
240
- g.__ns_solid_hmr_subscribe = nsSolidHmrSubscribe;
241
- // Eagerly create the listener set so the global exists at module load time.
242
- getNsSolidHmrListenerSet();
243
- if (VERBOSE)
244
- console.log('[hmr][solid] HMR client loaded. global set=', typeof g.__ns_solid_hmr_subscribe, 'listenerSet=', typeof g.__ns_solid_hmr_listener_set);
245
- }
246
- catch (err) {
247
- console.warn('[hmr][solid] could not install global __ns_solid_hmr_subscribe', err);
248
- }
249
- // Eagerly drive the HMR-applying overlay's 'received' frame as soon
250
- // as the server emits `ns:hmr-pending`, BEFORE the framework-specific
251
- // (`ns:angular-update` / `ns:css-updates`) payload arrives. The
252
- // flavor-specific handler later walks through 'evicting' →
253
- // 'reimporting' → 'rebooting' → 'complete'. Calling 'received' twice
254
- // in the same cycle is safe: the overlay preserves
255
- // `updateCycleStartedAt` when a 'received' frame replaces an existing
256
- // 'received' frame so the minimum-visible window is still timed
257
- // against the FIRST frame.
258
- //
259
- // Soft-fails when the overlay isn't installed (production builds,
260
- // vitest, etc.) or when the user opted out via
261
- // `__NS_HMR_PROGRESS_OVERLAY_ENABLED__ === false`.
262
- import { applyHmrPendingFrame } from './hmr-pending-overlay.js';
263
- function setHmrPendingOverlay(filePath) {
264
- applyHmrPendingFrame(filePath, { getOverlay: getHmrOverlayApi });
265
- }
266
- let connectionOverlayTimer = null;
267
- let connectionOverlayVisible = false;
268
- let hasOpenedHmrSocket = false;
269
- let awaitingHealthyHmrMessage = false;
270
- let pendingConnectionOverlayStage = 'connecting';
271
- let pendingConnectionOverlayDetail = '';
272
- // The stage currently PAINTED on screen (set only when we actually show
273
- // the overlay, not when we merely schedule it). Used to suppress the
274
- // sub-perceptible offline↔reconnecting flicker during the reconnect
275
- // retry loop — see the deferral in `connectHmr`/`tryNext`.
276
- let shownConnectionOverlayStage = null;
277
- // While the terminal 'offline' frame is showing, a fresh reconnect
278
- // attempt that is refused near-instantly (the norm when the dev server
279
- // is down — especially on the Android emulator, where connection-refused
280
- // returns in ~1ms) would flip the overlay to 'reconnecting' and straight
281
- // back to 'offline', producing a jarring 1-frame flicker. We defer the
282
- // 'reconnecting' frame by this much so an instant failure (→ back to
283
- // 'offline') or a success (→ 'synchronizing') cancels it before it ever
284
- // paints; only a genuinely in-flight attempt surfaces 'reconnecting'.
285
- // On iOS real connect attempts exceed this threshold, so the behaviour
286
- // there is unchanged.
287
- const RECONNECTING_OVER_OFFLINE_DELAY_MS = 500;
288
- function clearConnectionOverlayTimer() {
289
- if (connectionOverlayTimer) {
290
- clearTimeout(connectionOverlayTimer);
291
- connectionOverlayTimer = null;
292
- }
293
- }
294
- function showConnectionOverlayNow(stage, detail) {
295
- // Painting a stage now supersedes any scheduled (deferred) stage, so
296
- // cancel the pending timer — otherwise a deferred 'reconnecting' could
297
- // fire moments after we settle back on 'offline' and revive the flicker.
298
- clearConnectionOverlayTimer();
299
- pendingConnectionOverlayStage = stage;
300
- pendingConnectionOverlayDetail = detail || '';
301
- connectionOverlayVisible = true;
302
- shownConnectionOverlayStage = stage;
303
- setConnectionOverlayStage(stage, detail);
304
- }
305
- function scheduleConnectionOverlay(stage, detail, delayMs = 1200) {
306
- pendingConnectionOverlayStage = stage;
307
- pendingConnectionOverlayDetail = detail || '';
308
- clearConnectionOverlayTimer();
309
- connectionOverlayTimer = setTimeout(() => {
310
- showConnectionOverlayNow(pendingConnectionOverlayStage, pendingConnectionOverlayDetail);
311
- }, delayMs);
312
- }
313
- function updateConnectionOverlay(stage, detail) {
314
- pendingConnectionOverlayStage = stage;
315
- pendingConnectionOverlayDetail = detail || '';
316
- if (connectionOverlayVisible) {
317
- showConnectionOverlayNow(stage, detail);
318
- }
319
- }
320
- function markHmrConnectionHealthy() {
321
- awaitingHealthyHmrMessage = false;
322
- clearConnectionOverlayTimer();
323
- shownConnectionOverlayStage = null;
324
- if (connectionOverlayVisible) {
325
- connectionOverlayVisible = false;
326
- hideConnectionOverlay();
327
- }
328
- }
329
- let CLIENT_STRATEGY;
330
- const CLIENT_STRATEGY_READY = TARGET_FLAVOR === 'vue' || TARGET_FLAVOR === 'angular'
331
- ? import(`../frameworks/${TARGET_FLAVOR}/client/strategy.js`)
332
- .then((mod) => {
333
- CLIENT_STRATEGY = mod && mod[`${TARGET_FLAVOR}ClientStrategy`];
334
- if (VERBOSE)
335
- console.log('[hmr-client] client strategy loaded for flavor:', TARGET_FLAVOR);
336
- CLIENT_STRATEGY?.install();
337
- })
338
- .catch((err) => {
339
- console.warn('[hmr-client] failed to load client strategy for', TARGET_FLAVOR, err);
340
- })
341
- : Promise.resolve();
342
- // Track whether we've mounted an initial app root yet in HTTP-only boot
343
- let initialMounted = !!globalThis.__NS_HMR_BOOT_COMPLETE__;
344
- // Prevent duplicate initial-mount scheduling across rapid full-graph broadcasts and re-evaluations
345
- let initialMounting = !!globalThis.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__;
346
- // Track whether the first full-graph has been received. Before the full-graph,
347
- // delta messages are just the server discovering modules during initial boot —
348
- // NOT actual code changes. Re-imports must be gated behind this flag.
349
- let hasReceivedFullGraph = false;
350
- // TypeScript flavor: track registry modules and inferred main id
351
- let tsModuleSet = null;
352
- let tsMainId = null;
353
- const changedQueue = [];
354
- let processingQueue = false;
355
- let processingPromise = null;
356
- // Detect whether the early placeholder root is still active on screen
357
- function isPlaceholderActive() {
358
- try {
359
- const g = getGlobalScope();
360
- if (g.__NS_DEV_PLACEHOLDER_ROOT_VIEW__)
361
- return true;
362
- if (g.__NS_DEV_PLACEHOLDER_ROOT_EARLY__)
363
- return true;
364
- }
365
- catch { }
366
- return false;
367
- }
368
- // Navigation queue removed: we navigate immediately or throw with a clear error
369
- // Robust navigation fallback: create a sub-app and mount it on a new Page, then navigate there.
370
- // __nsNavigateWithSubApp removed: no navigation fallbacks are used
371
- function applyFullGraph(payload) {
372
- if (typeof payload.version !== 'number' || !Array.isArray(payload.modules))
373
- return;
374
- graph.clear();
375
- payload.modules.forEach((m) => {
376
- if (m && m.id)
377
- graph.set(m.id, { id: m.id, deps: m.deps || [], hash: m.hash || '' });
378
- });
379
- setGraphVersion(payload.version);
380
- if (VERBOSE)
381
- console.log('[hmr][graph] full graph applied version', getGraphVersion(), 'modules=', graph.size);
382
- // Guarded initial mount rescue: if app hasn't replaced the placeholder shortly after graph arrives,
383
- // perform a one-time mount. This waits briefly to let the app's main entry start() run first to avoid double mounts.
384
- // TypeScript flavor: skip the rescue entirely. The HTTP boot will load main.ts which
385
- // calls Application.run() (patched to resetRootView) — the rescue is redundant and
386
- // causes a double-mount race (rescue fires at 450ms, then main.ts fires ~1s later,
387
- // causing a visual flash and leaving the app in an inconsistent state).
388
- try {
389
- const g = getGlobalScope();
390
- const bootDone = !!g.__NS_HMR_BOOT_COMPLETE__;
391
- if (!bootDone && !initialMounted && !initialMounting && !g.__NS_HMR_RESCUE_SCHEDULED__ && !TS_LIKE_FLAVOR) {
392
- // simple snapshot helpers
393
- const getTopmost = () => {
394
- try {
395
- const F = getCore('Frame') || g.Frame;
396
- return F?.topmost?.() || null;
397
- }
398
- catch {
399
- return null;
400
- }
401
- };
402
- const isPlaceholderView = (v) => {
403
- try {
404
- if (!v)
405
- return false;
406
- if (v === (g.__NS_DEV_PLACEHOLDER_ROOT_VIEW__ || null))
407
- return true;
408
- return !!v.__ns_dev_placeholder;
409
- }
410
- catch {
411
- return false;
412
- }
413
- };
414
- const hasRealRoot = () => {
415
- try {
416
- const fr = getTopmost();
417
- if (!fr)
418
- return false;
419
- if (isPlaceholderView(fr))
420
- return false;
421
- const pg = fr.currentPage || fr._currentEntry?.resolvedPage;
422
- if (!pg)
423
- return false;
424
- if (isPlaceholderView(pg))
425
- return false;
426
- return true;
427
- }
428
- catch {
429
- return false;
430
- }
431
- };
432
- try {
433
- g.__NS_HMR_RESCUE_SCHEDULED__ = true;
434
- }
435
- catch { }
436
- setTimeout(() => {
437
- try {
438
- if (g.__NS_HMR_BOOT_COMPLETE__)
439
- return; // app already mounted
440
- if (hasRealRoot()) {
441
- markDevBootComplete();
442
- if (VERBOSE)
443
- console.log('[hmr][init] detected real root after delay; skipping client initial mount');
444
- // Detach placeholder handler if still present
445
- try {
446
- const restore = g.__NS_DEV_RESTORE_PLACEHOLDER__;
447
- if (typeof restore === 'function')
448
- restore();
449
- }
450
- catch { }
451
- return;
452
- }
453
- // If placeholder still active and no real root, try a one-time gentle initial mount.
454
- // Vue: prefer SFCs; TypeScript: import the app main TS module and let performResetRoot handle it once.
455
- const placeholderActive = isPlaceholderActive();
456
- if (!placeholderActive)
457
- return;
458
- if (VERBOSE)
459
- console.log('[hmr][init] placeholder persists after delay; evaluating rescue policy');
460
- // Flavor-specific rescue handling
461
- if (TS_LIKE_FLAVOR) {
462
- // For TS apps, perform a one-time resetRootView to the conventional
463
- // app root module. This mimics what Application.run would do and
464
- // replaces the placeholder with the real UI without trying to
465
- // treat app.ts as a component.
466
- try {
467
- const App = getCore('Application') || g.Application;
468
- if (App && typeof App.resetRootView === 'function') {
469
- if (VERBOSE)
470
- console.log('[hmr][init] TS flavor: performing rescue resetRootView to moduleName=app-root');
471
- initialMounting = true;
472
- try {
473
- g.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = true;
474
- }
475
- catch { }
476
- App.resetRootView({ moduleName: 'app-root' });
477
- initialMounted = true;
478
- markDevBootComplete();
479
- if (VERBOSE)
480
- console.log('[hmr][init] TS rescue resetRootView complete');
481
- }
482
- else if (VERBOSE) {
483
- console.warn('[hmr][init] TS flavor: Application.resetRootView unavailable; cannot perform rescue');
484
- }
485
- }
486
- catch (e) {
487
- console.warn('[hmr][init] TS rescue resetRootView failed', e);
488
- }
489
- finally {
490
- initialMounting = false;
491
- try {
492
- g.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = false;
493
- }
494
- catch { }
495
- }
496
- return;
497
- }
498
- const candidate = CLIENT_STRATEGY?.selectMountCandidate?.({ graph, appMainEntrySpec: APP_MAIN_ENTRY_SPEC }) ?? null;
499
- if (!candidate)
500
- return;
501
- initialMounting = true;
502
- try {
503
- g.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = true;
504
- }
505
- catch { }
506
- (async () => {
507
- try {
508
- let comp = null;
509
- if (CLIENT_STRATEGY?.loadComponentForMount) {
510
- comp = await CLIENT_STRATEGY.loadComponentForMount(candidate, 'initial_mount_rescue');
511
- }
512
- if (!comp)
513
- return;
514
- const ok = await performResetRoot(comp);
515
- if (ok) {
516
- initialMounted = true;
517
- markDevBootComplete();
518
- if (VERBOSE)
519
- console.log('[hmr][init] initial mount (rescue) complete');
520
- }
521
- }
522
- catch (e) {
523
- console.warn('[hmr][init] initial mount (rescue) error', e);
524
- }
525
- finally {
526
- initialMounting = false;
527
- try {
528
- g.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = false;
529
- }
530
- catch { }
531
- }
532
- })();
533
- }
534
- catch { }
535
- }, 450);
536
- }
537
- }
538
- catch { }
539
- // On first full graph, if we have not mounted yet, attempt an initial mount
540
- // by choosing a likely root component for the active flavor and performing a resetRootView with it.
541
- try {
542
- // Short-circuit if boot is complete or an initial mount is already underway (across realms/evals)
543
- const bootDone = !!globalThis.__NS_HMR_BOOT_COMPLETE__;
544
- const bootInProgress = !!globalThis.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ || initialMounting;
545
- // Only allow initial mount when explicitly enabled. Rely on the app's own main entry start() for the first mount
546
- // to avoid double-mount races that can cause duplicate navigation logs.
547
- if (ALLOW_INITIAL_MOUNT && !initialMounted && !bootDone && !bootInProgress && !getCurrentApp() && !getRootFrame()) {
548
- if (TS_LIKE_FLAVOR) {
549
- // For TS flavor, do not perform client-driven initial mount; rely on Application.run.
550
- return;
551
- }
552
- const candidate = CLIENT_STRATEGY?.selectMountCandidate?.({ graph, appMainEntrySpec: APP_MAIN_ENTRY_SPEC }) ?? null;
553
- if (candidate) {
554
- // Mark initial-mount in progress (both module-local and global) BEFORE scheduling async work
555
- initialMounting = true;
556
- try {
557
- globalThis.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = true;
558
- }
559
- catch { }
560
- (async () => {
561
- try {
562
- if (VERBOSE)
563
- console.log('[hmr][init] mounting initial root from', candidate, 'flavor=', TARGET_FLAVOR);
564
- // Android-only: avoid racing entry-runtime reset and Activity bring-up
565
- try {
566
- const g = getGlobalScope();
567
- const App = getCore('Application') || g.Application;
568
- const isAndroid = !!(App && App.android !== undefined);
569
- if (isAndroid) {
570
- const ready = async (ms = 8000, step = 60) => {
571
- const start = Date.now();
572
- const ok = () => {
573
- try {
574
- const a = App.android;
575
- const act = a && (a.foregroundActivity || a.startActivity);
576
- const inProg = !!g.__NS_DEV_RESET_IN_PROGRESS__;
577
- return !!act && !inProg;
578
- }
579
- catch {
580
- return false;
581
- }
582
- };
583
- while (Date.now() - start < ms) {
584
- if (ok())
585
- return true;
586
- await new Promise((r) => setTimeout(r, step));
587
- }
588
- return ok();
589
- };
590
- const ok = await ready(8000, 60);
591
- if (!ok && VERBOSE)
592
- console.warn('[hmr][init] proceeding without explicit boot-ready signal (timeout)');
593
- }
594
- }
595
- catch { }
596
- let comp = null;
597
- if (TS_LIKE_FLAVOR) {
598
- try {
599
- const url = await requestModuleFromServer(candidate);
600
- const mod = await import(/* @vite-ignore */ url);
601
- comp = mod && (mod.default || mod);
602
- }
603
- catch (e) {
604
- if (VERBOSE)
605
- console.warn('[hmr][init] TS initial mount failed to import', candidate, e);
606
- }
607
- }
608
- else if (CLIENT_STRATEGY?.loadComponentForMount) {
609
- comp = await CLIENT_STRATEGY.loadComponentForMount(candidate, 'initial_mount');
610
- }
611
- if (comp) {
612
- const ok = await performResetRoot(comp);
613
- if (ok) {
614
- initialMounted = true;
615
- markDevBootComplete();
616
- if (VERBOSE)
617
- console.log('[hmr][init] initial mount complete');
618
- }
619
- else if (VERBOSE) {
620
- console.warn('[hmr][init] initial mount did not verify; will rely on subsequent retries');
621
- }
622
- }
623
- else if (VERBOSE) {
624
- console.warn('[hmr][init] failed to load initial component from', candidate);
625
- }
626
- }
627
- catch (e) {
628
- console.warn('[hmr][init] initial mount error', e);
629
- }
630
- finally {
631
- // Clear in-progress flag regardless of outcome to allow future retries if needed
632
- initialMounting = false;
633
- try {
634
- globalThis.__NS_HMR_INITIAL_MOUNT_IN_PROGRESS__ = false;
635
- }
636
- catch { }
637
- }
638
- })();
639
- }
640
- else if (VERBOSE) {
641
- console.warn('[hmr][init] no component found in graph to mount initially for flavor', TARGET_FLAVOR);
642
- }
643
- }
644
- }
645
- catch { }
646
- }
647
- function applyDelta(payload) {
648
- // If versions are out of sync, request a full graph resync, but still
649
- // opportunistically queue the changed ids so the client can react once
650
- // the resync arrives. This is especially important for simple TS flavors
651
- // where we only need a signal that "something changed" to trigger a
652
- // resetRootView-driven hot update.
653
- const currentVersion = getGraphVersion();
654
- const versionMatches = payload.baseVersion === currentVersion;
655
- if (!versionMatches) {
656
- if (VERBOSE)
657
- console.warn('[hmr][graph] version mismatch requesting resync', payload.baseVersion, currentVersion);
658
- try {
659
- hmrSocket?.send(JSON.stringify({ type: 'ns:hmr-resync-request' }));
660
- }
661
- catch { }
662
- }
663
- if (versionMatches) {
664
- setGraphVersion(payload.newVersion);
665
- }
666
- const changed = payload.changed || [];
667
- CLIENT_STRATEGY?.recordPayloadChanges?.(changed, getGraphVersion());
668
- (payload.changed || []).forEach((m) => {
669
- if (!m || !m.id)
670
- return;
671
- // Always update the local graph view with the announced module metadata
672
- graph.set(m.id, { id: m.id, deps: m.deps || [], hash: m.hash || '' });
673
- });
674
- (payload.removed || []).forEach((r) => {
675
- graph.delete(r);
676
- });
677
- if (VERBOSE)
678
- console.log('[hmr][graph] delta applied newVersion', getGraphVersion(), 'changed=', (payload.changed || []).length, 'removed=', (payload.removed || []).length, 'baseVersion=', payload.baseVersion);
679
- // Queue evaluation of changed modules (placeholder pipeline)
680
- if (payload.changed?.length) {
681
- // Gate: Before the first full-graph is received, delta messages are the server
682
- // discovering modules during initial boot — NOT actual code changes. The entry-runtime
683
- // already loaded all modules; re-importing them would cause duplicate Application.run(),
684
- // router initialization, and modal conflicts. Only queue re-imports after the first
685
- // full-graph confirms the graph is synced and subsequent deltas are real changes.
686
- if (!hasReceivedFullGraph) {
687
- if (VERBOSE)
688
- console.log('[hmr][delta] skipping re-import queue (initial graph build, no full-graph yet)');
689
- return;
690
- }
691
- // HARD SUPPRESS: the very first delta (baseVersion 0) commonly includes the app main entry which is already evaluated during bootstrap.
692
- // Importing it again with a cache-bust often produces a spurious module-not-found (timestamp param treated as distinct file).
693
- const isInitial = payload.baseVersion === 0;
694
- // Filter out virtual helper ids (e.g. '\0plugin-vue:export-helper') which we do not evaluate directly
695
- const realIds = payload.changed.map((c) => c.id).filter((id) => !/^\0|^\/\0|plugin-vue:export-helper/.test(id));
696
- // Proactively prefetch core/src deps for any changed .vue SFCs (before registry update triggers reset)
697
- try {
698
- for (const entry of payload.changed || []) {
699
- if (!entry || !/\.vue$/i.test(entry.id))
700
- continue;
701
- const deps = Array.isArray(entry.deps) ? entry.deps : [];
702
- const prefetchTargets = deps.filter((d) => /^\//.test(d) && !/node_modules/.test(d) && !/\.vue$/i.test(d));
703
- if (prefetchTargets.length && VERBOSE)
704
- console.log('[hmr][prefetch] SFC deps', entry.id, '->', prefetchTargets);
705
- for (const dep of prefetchTargets) {
706
- const norm = normalizeSpec(dep);
707
- // Skip if we already wrote it (basic heuristic: moduleFetchCache has it or path exists in Documents/_ns_hmr)
708
- if (moduleFetchCache.has(norm))
709
- continue;
710
- // Fire and forget; ensure rejection does not break HMR pipeline
711
- requestModuleFromServer(norm).catch(() => { });
712
- }
713
- }
714
- }
715
- catch (e) {
716
- if (VERBOSE)
717
- console.warn('[hmr][prefetch] failed', e);
718
- }
719
- const isAppMainEntryId = (value) => value.endsWith(APP_MAIN_ENTRY_SPEC);
720
- for (const id of realIds) {
721
- // We now rely on SFC registry update events to trigger root resets for .vue files directly
722
- if (/\.vue$/i.test(id)) {
723
- if (VERBOSE)
724
- console.log('[hmr][delta] skipping queue for .vue id; will handle on registry update', id);
725
- continue;
726
- }
727
- if (isInitial && isAppMainEntryId(id)) {
728
- if (VERBOSE)
729
- console.log(`[hmr][delta] suppressing initial ${APP_MAIN_ENTRY_SPEC} evaluation`);
730
- continue;
731
- }
732
- if (isAppMainEntryId(id)) {
733
- try {
734
- const exists = getGlobalScope().require?.(id) || globalThis.__nsGetModuleExports?.(id);
735
- if (!exists && VERBOSE)
736
- console.log(`[hmr][delta] skipping unresolved ${APP_MAIN_ENTRY_SPEC} change`);
737
- if (!exists)
738
- continue;
739
- }
740
- catch {
741
- /* ignore */
742
- }
743
- }
744
- changedQueue.push(id);
745
- }
746
- if (changedQueue.length)
747
- processQueue();
748
- }
749
- }
750
- // Deterministic navigation using the current Vue app instance rather than vendor-held rootApp.
751
- function __nsNavigateUsingApp(comp, opts = {}) {
752
- const g = getGlobalScope();
753
- CLIENT_STRATEGY?.beforeNavigateBuild?.();
754
- const AppFactory = g.createApp;
755
- const RootCtor = g.NSVRoot;
756
- if (typeof AppFactory !== 'function' || typeof RootCtor !== 'function') {
757
- throw new Error('Vue runtime not initialized');
758
- }
759
- try {
760
- const top = (g.Frame && g.Frame.topmost && g.Frame.topmost()) || null;
761
- const ctor = top && top.constructor && top.constructor.name;
762
- if (VERBOSE)
763
- console.log('[app-nav] begin', {
764
- hmrRealm: g.__NS_HMR_REALM__ || 'unknown',
765
- rtRealm: g.__NS_RT_REALM__ || 'unknown',
766
- topCtor: ctor,
767
- hasTop: !!top,
768
- });
769
- }
770
- catch { }
771
- // Build a fresh Page each time the factory is invoked to avoid reusing a Page instance
772
- // across fragment recreations (Android) or multiple frame attachments.
773
- const buildTarget = () => {
774
- const existingApp = getCurrentApp();
775
- const baseProvides = (existingApp && existingApp._context && existingApp._context.provides) || {};
776
- // Forward `opts.props` as Vue's rootProps so `$navigateTo(Comp, { props: { … } })`
777
- // reaches the destination component. nativescript-vue's stock `$navigateTo`
778
- // does the same via `createNativeView(target, options?.props, …)` →
779
- // `renderer.createApp(component, props)`. Dropping props here would surface
780
- // at the destination as `[Vue warn]: Missing required prop` and any
781
- // required-prop component would render with `undefined` bindings.
782
- const app = AppFactory(normalizeComponent(comp, comp && (comp.__name || comp.name)), opts && opts.props);
783
- CLIENT_STRATEGY?.onNavAppCreated?.(app);
784
- try {
785
- const registry = g.__nsVendorRegistry;
786
- const req = registry?.get ? g.__nsVendorRequire || g.__nsRequire || g.require : g.__nsRequire || g.require;
787
- let rh = null;
788
- if (registry && registry.has('nativescript-vue/dist/runtimeHelpers'))
789
- rh = registry.get('nativescript-vue/dist/runtimeHelpers');
790
- if (!rh && typeof req === 'function') {
791
- try {
792
- rh = req('nativescript-vue/dist/runtimeHelpers');
793
- }
794
- catch { }
795
- }
796
- const setRootApp = rh && (rh.setRootApp || rh.default?.setRootApp);
797
- if (typeof setRootApp === 'function')
798
- setRootApp(app);
799
- }
800
- catch { }
801
- try {
802
- const ctx = app?._context;
803
- if (ctx) {
804
- const prov = (ctx.provides || (ctx.provides = {}));
805
- Object.getOwnPropertyNames(baseProvides).forEach((k) => {
806
- if (!Object.prototype.hasOwnProperty.call(prov, k))
807
- prov[k] = baseProvides[k];
808
- });
809
- Object.getOwnPropertySymbols(baseProvides).forEach((s) => {
810
- if (!Object.prototype.hasOwnProperty.call(prov, s))
811
- prov[s] = baseProvides[s];
812
- });
813
- }
814
- }
815
- catch { }
816
- const root = new RootCtor();
817
- const vm = typeof app.runWithContext === 'function' ? app.runWithContext(() => app.mount(root)) : app.mount(root);
818
- setCurrentApp(app);
819
- const el = vm?.$el;
820
- const nativeView = el?.nativeView;
821
- if (!nativeView)
822
- throw new Error('navigation mount did not yield a nativeView');
823
- const P = getCore('Page');
824
- const ctorName = String(nativeView?.constructor?.name || '').replace(/^_+/, '');
825
- if (ctorName === 'Page' || /^Page(\$\d+)?$/.test(ctorName)) {
826
- return nativeView;
827
- }
828
- if (typeof P === 'function') {
829
- const pg = new P();
830
- pg.content = nativeView;
831
- // Hide default ActionBar for wrapped views to avoid double bars
832
- try {
833
- pg.actionBarHidden = true;
834
- }
835
- catch { }
836
- return pg;
837
- }
838
- return nativeView; // fallback
839
- };
840
- let frame = opts && opts.frame ? opts.frame : getRootFrame();
841
- if (!frame) {
842
- const F = getCore('Frame');
843
- frame = F && typeof F.topmost === 'function' ? F.topmost() : null;
844
- }
845
- if (!frame) {
846
- const GApp = getCore('Application') || g.Application;
847
- const F = getCore('Frame');
848
- if (typeof GApp?.resetRootView === 'function' && typeof F === 'function') {
849
- GApp.resetRootView({
850
- create: () => {
851
- const fr = new F();
852
- const navEntry = {
853
- create: () => buildTarget(),
854
- clearHistory: true,
855
- animated: false,
856
- };
857
- try {
858
- fr.navigate(navEntry);
859
- }
860
- catch { }
861
- setRootFrame(fr);
862
- return fr;
863
- },
864
- });
865
- return undefined;
866
- }
867
- throw new Error('Application.resetRootView unavailable');
868
- }
869
- const navEntry = { create: () => buildTarget(), ...(opts || {}) };
870
- frame.navigate(navEntry);
871
- return undefined;
872
- }
873
- // Expose deterministic app navigation globally so /ns/rt can guarantee single-path navigation
874
- try {
875
- globalThis.__nsNavigateUsingApp = __nsNavigateUsingApp;
876
- }
877
- catch { }
878
- const openModalRecords = [];
879
- let modalTrackingInstalled = false;
880
- /**
881
- * Map a served/graph module id (e.g. `/app/modal-page.xml`) to its app-root
882
- * relative path (`modal-page.xml`). Single mapping point — the raw-asset
883
- * re-registration, page-navigation targets, and modal matching all derive
884
- * from this; keep them in sync by construction.
885
- */
886
- function toAppRelativePath(id) {
887
- try {
888
- const spec = normalizeSpec(id);
889
- const appVirtual = APP_VIRTUAL_WITH_SLASH.replace(/^\//, '');
890
- let relPath = spec.startsWith('/') ? spec.slice(1) : spec;
891
- if (relPath.startsWith(appVirtual))
892
- relPath = relPath.slice(appVirtual.length);
893
- return relPath || null;
894
- }
895
- catch {
896
- return null;
897
- }
898
- }
899
- /** App-root relative module name (no extension) for page-shaped files, else null. */
900
- function toAppModuleName(id) {
901
- const relPath = toAppRelativePath(id);
902
- if (!relPath || !/\.(xml|ts|js)$/i.test(relPath))
903
- return null;
904
- return relPath.replace(/\.(xml|ts|js)$/i, '');
905
- }
906
- function ensureModalTracking() {
907
- if (modalTrackingInstalled)
908
- return;
909
- try {
910
- const View = getCore('View') || getGlobalScope().View;
911
- const proto = View?.prototype;
912
- if (!proto || typeof proto.showModal !== 'function')
913
- return;
914
- const orig = proto.showModal;
915
- if (orig.__nsHmrModalTracked) {
916
- modalTrackingInstalled = true;
917
- return;
918
- }
919
- const wrapped = function (...args) {
920
- const result = orig.apply(this, args);
921
- try {
922
- if (typeof args[0] === 'string' && result) {
923
- // Mirror core's getModalOptions arg shapes: (moduleName, options)
924
- // or the deprecated positional form.
925
- const options = args.length === 2 && args[1] && typeof args[1] === 'object' ? args[1] : { context: args[1], closeCallback: args[2], fullscreen: args[3], animated: args[4], stretched: args[5] };
926
- const moduleName = String(args[0])
927
- .replace(/^\.\//, '')
928
- .replace(/\.(xml|ts|js)$/i, '');
929
- openModalRecords.push({ moduleName, options, parent: this, modal: result });
930
- if (VERBOSE)
931
- console.log('[hmr][modal] tracked open modal', moduleName);
932
- }
933
- }
934
- catch { }
935
- return result;
936
- };
937
- wrapped.__nsHmrModalTracked = true;
938
- proto.showModal = wrapped;
939
- modalTrackingInstalled = true;
940
- }
941
- catch (e) {
942
- if (VERBOSE)
943
- console.warn('[hmr][modal] tracking install failed', e);
944
- }
945
- }
946
- /**
947
- * Enumerate the modals that are currently presented AND were opened by module
948
- * name, with everything needed to re-present them.
949
- *
950
- * Source of truth is core's live modal stack (`_getRootModalViews()`):
951
- * - `modal._moduleName` — set by the Builder on every createViewFromEntry
952
- * view (longstanding, used by livesync), so available on any core.
953
- * - `modal._modalOptions` — the original ShowModalOptions, stored by core's
954
- * `_showNativeModalView` (newer cores). For older cores the showModal
955
- * wrap's records (see ensureModalTracking) fill the gap.
956
- * - `modal._modalParent` — the presenting view.
957
- * Stale wrap records are pruned against the live stack while we're here.
958
- */
959
- function getOpenStringModuleModals() {
960
- const out = [];
961
- try {
962
- const App = getCore('Application');
963
- const root = App?.getRootView?.() || App?._rootView;
964
- const stack = root?._getRootModalViews?.() || [];
965
- // Prune wrap records whose modal is gone (keeps the fallback list small).
966
- for (let i = openModalRecords.length - 1; i >= 0; i--) {
967
- if (!stack.includes(openModalRecords[i].modal)) {
968
- openModalRecords.splice(i, 1);
969
- }
970
- }
971
- for (const modal of stack) {
972
- const record = openModalRecords.find((r) => r.modal === modal);
973
- const rawModuleName = typeof modal?._moduleName === 'string' && modal._moduleName ? modal._moduleName : record?.moduleName;
974
- const parent = modal?._modalParent || record?.parent;
975
- const options = modal?._modalOptions || record?.options;
976
- if (!rawModuleName || !parent)
977
- continue;
978
- const moduleName = String(rawModuleName)
979
- .replace(/^\.\//, '')
980
- .replace(/\.(xml|ts|js)$/i, '');
981
- out.push({ moduleName, options, parent, modal });
982
- }
983
- }
984
- catch (e) {
985
- if (VERBOSE)
986
- console.warn('[hmr][modal] open-modal enumeration failed', e);
987
- }
988
- return out;
989
- }
990
- /**
991
- * Close and re-present an open modal so it rebuilds from the freshly
992
- * re-registered XML/code-behind. Core clears the modal stack synchronously on
993
- * close but the NATIVE dismissal completes asynchronously; iOS refuses a
994
- * present while a dismissal is in flight. Newer cores fire `closedModally` on
995
- * the modal at exactly that completion point — preferred signal. Older cores
996
- * fall back to polling `isLoaded` (flipped by `_tearDownUI` in the same
997
- * completion callback).
998
- */
999
- async function reshowOpenModal(record) {
1000
- const { parent, modal, moduleName, options } = record;
1001
- await new Promise((resolve) => {
1002
- let settled = false;
1003
- const finish = () => {
1004
- if (!settled) {
1005
- settled = true;
1006
- resolve();
1007
- }
1008
- };
1009
- let eventArmed = false;
1010
- try {
1011
- if (typeof modal.once === 'function') {
1012
- modal.once('closedModally', finish);
1013
- eventArmed = true;
1014
- }
1015
- }
1016
- catch { }
1017
- // Poll fallback (also the safety net if the event never fires —
1018
- // e.g. an interactive-dismiss cancellation).
1019
- const deadline = Date.now() + 2000;
1020
- const poll = () => {
1021
- if (settled)
1022
- return;
1023
- let stillLoaded = false;
1024
- try {
1025
- stillLoaded = !!modal.isLoaded;
1026
- }
1027
- catch { }
1028
- if ((!eventArmed && !stillLoaded) || Date.now() > deadline) {
1029
- finish();
1030
- return;
1031
- }
1032
- setTimeout(poll, 50);
1033
- };
1034
- setTimeout(poll, 50);
1035
- try {
1036
- modal.closeModal();
1037
- }
1038
- catch (e) {
1039
- if (VERBOSE)
1040
- console.warn('[hmr][modal] close failed for', moduleName, e);
1041
- finish();
1042
- }
1043
- });
1044
- // One settle beat so the platform finishes releasing the presentation
1045
- // before the new present begins.
1046
- await new Promise((resolve) => setTimeout(resolve, 100));
1047
- try {
1048
- parent.showModal(moduleName, { ...(options || {}), animated: false });
1049
- if (VERBOSE)
1050
- console.log('[hmr][modal] re-presented', moduleName);
1051
- }
1052
- catch (e) {
1053
- console.warn('[hmr][modal] re-present failed for', moduleName, e);
1054
- }
1055
- }
1056
- async function processQueue() {
1057
- if (!globalThis.__NS_HMR_BOOT_COMPLETE__) {
1058
- if (VERBOSE)
1059
- console.log('[hmr][gate] deferring HMR eval until boot complete');
1060
- setTimeout(() => {
1061
- try {
1062
- processQueue();
1063
- }
1064
- catch { }
1065
- }, 150);
1066
- return Promise.resolve();
1067
- }
1068
- if (processingQueue)
1069
- return processingPromise || Promise.resolve();
1070
- processingQueue = true;
1071
- processingPromise = (async () => {
1072
- try {
1073
- // Simple deterministic drain of the queue. We currently focus on TS flavor
1074
- // by re-importing changed modules (to refresh their HTTP ESM copies) and
1075
- // then performing a root reset so the UI reflects the new code.
1076
- const seen = new Set();
1077
- const drained = [];
1078
- while (changedQueue.length) {
1079
- const id = changedQueue.shift();
1080
- if (!id || typeof id !== 'string')
1081
- continue;
1082
- if (seen.has(id))
1083
- continue;
1084
- seen.add(id);
1085
- drained.push(id);
1086
- }
1087
- if (!drained.length)
1088
- return;
1089
- if (VERBOSE)
1090
- console.log('[hmr][queue] processing changed ids', drained);
1091
- // Track wall-clock so the 'complete' frame can show a meaningful
1092
- // total. Only the Solid + TypeScript flavors drive the overlay
1093
- // from here; Angular has its own flow inside
1094
- // `frameworks/angular/client/index.ts`.
1095
- const tQueueStart = Date.now();
1096
- const driveSolidOverlay = TARGET_FLAVOR === 'solid';
1097
- // Explicit eviction step.
1098
- //
1099
- // Without explicit eviction the upcoming `import(url)` would
1100
- // resolve via V8's `g_moduleRegistry` and return the cached
1101
- // stale module — making the queue drain a silent no-op for
1102
- // every save after the first. Eviction also arms the runtime's
1103
- // bust-next-fetch nonce so the re-fetch defeats OS-level HTTP
1104
- // caches; the re-import below then uses the STABLE canonical
1105
- // URL (module identity IS the URL). node_modules and virtual
1106
- // specs are filtered out by `buildEvictionUrls` so vendor
1107
- // modules stay hot.
1108
- if (driveSolidOverlay) {
1109
- setUpdateOverlayStage('evicting', {
1110
- detail: drained.length === 1 ? `Invalidating ${drained[0]}` : `Invalidating ${drained.length} modules`,
1111
- });
1112
- }
1113
- const evictUrls = buildEvictionUrls(drained);
1114
- const evicted = invalidateModulesByUrls(evictUrls);
1115
- if (VERBOSE)
1116
- console.log(`[hmr][queue] eviction count=${evictUrls.length} ok=${evicted}`);
1117
- // Evaluate changed modules best-effort; failures shouldn't completely break HMR.
1118
- if (driveSolidOverlay) {
1119
- setUpdateOverlayStage('reimporting', {
1120
- detail: drained.length === 1 ? `Re-importing ${drained[0]}` : `Re-importing ${drained.length} modules`,
1121
- });
1122
- }
1123
- let reimportFailures = 0;
1124
- for (const id of drained) {
1125
- try {
1126
- const spec = normalizeSpec(id);
1127
- const url = await requestModuleFromServer(spec);
1128
- if (!url)
1129
- continue;
1130
- if (VERBOSE)
1131
- console.log('[hmr][queue] re-import', { id, spec, url });
1132
- const mod = await import(/* @vite-ignore */ url);
1133
- // TS/XML flavor: refresh the bundler module registry with the fresh
1134
- // exports so Builder.createViewFromEntry / loadModule('<page>')
1135
- // resolves the NEW code-behind (tap handlers, page events) instead
1136
- // of the stale module captured in the boot bundle. Without this,
1137
- // XML re-renders pick up new markup but keep old behavior.
1138
- if (TS_LIKE_FLAVOR && mod && /\.(ts|js)$/i.test(id)) {
1139
- try {
1140
- const g = getGlobalScope();
1141
- const moduleName = toAppModuleName(id);
1142
- if (moduleName && typeof g.registerModule === 'function') {
1143
- g.registerModule(moduleName, () => mod);
1144
- g.registerModule('./' + moduleName, () => mod);
1145
- if (VERBOSE)
1146
- console.log('[hmr][queue] re-registered code-behind', moduleName);
1147
- }
1148
- }
1149
- catch (e) {
1150
- if (VERBOSE)
1151
- console.warn('[hmr][queue] code-behind re-register failed for', id, e);
1152
- }
1153
- }
1154
- }
1155
- catch (e) {
1156
- // Never silent: a failed re-import means the device may keep
1157
- // running the previous module body, so always surface it (not
1158
- // verbose-gated) — otherwise the overlay reports success while
1159
- // the app runs stale code.
1160
- reimportFailures++;
1161
- console.warn('[hmr][queue] re-import FAILED for', id, '-', e?.message ?? e);
1162
- }
1163
- }
1164
- if (reimportFailures > 0) {
1165
- console.warn(`[hmr][queue] ${reimportFailures}/${drained.length} module(s) failed to re-import; the applied update may be incomplete.`);
1166
- }
1167
- // After evaluating the batch, perform flavor-specific UI refresh.
1168
- switch (TARGET_FLAVOR) {
1169
- case 'vue':
1170
- // graph + performResetRoot + getOverlay let the Vue strategy
1171
- // propagate non-SFC dep changes to the nearest `.vue` boundary
1172
- // and remount it (see `propagateDepChangeToSfcBoundary`).
1173
- await CLIENT_STRATEGY?.refreshAfterBatch?.(drained, { setUpdateOverlayStage, startedAt: tQueueStart, graph, performResetRoot, getOverlay: getHmrOverlayApi });
1174
- break;
1175
- case 'react': {
1176
- // React has no Fast Refresh, and (like Solid) mounts a dominative
1177
- // document root via `startReactApp` rather than an `app-root`
1178
- // module — so the TypeScript `resetRootView({moduleName:'app-root'})`
1179
- // path doesn't apply. The changed modules were already re-imported
1180
- // into the device cache above; the per-page remount is driven by the
1181
- // app's `__NS_HMR_ON_UPDATE__` hook (see
1182
- // `@nativescript/tanstack-router/react`'s `subscribeReactHmrRemount`),
1183
- // which fires right after this queue drains. Here we only mark the
1184
- // overlay complete so it doesn't stick at 'received' (5%).
1185
- setUpdateOverlayStage('complete', {
1186
- detail: `Total ${Math.max(0, Date.now() - tQueueStart)}ms`,
1187
- });
1188
- break;
1189
- }
1190
- case 'solid': {
1191
- // Boundaries discovered in this HMR cycle (tsx files reachable
1192
- // via the reverse import graph from any changed file, plus route
1193
- // files reachable from any tsx start point). Declared at the top
1194
- // of the case block so the emit step below can include the
1195
- // complete set in the listener event — framework integrations
1196
- // use it to map route boundaries → fresh component references.
1197
- const boundaries = new Set();
1198
- // FULL reverse-import chain from every changed file up to the app
1199
- // entry (all importers, transitively — not just tsx ones). Emitted
1200
- // as `ev.ancestors` so app-level remount helpers can evict the
1201
- // whole chain: re-importing only the root would resolve cached
1202
- // intermediates and hand the fresh root a stale subtree.
1203
- const ancestors = new Set();
1204
- // Solid .tsx components are self-accepting via solid-refresh's inline
1205
- // patchRegistry — re-importing them is sufficient. For non-component
1206
- // .ts utility modules, we must propagate up the import graph to find
1207
- // the .tsx/.jsx component boundaries and re-import those so their
1208
- // solid-refresh proxies pick up the new dependency values.
1209
- try {
1210
- // Build reverse index: dep id → list of importer ids
1211
- const reverseIndex = new Map();
1212
- for (const [id, mod] of graph) {
1213
- for (const dep of mod.deps) {
1214
- let arr = reverseIndex.get(dep);
1215
- if (!arr) {
1216
- arr = [];
1217
- reverseIndex.set(dep, arr);
1218
- }
1219
- arr.push(id);
1220
- }
1221
- }
1222
- // Pass 0: collect the FULL importer chain of every changed file
1223
- // (BFS up the reverse graph, no filtering). This feeds
1224
- // `ev.ancestors` for app-level remount helpers.
1225
- for (const id of drained) {
1226
- const queue = [id];
1227
- while (queue.length) {
1228
- const cur = queue.shift();
1229
- const importers = reverseIndex.get(cur);
1230
- if (!importers)
1231
- continue;
1232
- for (const imp of importers) {
1233
- if (ancestors.has(imp))
1234
- continue;
1235
- ancestors.add(imp);
1236
- queue.push(imp);
1237
- }
1238
- }
1239
- }
1240
- // Pass 1: BFS from each non-tsx changed module up to tsx/jsx
1241
- // boundaries. These get re-imported below so solid-refresh's
1242
- // inline patchRegistry runs and (best-effort) swaps the proxy
1243
- // signals for any components defined in those tsx boundaries.
1244
- for (const id of drained) {
1245
- if (/\.(tsx|jsx)$/i.test(id))
1246
- continue; // already self-accepting
1247
- const visited = new Set();
1248
- const queue = [id];
1249
- while (queue.length) {
1250
- const cur = queue.shift();
1251
- if (visited.has(cur))
1252
- continue;
1253
- visited.add(cur);
1254
- const importers = reverseIndex.get(cur);
1255
- if (!importers)
1256
- continue;
1257
- for (const imp of importers) {
1258
- if (/\.(tsx|jsx)$/i.test(imp)) {
1259
- boundaries.add(imp);
1260
- }
1261
- else {
1262
- queue.push(imp);
1263
- }
1264
- }
1265
- }
1266
- }
1267
- // Pass 2: walk further from any tsx starting point (a tsx file
1268
- // in `drained` OR a tsx boundary discovered in pass 1) to find
1269
- // route files (`/src/routes/*.{tsx,jsx}`) that transitively
1270
- // import them. Re-importing a route file refreshes its
1271
- // `Route.options.component` to the freshly-imported reference
1272
- // and the existing boundary loop below patches the live router
1273
- // with that fresh reference.
1274
- //
1275
- // This is the key fix for "edit home.tsx → save → no visual
1276
- // update": the old BFS skipped tsx files in `drained` (assuming
1277
- // solid-refresh's in-place proxy patch was sufficient), but in
1278
- // the universal-renderer + nested-context configuration that
1279
- // patch does not always propagate to the visible page tree.
1280
- // Adding the route file as a boundary lets us patch
1281
- // `route.options.component` directly to a fresh module export,
1282
- // which the framework subscriber then passes through to the
1283
- // page remount — making the cycle robust to the proxy patch
1284
- // silently failing.
1285
- const tsxStarts = new Set();
1286
- for (const id of drained) {
1287
- if (/\.(tsx|jsx)$/i.test(id))
1288
- tsxStarts.add(id);
1289
- }
1290
- for (const b of boundaries)
1291
- tsxStarts.add(b);
1292
- const ROUTE_FILE_RE = /\/src\/routes\/.+\.(tsx|jsx)$/i;
1293
- for (const start of tsxStarts) {
1294
- const visited = new Set();
1295
- const queue = [start];
1296
- while (queue.length) {
1297
- const cur = queue.shift();
1298
- if (visited.has(cur))
1299
- continue;
1300
- visited.add(cur);
1301
- if (cur !== start && ROUTE_FILE_RE.test(cur)) {
1302
- boundaries.add(cur);
1303
- }
1304
- const importers = reverseIndex.get(cur);
1305
- if (!importers)
1306
- continue;
1307
- for (const imp of importers) {
1308
- queue.push(imp);
1309
- }
1310
- }
1311
- }
1312
- // Re-import each boundary so solid-refresh patchRegistry fires.
1313
- // For route files (TanStack Router), capture the new Route export
1314
- // and patch the router's existing route with the fresh loader.
1315
- let routesPatchCount = 0;
1316
- let discoveredRouter = null;
1317
- // Discover router: try __ns_router global (set by createNativeScriptRouter),
1318
- // then scan globalThis for any router-shaped object with routesById.
1319
- const findRouter = () => {
1320
- if (discoveredRouter)
1321
- return discoveredRouter;
1322
- const g = getGlobalScope();
1323
- if (g.__ns_router?.routesById)
1324
- return (discoveredRouter = g.__ns_router);
1325
- // Fallback: scan common global keys for router
1326
- for (const key of ['__ns_router', 'router', '__router']) {
1327
- if (g[key]?.routesById && g[key]?.invalidate)
1328
- return (discoveredRouter = g[key]);
1329
- }
1330
- return null;
1331
- };
1332
- // Convert boundary file path to TanStack Router fullPath.
1333
- // e.g. /src/routes/posts.$postId.tsx → /posts/$postId
1334
- const boundaryToFullPath = (bid) => {
1335
- const m = bid.match(/\/src\/routes\/(.+)\.(tsx|jsx|ts|js)$/i);
1336
- if (!m)
1337
- return null;
1338
- let p = m[1];
1339
- // Replace dots between segments with slashes (posts.$postId → posts/$postId)
1340
- p = p.replace(/\./g, '/');
1341
- // Handle index files
1342
- if (p === 'index')
1343
- return '/';
1344
- if (p.endsWith('/index'))
1345
- p = p.slice(0, -6);
1346
- // Strip leading - (TanStack pathless layout convention)
1347
- p = p.replace(/(^|\/)-([\w])/g, '$1$2');
1348
- return '/' + p;
1349
- };
1350
- // Find existing route by fullPath (since new Route has no id yet).
1351
- // The root route (`__root__`) shares fullPath '/' with the index
1352
- // route, so prefer the non-root (leaf) match — otherwise editing
1353
- // `index.tsx` would clobber the root layout's component instead of
1354
- // the page's. @nativescript/tanstack-router's remount uses the same
1355
- // preference so patch + read target the same route.
1356
- const findRouteByFullPath = (router, fp) => {
1357
- if (!router?.routesById)
1358
- return null;
1359
- let rootMatch = null;
1360
- for (const rid of Object.keys(router.routesById)) {
1361
- const r = router.routesById[rid];
1362
- if (r?.fullPath !== fp)
1363
- continue;
1364
- if (rid === '__root__') {
1365
- rootMatch = rootMatch || r;
1366
- continue;
1367
- }
1368
- return r;
1369
- }
1370
- return rootMatch;
1371
- };
1372
- // A changed route file is itself a boundary to re-import + patch — Pass 2
1373
- // only adds OTHER route files that import a changed module, never the
1374
- // changed route file itself. Without this, editing `about.tsx` while on
1375
- // /about never refreshes the About component.
1376
- for (const id of drained) {
1377
- if (ROUTE_FILE_RE.test(id))
1378
- boundaries.add(id);
1379
- }
1380
- // Evict ONLY the boundary set (changed component + route files) — NOT the
1381
- // router / route-tree / app chain. Keeping those cached preserves the live
1382
- // router instance and the user's current route across the re-mount; fresh
1383
- // route components reach the screen via the in-place `route.options.component`
1384
- // patch below, not a router rebuild (which would reset to the initial route).
1385
- const boundaryIds = Array.from(boundaries);
1386
- const solidEvictUrls = buildEvictionUrls(boundaryIds);
1387
- const solidEvicted = invalidateModulesByUrls(solidEvictUrls);
1388
- if (VERBOSE)
1389
- console.log(`[hmr][solid] eviction count=${solidEvictUrls.length} ok=${solidEvicted}`);
1390
- for (const id of boundaries) {
1391
- // Skip already-drained modules — EXCEPT route files. The main
1392
- // drain loop above re-imports drained modules but does NOT patch
1393
- // `route.options.component`; a changed ROUTE file (which is in
1394
- // `drained`/`seen`) must still flow through this loop so its route
1395
- // gets patched with the fresh component, otherwise the router's
1396
- // per-page HMR remount re-renders the stale (one-edit-behind) one.
1397
- if (seen.has(id) && !/\/src\/routes\/.+\.(?:tsx|jsx)$/i.test(id))
1398
- continue;
1399
- // Skip the root layout (`__root`): it commonly imports a global
1400
- // stylesheet (`./styles.css?url`) with no ESM `default` export on
1401
- // device, so re-importing it throws and aborts the cycle. The root
1402
- // layout rarely needs a component hot-swap anyway.
1403
- if (/\/routes\/__root\.(?:tsx|jsx|ts|js)$/i.test(id))
1404
- continue;
1405
- try {
1406
- const spec = normalizeSpec(id);
1407
- // Re-import the canonical URL. The boundary was evicted above
1408
- // (`invalidateModulesByUrls(solidEvictUrls)`), which also armed
1409
- // the runtime's bust-next-fetch nonce, so this import re-fetches
1410
- // the just-saved transform rather than a cached one. This is what
1411
- // `route.options.component` is patched from below, and what
1412
- // @nativescript/tanstack-router's per-page HMR remount reads.
1413
- const url = await requestModuleFromServer(spec);
1414
- if (!url)
1415
- continue;
1416
- if (VERBOSE)
1417
- console.log('[hmr][solid] propagated to boundary', { id, url });
1418
- const mod = await import(/* @vite-ignore */ url);
1419
- // Patch TanStack Router route options for any module
1420
- // that exports a `Route`. We patch BOTH the component
1421
- // and the loader (when present); components-only routes
1422
- // were previously skipped because the gate required a
1423
- // loader, which left their `options.component` pointing
1424
- // at the stale module's exports after HMR.
1425
- try {
1426
- const newRoute = mod?.Route;
1427
- if (newRoute?.options) {
1428
- const router = findRouter();
1429
- const fullPath = boundaryToFullPath(id);
1430
- if (VERBOSE)
1431
- console.log('[hmr][solid][diag] route patch attempt', { id, fullPath, hasRouter: !!router, hasLoader: !!newRoute.options.loader, hasComponent: !!newRoute.options.component });
1432
- const existingRoute = fullPath && router ? findRouteByFullPath(router, fullPath) : null;
1433
- if (existingRoute?.options) {
1434
- if (newRoute.options.loader)
1435
- existingRoute.options.loader = newRoute.options.loader;
1436
- if (newRoute.options.component)
1437
- existingRoute.options.component = newRoute.options.component;
1438
- routesPatchCount++;
1439
- if (VERBOSE)
1440
- console.log('[hmr][solid] patched route', existingRoute.id, 'fullPath=', fullPath);
1441
- }
1442
- else if (VERBOSE) {
1443
- console.log('[hmr][solid] no matching route for fullPath', fullPath);
1444
- }
1445
- }
1446
- }
1447
- catch (e) {
1448
- if (VERBOSE)
1449
- console.warn('[hmr][solid] route patch error', id, e);
1450
- }
1451
- }
1452
- catch (e) {
1453
- if (VERBOSE)
1454
- console.warn('[hmr][solid] boundary re-import failed', id, e);
1455
- }
1456
- }
1457
- // Route loaders were patched with fresh closures. The data is
1458
- // correct in router.state.matches[].loaderData (confirmed via
1459
- // diagnostics), but the currently visible page doesn't re-render
1460
- // because the NativeScriptRouterProvider's Solid store flush only
1461
- // fires through history.subscribe. TODO: find the right mechanism
1462
- // to trigger a Solid reactive update for the active match stores.
1463
- if (routesPatchCount > 0 && VERBOSE) {
1464
- console.log('[hmr][solid] patched', routesPatchCount, 'route loaders (data correct in match state, pending UI refresh mechanism)');
1465
- }
1466
- if (VERBOSE) {
1467
- if (boundaries.size)
1468
- console.log('[hmr][solid] propagated non-component change to', boundaries.size, 'boundaries', Array.from(boundaries));
1469
- console.log('[hmr][queue] Solid: modules re-imported; UI refresh is driven by the framework subscriber (router per-page remount or startSolidApp re-render)', drained);
1470
- }
1471
- }
1472
- catch (e) {
1473
- if (VERBOSE)
1474
- console.warn('[hmr][solid] propagation failed', e);
1475
- }
1476
- // Notify any framework integrations (e.g.
1477
- // `@nativescript/tanstack-router`) that a Solid HMR
1478
- // cycle has completed. They use this signal to perform
1479
- // framework-specific UI refresh (e.g. remount the active
1480
- // router page) when solid-refresh's own reactive
1481
- // propagation does not reach the visible tree under
1482
- // the current renderer/context configuration.
1483
- //
1484
- // Boundaries include both the directly-changed tsx files
1485
- // AND every tsx ancestor reachable via the reverse import
1486
- // graph (route files in particular). The framework
1487
- // listener uses the route-file boundaries to look up the
1488
- // freshly-patched `route.options.component` and pass it
1489
- // through to the page remount.
1490
- try {
1491
- const tsxChangedInDrained = drained.filter((id) => /\.(tsx|jsx)$/i.test(id));
1492
- const allBoundaries = Array.from(new Set([...tsxChangedInDrained, ...boundaries]));
1493
- nsSolidHmrEmit({
1494
- kind: 'solid',
1495
- changedFiles: drained.slice(),
1496
- boundaries: allBoundaries,
1497
- ancestors: Array.from(ancestors),
1498
- });
1499
- }
1500
- catch (err) {
1501
- if (VERBOSE)
1502
- console.warn('[hmr][solid] emit failed', err);
1503
- }
1504
- // Tell the overlay the cycle is done. solid-refresh's
1505
- // inline patchRegistry has already flushed the new
1506
- // component bodies into the live tree (the `case
1507
- // 'solid'` block above re-imports each .tsx
1508
- // boundary), so by the time we get here the user is
1509
- // already looking at the new render. The 'complete'
1510
- // frame surfaces the wall-clock total and triggers
1511
- // the overlay's auto-hide.
1512
- setUpdateOverlayStage('complete', {
1513
- detail: `Total ${Math.max(0, Date.now() - tQueueStart)}ms`,
1514
- });
1515
- break;
1516
- }
1517
- case 'typescript': {
1518
- // For TS apps, always reset back to the conventional app root.
1519
- // This preserves the shell (Frame, ActionBar, etc.) that the app's
1520
- // own bootstrapping wires up via `Application.run`.
1521
- try {
1522
- const g = getGlobalScope();
1523
- const App = getCore('Application') || g.Application;
1524
- if (!App || typeof App.resetRootView !== 'function') {
1525
- if (VERBOSE)
1526
- console.warn('[hmr][queue] TS flavor: Application.resetRootView unavailable; skipping UI refresh');
1527
- break;
1528
- }
1529
- // Re-fetch changed XML/CSS files and update the bundled module registry
1530
- // so Builder.createViewFromEntry picks up fresh content.
1531
- const rawAssetIds = drained.filter((id) => /\.(xml|css|scss|sass|less)$/i.test(id));
1532
- if (rawAssetIds.length && typeof g.registerModule === 'function') {
1533
- const origin = getHttpOriginForVite() || deriveHttpOrigin(getHMRWsUrl());
1534
- if (origin) {
1535
- for (const id of rawAssetIds) {
1536
- try {
1537
- const spec = normalizeSpec(id);
1538
- // Fetch the raw file content directly from Vite's dev server.
1539
- // Use the project-relative path which Vite serves as static files.
1540
- const fetchUrl = origin + (spec.startsWith('/') ? spec : '/' + spec);
1541
- if (VERBOSE)
1542
- console.log('[hmr][queue] fetching raw asset', { id, fetchUrl });
1543
- const resp = await fetch(fetchUrl);
1544
- if (resp.ok) {
1545
- const rawContent = await resp.text();
1546
- // Register under all nickname variants the module registry uses.
1547
- // The bundler context registers XML as e.g., './main-page.xml' and 'main-page.xml'
1548
- const relPath = toAppRelativePath(id);
1549
- if (!relPath)
1550
- continue;
1551
- const nicknames = ['./' + relPath, relPath];
1552
- // Also add without extension for CSS
1553
- const extIdx = relPath.lastIndexOf('.');
1554
- if (extIdx > 0) {
1555
- const baseName = relPath.slice(0, extIdx);
1556
- if (!relPath.endsWith('.xml'))
1557
- nicknames.push(baseName, './' + baseName);
1558
- }
1559
- for (const name of nicknames) {
1560
- if (VERBOSE)
1561
- console.log('[hmr][queue] re-registering module', name);
1562
- g.registerModule(name, () => rawContent);
1563
- }
1564
- }
1565
- else if (VERBOSE) {
1566
- console.warn('[hmr][queue] raw asset fetch failed', id, resp.status);
1567
- }
1568
- }
1569
- catch (e) {
1570
- if (VERBOSE)
1571
- console.warn('[hmr][queue] raw asset refresh failed for', id, e);
1572
- }
1573
- }
1574
- }
1575
- }
1576
- // Modal-aware refresh: pages currently PRESENTED AS MODALS must be
1577
- // closed + re-presented in place — navigating the top frame to a
1578
- // modal's page would push it as a frame page, and resetRootView
1579
- // would dismiss the modal entirely. State comes from core's live
1580
- // modal stack (_moduleName/_modalOptions/_modalParent); the
1581
- // showModal wrap only backfills options on older cores.
1582
- ensureModalTracking();
1583
- const openModals = getOpenStringModuleModals();
1584
- const changedModuleNames = new Set(drained.map(toAppModuleName).filter(Boolean));
1585
- const modalsToReshow = openModals.filter((record) => changedModuleNames.has(record.moduleName));
1586
- const reshowModuleNames = new Set(modalsToReshow.map((record) => record.moduleName));
1587
- // Determine if we can navigate in-place to a changed page
1588
- // instead of resetting all the way back to app-root.
1589
- // This keeps the user on the page they're editing for faster iteration.
1590
- const changedXmlPages = drained
1591
- .filter((id) => /\.xml$/i.test(id))
1592
- .map((id) => toAppModuleName(id))
1593
- .filter((m) => m && m !== 'app-root' && !reshowModuleNames.has(m));
1594
- // Resolve the topmost Frame from the bundled realm.
1595
- // Frame.topmost() relies on an internal frameStack array, so we must
1596
- // call it on the bundled-realm class. Multiple strategies to find it:
1597
- const FrameClass = getCore('Frame') || g.Frame;
1598
- let topFrame = null;
1599
- // 1) Try the vendor-realm static topmost()
1600
- try {
1601
- topFrame = FrameClass?.topmost?.();
1602
- }
1603
- catch { }
1604
- // 2) Try getting the root view from Application — if it's a Frame, use it
1605
- if (!topFrame) {
1606
- try {
1607
- const rootView = App.getRootView?.() || App._rootView;
1608
- if (rootView) {
1609
- // rootView could be a Frame itself, or contain a Frame
1610
- const isFrame = rootView.constructor?.name === 'Frame' || rootView.navigate;
1611
- if (isFrame) {
1612
- topFrame = rootView;
1613
- }
1614
- else if (rootView.getChildAt) {
1615
- // Walk direct children looking for a Frame
1616
- for (let i = 0; i < (rootView.getChildrenCount?.() || 0); i++) {
1617
- const child = rootView.getChildAt(i);
1618
- if (child?.constructor?.name === 'Frame' || child?.navigate) {
1619
- topFrame = child;
1620
- break;
1621
- }
1622
- }
1623
- }
1624
- }
1625
- }
1626
- catch { }
1627
- }
1628
- if (VERBOSE)
1629
- console.log('[hmr][queue] TS: changedXmlPages=', changedXmlPages, 'topFrame=', !!topFrame, 'modalsToReshow=', modalsToReshow.length);
1630
- if (changedXmlPages.length > 0 && topFrame) {
1631
- // Navigate the current frame to the changed page directly.
1632
- // Use the last changed XML page (most specific).
1633
- const moduleName = changedXmlPages[changedXmlPages.length - 1];
1634
- if (VERBOSE)
1635
- console.log('[hmr][queue] TS: navigating in-place to', moduleName);
1636
- try {
1637
- topFrame.navigate({ moduleName, clearHistory: false, animated: false });
1638
- }
1639
- catch (navErr) {
1640
- console.warn('[hmr][queue] TS flavor: in-place navigate failed, falling back to resetRootView', navErr);
1641
- App.resetRootView({ moduleName: 'app-root' });
1642
- }
1643
- }
1644
- else if (modalsToReshow.length === 0) {
1645
- // No frame page to refresh and no open modal owns the change —
1646
- // fall back to a full root reset. (Skipped when an open modal is
1647
- // being re-presented below: resetRootView would dismiss it.)
1648
- if (VERBOSE)
1649
- console.log('[hmr][queue] TS flavor: resetRootView(app-root) after changes');
1650
- App.resetRootView({ moduleName: 'app-root' });
1651
- }
1652
- // Re-present any open modals whose XML/code-behind changed. The
1653
- // modules were already re-registered above (raw XML assets + fresh
1654
- // code-behind exports), so the re-presented modal rebuilds from
1655
- // the new content while the page beneath it stays put.
1656
- for (const record of modalsToReshow) {
1657
- await reshowOpenModal(record);
1658
- }
1659
- }
1660
- catch (e) {
1661
- console.warn('[hmr][queue] TS flavor: resetRootView(app-root) failed', e);
1662
- }
1663
- // Tell the overlay the cycle is done — same as the solid path
1664
- // above. Without this the applying overlay sticks at
1665
- // 'received' (5%) forever even though the in-place navigate /
1666
- // resetRootView already applied the update.
1667
- setUpdateOverlayStage('complete', {
1668
- detail: `Total ${Math.max(0, Date.now() - tQueueStart)}ms`,
1669
- });
1670
- break;
1671
- }
1672
- }
1673
- }
1674
- finally {
1675
- processingQueue = false;
1676
- processingPromise = null;
1677
- // If a delta arrived mid-cycle (pushed onto changedQueue while
1678
- // processingQueue was still true, so its processQueue() call early-
1679
- // returned), re-drain — otherwise that save is stranded until the next
1680
- // delta. Deferred via setTimeout to avoid synchronous re-entrancy as
1681
- // this promise settles.
1682
- if (changedQueue.length) {
1683
- setTimeout(() => {
1684
- try {
1685
- processQueue();
1686
- }
1687
- catch { }
1688
- }, 0);
1689
- }
1690
- }
1691
- })();
1692
- return processingPromise;
1693
- }
1694
- let hmrSocket = null;
1695
- // Single reconnect timer. Overlapping close/timeout events used to each schedule
1696
- // their own `setTimeout(connectHmr, …)`, stacking multiple pending reconnects
1697
- // that could spawn (and leak) duplicate sockets/listeners. Route all reconnect
1698
- // scheduling through here so only one is ever pending.
1699
- let reconnectTimer = null;
1700
- function scheduleReconnect(delayMs) {
1701
- if (reconnectTimer)
1702
- clearTimeout(reconnectTimer);
1703
- reconnectTimer = setTimeout(() => {
1704
- reconnectTimer = null;
1705
- connectHmr();
1706
- }, delayMs);
1707
- }
1708
- // Track server-announced batches for each version so we can import in-order client-side
1709
- const txnClientBatches = new Map();
1710
- // Public hook for NativeScript runtime to call from ImportModuleDynamicallyCallback later.
1711
- globalThis.__nsHmrRequestModule = async function (spec) {
1712
- let normalized = normalizeSpec(spec);
1713
- // Remove extension for transform lookup variants (server will try .ts/.js/.mjs)
1714
- normalized = normalized.replace(/\.(ts|js|tsx|jsx|mjs)$/i, '');
1715
- if (!normalized.startsWith('/'))
1716
- normalized = '/' + normalized;
1717
- if (normalized === '@') {
1718
- // Soft-handle instead of throwing to avoid breaking evaluation paths: return a safe empty module stub.
1719
- try {
1720
- const err = new Error('[hmr-fetch] anomalous @ spec');
1721
- const stack = err.stack || '';
1722
- hmrMetrics.invalidAtSpec = (hmrMetrics.invalidAtSpec || 0) + 1;
1723
- console.warn('[hmr-fetch] refusing to fetch bare @ spec; returning stub; original=', spec, 'stack=\n' + stack);
1724
- }
1725
- catch { }
1726
- return '/__invalid_at__.mjs';
1727
- }
1728
- const url = await requestModuleFromServer(normalized);
1729
- return url;
1730
- };
1731
- function connectHmr() {
1732
- if (hmrSocket?.readyState === WebSocket.OPEN)
1733
- return;
1734
- if (hmrSocket?.readyState === WebSocket.CONNECTING) {
1735
- if (VERBOSE)
1736
- console.log('[hmr-client] Already connecting to HMR WebSocket, skipping');
1737
- return;
1738
- }
1739
- // A reconnect fired (or a manual connect raced one) — cancel any other pending
1740
- // reconnect so we don't end up with overlapping connect attempts.
1741
- if (reconnectTimer) {
1742
- clearTimeout(reconnectTimer);
1743
- reconnectTimer = null;
1744
- }
1745
- try {
1746
- globalThis.__NS_HMR_CLIENT_SOCKET_READY__ = false;
1747
- }
1748
- catch { }
1749
- const overlayStage = hasOpenedHmrSocket ? 'reconnecting' : 'connecting';
1750
- const baseUrl = getHMRWsUrl() || 'ws://localhost:5173/ns-hmr';
1751
- const buildCandidates = (url) => {
1752
- const candidates = [];
1753
- try {
1754
- const u = new URL(url);
1755
- const proto = u.protocol === 'wss:' ? ['wss'] : ['ws'];
1756
- const defaultPort = u.port || '5173';
1757
- // Build ordered host candidates with preference to the active HTTP origin
1758
- const orderedHosts = [];
1759
- try {
1760
- const g = getGlobalScope();
1761
- const httpOrigin = g && typeof g.__NS_HTTP_ORIGIN__ === 'string' ? g.__NS_HTTP_ORIGIN__ : undefined;
1762
- if (httpOrigin) {
1763
- try {
1764
- const ho = new URL(httpOrigin);
1765
- orderedHosts.push({
1766
- host: ho.hostname,
1767
- port: ho.port || defaultPort,
1768
- });
1769
- }
1770
- catch { }
1771
- }
1772
- }
1773
- catch { }
1774
- // From provided URL
1775
- orderedHosts.push({ host: u.hostname, port: defaultPort });
1776
- // Explicit override
1777
- try {
1778
- const h = globalThis.__NS_HMR_HOST;
1779
- if (h)
1780
- orderedHosts.push({ host: String(h), port: defaultPort });
1781
- }
1782
- catch { }
1783
- // Common fallbacks
1784
- orderedHosts.push({ host: '10.0.2.2', port: defaultPort });
1785
- orderedHosts.push({ host: 'localhost', port: defaultPort });
1786
- const seen = new Set();
1787
- for (const p of proto) {
1788
- for (const { host, port } of orderedHosts) {
1789
- const key = `${host}:${port}`;
1790
- if (seen.has(key))
1791
- continue;
1792
- seen.add(key);
1793
- const cand = `${p}://${host}:${port}${u.pathname || '/ns-hmr'}${u.search || ''}`;
1794
- candidates.push(cand);
1795
- }
1796
- }
1797
- }
1798
- catch {
1799
- candidates.push(url);
1800
- }
1801
- // Deduplicate while preserving order
1802
- const seen = new Set();
1803
- return candidates.filter((c) => (seen.has(c) ? false : (seen.add(c), true)));
1804
- };
1805
- const candidates = buildCandidates(baseUrl);
1806
- let idx = 0;
1807
- const tryNext = () => {
1808
- if (idx >= candidates.length) {
1809
- showConnectionOverlayNow('offline', 'Waiting for the Vite websocket to come back.');
1810
- console.warn('[hmr-client] All WS candidates failed:', candidates.join(', '));
1811
- scheduleReconnect(1500);
1812
- return;
1813
- }
1814
- const url = candidates[idx++];
1815
- const connectionDetail = `${overlayStage === 'reconnecting' ? 'Retrying' : 'Opening'} ${url}`;
1816
- if (overlayStage === 'reconnecting' && shownConnectionOverlayStage === 'offline') {
1817
- // Don't flip the visible 'offline' frame to 'reconnecting' for an
1818
- // attempt that may fail instantly — defer it so only a genuinely
1819
- // in-flight attempt surfaces. The deferred show is cancelled by
1820
- // showConnectionOverlayNow (offline re-show / synchronizing) the
1821
- // moment this attempt resolves. Keeps 'offline' stable instead of
1822
- // flickering once per retry. (Checking the PAINTED stage, not the
1823
- // pending one, so every candidate in the loop keeps deferring.)
1824
- scheduleConnectionOverlay(overlayStage, connectionDetail, RECONNECTING_OVER_OFFLINE_DELAY_MS);
1825
- }
1826
- else if (connectionOverlayVisible) {
1827
- updateConnectionOverlay(overlayStage, connectionDetail);
1828
- }
1829
- else {
1830
- scheduleConnectionOverlay(overlayStage, connectionDetail);
1831
- }
1832
- try {
1833
- if (VERBOSE)
1834
- console.log('[hmr-client] Connecting to HMR WebSocket:', url);
1835
- const sock = new WebSocket(url);
1836
- hmrSocket = sock;
1837
- setHttpOriginForVite(deriveHttpOrigin(url));
1838
- let opened = false;
1839
- const timeout = setTimeout(() => {
1840
- if (!opened && sock.readyState !== WebSocket.OPEN) {
1841
- try {
1842
- sock.close();
1843
- }
1844
- catch { }
1845
- if (VERBOSE)
1846
- console.warn('[hmr-client] WS connect timeout, trying next…');
1847
- tryNext();
1848
- }
1849
- }, 3500);
1850
- sock.onopen = () => {
1851
- opened = true;
1852
- clearTimeout(timeout);
1853
- clearConnectionOverlayTimer();
1854
- hasOpenedHmrSocket = true;
1855
- awaitingHealthyHmrMessage = true;
1856
- try {
1857
- globalThis.__NS_HMR_CLIENT_SOCKET_READY__ = true;
1858
- }
1859
- catch { }
1860
- // Wire the JS hot registry's server channel to this socket so
1861
- // `import.meta.hot.send(event, data)` reaches Vite plugins as
1862
- // `{ type: 'custom', event, data }` (Vite wire protocol).
1863
- try {
1864
- getNsHotRegistry().setSendToServer((event, data) => {
1865
- try {
1866
- if (sock.readyState === WebSocket.OPEN) {
1867
- sock.send(JSON.stringify({ type: 'custom', event, data }));
1868
- }
1869
- }
1870
- catch { }
1871
- });
1872
- }
1873
- catch { }
1874
- if (connectionOverlayVisible) {
1875
- showConnectionOverlayNow('synchronizing', 'Connected. Synchronizing the HMR graph.');
1876
- }
1877
- if (VERBOSE)
1878
- console.log('[hmr-client] Connected to HMR WebSocket');
1879
- // Print the active module reload mode once on first
1880
- // successful connect so the user can correlate HMR latency
1881
- // with runtime capability without grepping for protocol
1882
- // details. The banner is verbose-gated.
1883
- try {
1884
- emitHmrModeBannerOnce();
1885
- }
1886
- catch { }
1887
- };
1888
- sock.onmessage = handleHmrMessage;
1889
- sock.onerror = (error) => {
1890
- clearTimeout(timeout);
1891
- console.warn('[hmr-client] WebSocket error:', (error && (error.message || error)) || error);
1892
- };
1893
- sock.onclose = (ev) => {
1894
- clearTimeout(timeout);
1895
- try {
1896
- globalThis.__NS_HMR_CLIENT_SOCKET_READY__ = false;
1897
- }
1898
- catch { }
1899
- if (!opened) {
1900
- // immediate failure during connect → try another candidate
1901
- if (VERBOSE)
1902
- console.warn('[hmr-client] WS close before open (code', ev?.code, '), trying next…');
1903
- tryNext();
1904
- }
1905
- else {
1906
- if (VERBOSE)
1907
- console.log('[hmr-client] WebSocket closed (code', ev?.code, '), will reconnect…');
1908
- scheduleConnectionOverlay('reconnecting', 'The websocket closed. Waiting to reconnect.', 700);
1909
- // try to reconnect with full candidate list again
1910
- scheduleReconnect(1000);
1911
- }
1912
- };
1913
- }
1914
- catch (e) {
1915
- console.warn('[hmr-client] Failed to connect WebSocket', e);
1916
- tryNext();
1917
- }
1918
- };
1919
- tryNext();
1920
- }
1921
- async function handleHmrMessage(ev) {
1922
- let msg;
1923
- try {
1924
- msg = JSON.parse(ev.data);
1925
- }
1926
- catch {
1927
- return;
1928
- }
1929
- if (awaitingHealthyHmrMessage && msg) {
1930
- markHmrConnectionHealthy();
1931
- }
1932
- if (VERBOSE && msg?.type) {
1933
- console.log('[hmr-client] received message', msg.type);
1934
- }
1935
- // Notify optional app-level hook after an HMR batch is applied.
1936
- function notifyAppHmrUpdate(kind, changedIds) {
1937
- try {
1938
- const hook = globalThis.__NS_HMR_ON_UPDATE__;
1939
- if (typeof hook === 'function') {
1940
- hook({ type: kind, version: getGraphVersion(), changedIds: changedIds || [], raw: msg });
1941
- }
1942
- }
1943
- catch { }
1944
- }
1945
- if (msg) {
1946
- // `ns:hmr-pending` is a fire-and-forget UX hint emitted by the
1947
- // server at the START of handleHotUpdate. We drive the
1948
- // HMR-applying overlay's 'received' frame here (synchronously),
1949
- // well before the authoritative payload (`ns:angular-update` /
1950
- // `ns:css-updates`) lands. Skip running any other handlers —
1951
- // the pending message has no module payload and intentionally
1952
- // does not bump the graph version.
1953
- if (msg.type === 'ns:hmr-pending' && typeof msg.path === 'string') {
1954
- setHmrPendingOverlay(msg.path);
1955
- return;
1956
- }
1957
- // The per-flavor client strategy is loaded by a dynamic import(); make
1958
- // sure it has resolved (and `install()` has run) before any handler that
1959
- // delegates through it. After the first message this is an already-settled
1960
- // promise (microtask only); for Solid/TypeScript it is `Promise.resolve()`.
1961
- await CLIENT_STRATEGY_READY;
1962
- if (msg.type === 'ns:hmr-full-graph') {
1963
- // Bump a monotonic nonce so HTTP ESM imports can always be cache-busted per update.
1964
- try {
1965
- const g = getGlobalScope();
1966
- g.__NS_HMR_IMPORT_NONCE__ = (typeof g.__NS_HMR_IMPORT_NONCE__ === 'number' ? g.__NS_HMR_IMPORT_NONCE__ : 0) + 1;
1967
- }
1968
- catch { }
1969
- // Capture previous graph snapshot so we can infer which modules changed.
1970
- const prevGraph = new Map(graph);
1971
- setGraphVersion(Number(msg.version || getGraphVersion() || 0));
1972
- applyFullGraph(msg);
1973
- hasReceivedFullGraph = true;
1974
- // Gate: On first boot, the entry-runtime handles all initial module loading
1975
- // (with the import map already configured). Don't re-import here — the graph
1976
- // is stored above for future HMR delta comparisons, but modules are already
1977
- // loaded correctly via the entry-runtime boot sequence.
1978
- //
1979
- // Two cases to catch:
1980
- // 1. Boot still in progress (__NS_HMR_BOOT_COMPLETE__ is false)
1981
- // 2. Boot already finished but this is the FIRST full-graph (prevGraph was
1982
- // empty). The WebSocket often connects after entry-runtime finishes, so
1983
- // boot is "complete" but we still shouldn't re-import — all modules were
1984
- // just loaded fresh. Only re-import on subsequent full-graphs (reconnect
1985
- // scenarios) where prevGraph already has entries.
1986
- if (!globalThis.__NS_HMR_BOOT_COMPLETE__) {
1987
- if (VERBOSE)
1988
- console.info('[hmr][full-graph] skipping initial re-import (boot in progress)');
1989
- const fullIds = Array.isArray(msg.modules) ? msg.modules.map((m) => m?.id).filter(Boolean) : [];
1990
- notifyAppHmrUpdate('full-graph', fullIds);
1991
- return;
1992
- }
1993
- if (prevGraph.size === 0) {
1994
- if (VERBOSE)
1995
- console.info('[hmr][full-graph] skipping re-import on first graph after boot (modules already fresh)');
1996
- const fullIds = Array.isArray(msg.modules) ? msg.modules.map((m) => m?.id).filter(Boolean) : [];
1997
- notifyAppHmrUpdate('full-graph', fullIds);
1998
- return;
1999
- }
2000
- // Reconnect / resync case — re-import changed modules as normal.
2001
- // In some cases (e.g. server chooses full-graph resync / page reload), we won't
2002
- // receive a delta queue to re-import changed TS modules. Without re-import,
2003
- // HTTP ESM caching means module bodies (and side effects) won't re-run.
2004
- try {
2005
- const inferredChanged = [];
2006
- try {
2007
- for (const [id, next] of graph.entries()) {
2008
- const prev = prevGraph.get(id);
2009
- if (!prev || prev.hash !== next.hash)
2010
- inferredChanged.push(id);
2011
- }
2012
- // Removed modules are also "changed" but we don't import them.
2013
- }
2014
- catch { }
2015
- // Best-effort: only re-import real source modules (avoid .vue registry pipeline and virtual ids)
2016
- const toReimport = inferredChanged.filter((id) => {
2017
- if (!id || typeof id !== 'string')
2018
- return false;
2019
- if (/^\0|^\/\0/.test(id))
2020
- return false;
2021
- if (/plugin-vue:export-helper/.test(id))
2022
- return false;
2023
- if (/\.vue$/i.test(id))
2024
- return false;
2025
- if (id.endsWith(APP_MAIN_ENTRY_SPEC))
2026
- return false;
2027
- return true;
2028
- });
2029
- if (toReimport.length && VERBOSE)
2030
- console.log('[hmr][full-graph] inferred changed modules; re-importing', toReimport);
2031
- // Evict the inferred changed set before re-importing.
2032
- // See `processQueue` for the architectural rationale; the
2033
- // full-graph code path is the resync fallback (server chose
2034
- // not to send a delta) and shares the same V8 cache pitfall.
2035
- const fgEvictUrls = buildEvictionUrls(toReimport);
2036
- const fgEvicted = invalidateModulesByUrls(fgEvictUrls);
2037
- if (VERBOSE)
2038
- console.log(`[hmr][full-graph] eviction count=${fgEvictUrls.length} ok=${fgEvicted}`);
2039
- for (const id of toReimport) {
2040
- try {
2041
- const spec = normalizeSpec(id);
2042
- const url = await requestModuleFromServer(spec);
2043
- if (!url)
2044
- continue;
2045
- if (VERBOSE)
2046
- console.log('[hmr][full-graph] re-import', { id, spec, url });
2047
- await import(/* @vite-ignore */ url);
2048
- }
2049
- catch (e) {
2050
- if (VERBOSE)
2051
- console.warn('[hmr][full-graph] re-import failed for', id, e);
2052
- }
2053
- }
2054
- }
2055
- catch { }
2056
- const fullIds = Array.isArray(msg.modules) ? msg.modules.map((m) => m?.id).filter(Boolean) : [];
2057
- notifyAppHmrUpdate('full-graph', fullIds);
2058
- return;
2059
- }
2060
- if (msg.type === 'ns:ts-module-registry') {
2061
- try {
2062
- const mods = Array.isArray(msg.modules) ? msg.modules.filter((m) => typeof m === 'string') : [];
2063
- if (mods.length) {
2064
- if (!tsModuleSet)
2065
- tsModuleSet = new Set();
2066
- mods.forEach((m) => tsModuleSet.add(m));
2067
- // Prefer explicit app main entry if present, else first module
2068
- if (mods.includes(APP_MAIN_ENTRY_SPEC)) {
2069
- tsMainId = APP_MAIN_ENTRY_SPEC;
2070
- }
2071
- else if (!tsMainId) {
2072
- tsMainId = mods[0];
2073
- }
2074
- if (VERBOSE)
2075
- console.log('[hmr-client][ts-registry] registered TS modules', {
2076
- count: tsModuleSet.size,
2077
- mainId: tsMainId,
2078
- });
2079
- }
2080
- }
2081
- catch (e) {
2082
- if (VERBOSE)
2083
- console.warn('[hmr-client][ts-registry] failed to record', e);
2084
- }
2085
- return;
2086
- }
2087
- if (msg.type === 'ns:hmr-delta') {
2088
- // Bump a monotonic nonce so HTTP ESM imports can always be cache-busted per update.
2089
- try {
2090
- const g = getGlobalScope();
2091
- g.__NS_HMR_IMPORT_NONCE__ = (typeof g.__NS_HMR_IMPORT_NONCE__ === 'number' ? g.__NS_HMR_IMPORT_NONCE__ : 0) + 1;
2092
- }
2093
- catch { }
2094
- try {
2095
- const ids = Array.isArray(msg.changed) ? msg.changed.map((c) => c?.id).filter(Boolean) : [];
2096
- if (ids.length)
2097
- txnClientBatches.set(getGraphVersion(), ids);
2098
- }
2099
- catch { }
2100
- applyDelta(msg);
2101
- // Ensure queued module re-imports complete before notifying app hooks.
2102
- // Otherwise app-level handlers can run against stale module bodies due to HTTP ESM caching.
2103
- try {
2104
- await processQueue();
2105
- }
2106
- catch { }
2107
- const deltaIds = Array.isArray(msg.changed) ? msg.changed.map((c) => c?.id).filter(Boolean) : [];
2108
- notifyAppHmrUpdate('delta', deltaIds);
2109
- return;
2110
- }
2111
- else {
2112
- // Vite custom-event dispatch.
2113
- //
2114
- // `server.ws.send('event-name', payload)` from any Vite plugin lands
2115
- // on the wire as `{ type: 'custom', event: 'event-name', data: payload }`.
2116
- // On the web, Vite's stock client owns a `customListenersMap` that
2117
- // fires every `import.meta.hot.on('event-name', cb)` callback. We
2118
- // don't run Vite's stock client on device — the JS hot registry
2119
- // (`hot-context.ts`, installed by the bootstrap before the entry
2120
- // graph) owns the listener registry populated by user code +
2121
- // compiled Angular components via `import.meta.hot.on`.
2122
- // Forwarding `type: 'custom'` here is the only thing standing
2123
- // between server-emitted events and the listeners they were
2124
- // meant for.
2125
- //
2126
- // `angular:component-update` is the canonical example. Analog's
2127
- // plugin sends it on `.html` / component-style edits; the
2128
- // compiled component `.mjs` registered a listener that
2129
- // dynamic-imports `/@ng/component?c=<id>&t=<ts>` and calls
2130
- // `ɵɵreplaceMetadata` on the live class — swapping the template
2131
- // definition AND walking live `LView`s to recreate matching views
2132
- // in-place. The page stays mounted and only the changed bits
2133
- // re-render. We MUST `return` after dispatch so the reboot path
2134
- // (`handleAngularHotUpdateMessage` → `__reboot_ng_modules__`)
2135
- // never runs for these updates — that's the whole point of the
2136
- // component-replacement pipeline.
2137
- //
2138
- // All other custom events are forwarded but NOT short-circuited
2139
- // (Vite spec: custom events are additive — they don't replace
2140
- // any framework-specific handling). The reboot path falls through
2141
- // for `ns:angular-update` (the legacy/`.ts`-edit broadcast) and
2142
- // for any framework not yet using the in-place replacement path.
2143
- if (msg.type === 'custom' && typeof msg.event === 'string') {
2144
- // Dispatch every Vite "custom" event through the JS hot
2145
- // registry so `import.meta.hot.on(event, cb)` callbacks fire
2146
- // on the device. Critical contract: this is the ONLY route by
2147
- // which Analog's `angular:component-update` reaches the
2148
- // compiled component's `(d) => d.id === id && Component_HmrLoad(...)`
2149
- // listener — without it, server-side broadcasts log green
2150
- // (`(client) hmr update`) while the device sees nothing happen.
2151
- //
2152
- // Diagnostic policy: listener exceptions log loud (compiled
2153
- // HmrLoad fetch/parse error). Successful dispatches are silent.
2154
- try {
2155
- getNsHotRegistry().dispatchHotEvent(msg.event, msg.data);
2156
- }
2157
- catch (err) {
2158
- console.warn('[hmr-client][custom] dispatch threw for', msg.event, err);
2159
- }
2160
- if (msg.event === 'angular:component-update') {
2161
- if (VERBOSE)
2162
- console.log('[hmr-client][custom] dispatched angular:component-update — skipping reboot path');
2163
- // Walk the apply-progress overlay through its
2164
- // remaining stages for the in-place template-swap
2165
- // path. The full reboot path
2166
- // (`handleAngularHotUpdateMessage`) drives the
2167
- // overlay itself ('received' → 'evicting' →
2168
- // 'reimporting' → 'rebooting' → 'complete'); the
2169
- // in-place path bypasses that handler entirely
2170
- // because the work happens inside Angular's
2171
- // `ɵɵreplaceMetadata` after the runtime forwards the
2172
- // `angular:component-update` event to the compiled
2173
- // component's listener. Without this update the
2174
- // overlay would freeze at 5% ('received') even
2175
- // though the visual swap completes a few frames
2176
- // later — exactly the "Preparing update (5%)" stuck
2177
- // frame we have been chasing.
2178
- //
2179
- // We transition straight to 'reimporting' to
2180
- // communicate that metadata is being fetched (the
2181
- // runtime listener fires `__ns_import('/@ng/component?c=...&t=...')`),
2182
- // then schedule 'complete' on the next macrotask so
2183
- // the auto-hide timer kicks in. The actual
2184
- // template swap is fire-and-forget from this point;
2185
- // the user sees the overlay close at the same time
2186
- // as Angular re-renders the bound text/structure.
2187
- try {
2188
- const filePath = typeof msg.data?.id === 'string' ? decodeURIComponent(msg.data.id).split('@')[0] : undefined;
2189
- const detail = filePath ? `Applying template update to ${filePath}` : 'Applying template update';
2190
- setUpdateOverlayStage('reimporting', { detail });
2191
- setTimeout(() => {
2192
- try {
2193
- setUpdateOverlayStage('complete', { detail: filePath ? `Updated ${filePath}` : 'Update applied' });
2194
- }
2195
- catch { }
2196
- }, 16);
2197
- }
2198
- catch { }
2199
- return;
2200
- }
2201
- }
2202
- if (msg.type === 'ns:angular-update' && typeof msg.version === 'number') {
2203
- setGraphVersion(Number(msg.version || getGraphVersion() || 0));
2204
- }
2205
- if (CLIENT_STRATEGY?.handleHotUpdateMessage && (await CLIENT_STRATEGY.handleHotUpdateMessage(msg, { getCore, verbose: VERBOSE, performResetRoot, getOverlay: getHmrOverlayApi }))) {
2206
- return;
2207
- }
2208
- }
2209
- }
2210
- // On-demand module fetch response (Option A)
2211
- if (msg.type === 'ns:module-response' && typeof msg.requestId === 'number') {
2212
- const pending = pendingModuleFetches.get(msg.requestId);
2213
- if (pending) {
2214
- pendingModuleFetches.delete(msg.requestId);
2215
- if (msg.error) {
2216
- if (VERBOSE)
2217
- console.warn('[hmr-fetch] error', msg.error, 'spec=', pending.spec, 'id=', msg.requestId);
2218
- pending.reject(new Error(`[hmr-fetch] ${msg.error} for ${pending.spec}`));
2219
- }
2220
- else {
2221
- try {
2222
- const origin = getHttpOriginForVite() || deriveHttpOrigin(getHMRWsUrl());
2223
- if (!origin)
2224
- throw new Error('no-http-origin');
2225
- const url = origin + '/ns/m' + (String(pending.spec).startsWith('/') ? pending.spec : '/' + pending.spec);
2226
- moduleFetchCache.set(pending.spec, url);
2227
- if (VERBOSE)
2228
- console.log('[hmr-fetch] resolved via URL', pending.spec, '->', url, 'id=', msg.requestId);
2229
- pending.resolve(url);
2230
- }
2231
- catch (e) {
2232
- pending.reject(e);
2233
- }
2234
- }
2235
- }
2236
- return;
2237
- }
2238
- if (msg.type === 'ns:css-updates' && Array.isArray(msg.updates)) {
2239
- // Drive the HMR-applying overlay past the 'received' (5%) frame
2240
- // that `ns:hmr-pending` set earlier in the cycle. Without this
2241
- // the overlay sticks at "Preparing update" forever for CSS-only
2242
- // edits because `handleCssUpdates` is a leaf — there's no
2243
- // downstream module-evaluation path that would hit the queue's
2244
- // 'complete' transition.
2245
- const cssCount = msg.updates.length;
2246
- try {
2247
- setUpdateOverlayStage('reimporting', { detail: buildCssApplyingDetail(cssCount) });
2248
- }
2249
- catch { }
2250
- try {
2251
- const origin = msg.origin || getHttpOriginForVite() || deriveHttpOrigin(getHMRWsUrl());
2252
- await handleCssUpdates(msg.updates, origin);
2253
- try {
2254
- setUpdateOverlayStage('complete', { detail: buildCssAppliedDetail(cssCount) });
2255
- }
2256
- catch { }
2257
- return;
2258
- }
2259
- catch (e) {
2260
- console.warn('[hmr-client] CSS updates handling failed:', e);
2261
- try {
2262
- setUpdateOverlayStage('complete', { detail: 'CSS update failed' });
2263
- }
2264
- catch { }
2265
- return;
2266
- }
2267
- }
2268
- if (msg.type === 'ns:vue-sfc-registry') {
2269
- CLIENT_STRATEGY?.handleSfcRegistry?.(msg);
2270
- return;
2271
- }
2272
- if (msg.type === 'ns:vue-sfc-registry-update') {
2273
- if (typeof msg.version === 'number')
2274
- setGraphVersion(msg.version);
2275
- // `ns:hmr-pending` already set the overlay to 'received' (5%). The Vue
2276
- // strategy walks 'evicting' → 'reimporting' → 'rebooting' → 'complete'
2277
- // around the SFC load + reset so the toast always lands on 'complete'
2278
- // (or a failure detail) and the auto-hide timer can dismiss it.
2279
- await CLIENT_STRATEGY?.handleSfcRegistryUpdate?.(msg, getGraphVersion(), { getCore, verbose: VERBOSE, performResetRoot, getOverlay: getHmrOverlayApi });
2280
- return;
2281
- }
2282
- }
2283
- function normalizeComponent(input, nameHint) {
2284
- try {
2285
- if (!input)
2286
- return null;
2287
- // Unwrap module namespace with default
2288
- if (input && typeof input === 'object' && 'default' in input) {
2289
- const d = input.default;
2290
- if (d)
2291
- return normalizeComponent(d, nameHint);
2292
- }
2293
- // If already a component-like object with render/setup/template, return as-is
2294
- if (typeof input === 'object' && (input.render || input.setup || input.template || input.__isVue)) {
2295
- return input;
2296
- }
2297
- // If provided a render function, wrap with defineComponent
2298
- if (typeof input === 'function') {
2299
- CLIENT_STRATEGY?.beforeNavigateBuild?.();
2300
- const comp = getGlobalScope().defineComponent
2301
- ? getGlobalScope().defineComponent({
2302
- name: nameHint || input.name || 'AnonymousSFC',
2303
- render: input,
2304
- })
2305
- : { name: nameHint || input.name || 'AnonymousSFC', render: input };
2306
- return comp;
2307
- }
2308
- // If object has a render function property
2309
- if (input?.render && typeof input.render === 'function') {
2310
- CLIENT_STRATEGY?.beforeNavigateBuild?.();
2311
- const comp = getGlobalScope().defineComponent
2312
- ? getGlobalScope().defineComponent({
2313
- name: nameHint || input.name || 'AnonymousSFC',
2314
- render: input.render,
2315
- })
2316
- : {
2317
- name: nameHint || input.name || 'AnonymousSFC',
2318
- render: input.render,
2319
- };
2320
- return comp;
2321
- }
2322
- }
2323
- catch { }
2324
- return input;
2325
- }
2326
- async function performResetRoot(newComponent) {
2327
- const tStart = Date.now();
2328
- // Guard against re-entrant or rapid successive resets
2329
- try {
2330
- globalThis.__NS_DEV_RESET_IN_PROGRESS__ = true;
2331
- }
2332
- catch { }
2333
- try {
2334
- ensureCoreAliasesOnGlobalThis();
2335
- }
2336
- catch { }
2337
- if (VERBOSE) {
2338
- console.log('[hmr-client] Single-path: replace current root Page');
2339
- console.log('[hmr-client] Component details:', {
2340
- componentName: newComponent?.__name,
2341
- componentFile: newComponent?.__file,
2342
- hasRender: !!newComponent?.render,
2343
- hasSetup: !!newComponent?.setup,
2344
- componentKeys: Object.keys(newComponent || {}),
2345
- });
2346
- }
2347
- function createRootFactory() {
2348
- let rootKind = 'page';
2349
- let cachedRoot = undefined;
2350
- const state = {
2351
- getRootKind: () => rootKind,
2352
- setRootKind: (k) => {
2353
- rootKind = k;
2354
- },
2355
- getCachedRoot: () => cachedRoot,
2356
- setCachedRoot: (r) => {
2357
- cachedRoot = r;
2358
- },
2359
- };
2360
- const factory = {
2361
- get kind() {
2362
- return rootKind;
2363
- },
2364
- create: () => {
2365
- if (cachedRoot)
2366
- return cachedRoot;
2367
- try {
2368
- if (CLIENT_STRATEGY?.createRoot) {
2369
- cachedRoot = CLIENT_STRATEGY.createRoot(newComponent, state);
2370
- }
2371
- else if (TS_LIKE_FLAVOR) {
2372
- // For TS flavor, treat the component as a factory or direct NS view.
2373
- let root = null;
2374
- try {
2375
- if (typeof newComponent === 'function') {
2376
- root = newComponent();
2377
- }
2378
- else {
2379
- root = newComponent;
2380
- }
2381
- }
2382
- catch (e) {
2383
- console.warn('[hmr-client][ts] root factory invocation failed', e);
2384
- }
2385
- cachedRoot = root || {};
2386
- // Heuristic: if the root "looks" like a Frame, prefer frame semantics
2387
- try {
2388
- const name = String(cachedRoot?.constructor?.name || '').replace(/^_+/, '');
2389
- if (/^Frame(\$\d+)?$/.test(name)) {
2390
- rootKind = 'frame';
2391
- }
2392
- }
2393
- catch { }
2394
- }
2395
- return cachedRoot;
2396
- }
2397
- catch (e) {
2398
- console.warn('[hmr-client] createRootFactory failed', e);
2399
- if (VERBOSE)
2400
- console.warn('[hmr-client] [createRoot] stack', e?.stack);
2401
- const GPage = getCore('Page');
2402
- rootKind = 'page';
2403
- cachedRoot = GPage ? new GPage() : {};
2404
- return cachedRoot;
2405
- }
2406
- },
2407
- };
2408
- return factory;
2409
- }
2410
- // Android readiness before any root changes
2411
- const App = getCore('Application') || getGlobalScope().Application;
2412
- const isAndroid = !!(App && App.android !== undefined);
2413
- if (isAndroid) {
2414
- const isReady = () => {
2415
- try {
2416
- const a = App.android;
2417
- const act = a && (a.foregroundActivity || a.startActivity);
2418
- return !!act;
2419
- }
2420
- catch {
2421
- return false;
2422
- }
2423
- };
2424
- const waitFor = async (pred, ms = 6000, step = 60) => {
2425
- const start = Date.now();
2426
- while (Date.now() - start < ms) {
2427
- if (pred())
2428
- return true;
2429
- await new Promise((r) => setTimeout(r, step));
2430
- }
2431
- return pred();
2432
- };
2433
- const withEvents = async (ms = 6000) => {
2434
- try {
2435
- const a = App.android;
2436
- if (!a || typeof a.on !== 'function' || typeof a.off !== 'function') {
2437
- if (VERBOSE)
2438
- console.log('[hmr-client] [android] events API not available; polling');
2439
- return await waitFor(isReady, ms, 60);
2440
- }
2441
- if (isReady()) {
2442
- if (VERBOSE)
2443
- console.log('[hmr-client] [android] activity already ready');
2444
- return true;
2445
- }
2446
- return await new Promise((resolve) => {
2447
- let done = false;
2448
- const tWait = Date.now();
2449
- const finish = (ok) => {
2450
- if (done)
2451
- return;
2452
- done = true;
2453
- try {
2454
- a.off(a.activityStartedEvent || 'activityStarted', onAny);
2455
- a.off(a.activityResumedEvent || 'activityResumed', onAny);
2456
- }
2457
- catch { }
2458
- if (VERBOSE)
2459
- console.log('[hmr-client] [android] readiness result', {
2460
- ok,
2461
- elapsedMs: Date.now() - tWait,
2462
- });
2463
- resolve(ok);
2464
- };
2465
- const onAny = (evt) => {
2466
- if (VERBOSE)
2467
- console.log('[hmr-client] [android] activity event', {
2468
- type: evt?.eventName || 'unknown',
2469
- });
2470
- if (isReady())
2471
- finish(true);
2472
- };
2473
- try {
2474
- a.on(a.activityStartedEvent || 'activityStarted', onAny);
2475
- a.on(a.activityResumedEvent || 'activityResumed', onAny);
2476
- if (VERBOSE)
2477
- console.log('[hmr-client] [android] waiting for activity events…');
2478
- }
2479
- catch {
2480
- return resolve(waitFor(isReady, ms, 60));
2481
- }
2482
- setTimeout(() => finish(isReady()), ms);
2483
- });
2484
- }
2485
- catch {
2486
- return await waitFor(isReady, ms, 60);
2487
- }
2488
- };
2489
- const ok = await withEvents(6000);
2490
- if (!ok && VERBOSE)
2491
- console.warn('[hmr-client] [android] activity not ready; proceeding with best-effort');
2492
- }
2493
- // Create the new root first to determine whether it is a Page or a Frame
2494
- const rootFactory = createRootFactory();
2495
- const preparedRoot = rootFactory.create();
2496
- const isFrameRoot = (() => {
2497
- try {
2498
- const name = String(preparedRoot?.constructor?.name || '').replace(/^_+/, '');
2499
- return /^Frame(\$\d+)?$/.test(name);
2500
- }
2501
- catch {
2502
- return false;
2503
- }
2504
- })();
2505
- // Prefer resetRootView on initial boot (placeholder present) or on iOS to avoid early createRootView races
2506
- let hadPlaceholder = false;
2507
- let isIOS = false;
2508
- try {
2509
- hadPlaceholder = !!globalThis.__NS_DEV_PLACEHOLDER_ROOT_EARLY__;
2510
- }
2511
- catch { }
2512
- try {
2513
- const AppAny = getCore('Application') || getGlobalScope().Application;
2514
- isIOS = !!(AppAny && AppAny.ios !== undefined);
2515
- }
2516
- catch { }
2517
- // Preferred policy:
2518
- // - If this is the very first mount (placeholder present), or if the new root is a Frame,
2519
- // perform a full root replacement via resetRootView so we never couple with the placeholder.
2520
- // - Otherwise (subsequent HMR updates with an authoritative Frame already in place), re-use the
2521
- // current app Frame and navigate to the new Page. This avoids a brief flash that can occur
2522
- // when swapping the entire root view on Android. The placeholder is never involved here.
2523
- const gAnyForPolicy = getGlobalScope();
2524
- const placeholderFrame = (() => {
2525
- try {
2526
- return gAnyForPolicy.__NS_DEV_PLACEHOLDER_ROOT_VIEW__ || null;
2527
- }
2528
- catch {
2529
- return null;
2530
- }
2531
- })();
2532
- let existingAppFrame = null;
2533
- try {
2534
- existingAppFrame = getRootFrame() || getCore('Frame')?.topmost?.() || null;
2535
- }
2536
- catch { }
2537
- const isAuthoritativeFrame = !!existingAppFrame && existingAppFrame !== placeholderFrame;
2538
- // Vue: skip the in-place navigate path. After `app.mount(NSVRoot)` in getRootForVue the
2539
- // new Page already has a parent (the freshly-constructed NSVRoot), so an attempt to navigate
2540
- // the existing app Frame to that same Page completes silently without ever rebinding the
2541
- // page to the Frame — the screen keeps showing the previous render. resetRootView with a
2542
- // fresh Frame correctly reparents the Page and is the proven path that produces visible
2543
- // in-place updates for SFC HMR cycles. Non-Vue flavors keep the legacy navigate fast path.
2544
- const allowNavigateFastPath = CLIENT_STRATEGY?.allowNavigateFastPath ?? true;
2545
- if (allowNavigateFastPath && !hadPlaceholder && !isFrameRoot && isAuthoritativeFrame && typeof existingAppFrame.navigate === 'function') {
2546
- try {
2547
- const navEntry = {
2548
- create: () => preparedRoot,
2549
- clearHistory: true,
2550
- animated: false,
2551
- };
2552
- existingAppFrame.navigate(navEntry);
2553
- setRootFrame(existingAppFrame);
2554
- return true;
2555
- }
2556
- catch (e) {
2557
- console.warn('[hmr-client] authoritative navigate fallback to resetRootView due to error', e);
2558
- }
2559
- }
2560
- if (VERBOSE)
2561
- console.log('[hmr-client] full root replacement via resetRootView (placeholder will be discarded)', { isFrameRoot, isIOS, hadPlaceholder });
2562
- // Fallback or preferred path: resetRootView with a creator that builds a fresh Frame and navigates to the new Page
2563
- try {
2564
- const App2 = getCore('Application') || getGlobalScope().Application;
2565
- if (!App2 || typeof App2.resetRootView !== 'function') {
2566
- console.warn('[hmr-client] Application.resetRootView unavailable');
2567
- return false;
2568
- }
2569
- // iOS-specific: if the cached window was left in an invalid state (boolean false), clear it so
2570
- // setWindowContent can recreate a proper UIWindow. This can occur in rare early-boot races.
2571
- try {
2572
- const isIos = !!(App2 && App2.ios !== undefined);
2573
- if (isIos) {
2574
- let win = undefined;
2575
- try {
2576
- win = App2.window;
2577
- }
2578
- catch { }
2579
- if (win === false) {
2580
- if (VERBOSE)
2581
- console.warn('[hmr-client] iOS Application.window is boolean false; attempting to clear cached window');
2582
- try {
2583
- const g = getGlobalScope();
2584
- const reg = g.__nsVendorRegistry;
2585
- const req = reg?.get ? g.__nsVendorRequire || g.__nsRequire || g.require : g.__nsRequire || g.require;
2586
- let helpers = null;
2587
- // Try vendor registry first
2588
- if (reg && reg.has('@nativescript/core/application/helpers-common')) {
2589
- helpers = reg.get('@nativescript/core/application/helpers-common');
2590
- }
2591
- // Fallback to device require
2592
- if (!helpers && typeof req === 'function') {
2593
- try {
2594
- helpers = req('@nativescript/core/application/helpers-common');
2595
- }
2596
- catch { }
2597
- }
2598
- const setter = helpers && (helpers.setiOSWindow || helpers.default?.setiOSWindow);
2599
- if (typeof setter === 'function') {
2600
- try {
2601
- setter(undefined);
2602
- if (VERBOSE)
2603
- console.log('[hmr-client] cleared cached iOS window via helpers-common');
2604
- }
2605
- catch { }
2606
- }
2607
- }
2608
- catch { }
2609
- }
2610
- }
2611
- }
2612
- catch { }
2613
- // Use the previously created preparedRoot
2614
- const entry = {
2615
- create: () => {
2616
- if (!isFrameRoot) {
2617
- const F = getCore('Frame');
2618
- const fr = new F();
2619
- if (VERBOSE)
2620
- console.log('[hmr-client] resetRootView:create new Frame', {
2621
- type: fr?.constructor?.name,
2622
- });
2623
- const navEntry = {
2624
- create: () => preparedRoot,
2625
- clearHistory: true,
2626
- animated: false,
2627
- };
2628
- try {
2629
- fr.navigate(navEntry);
2630
- }
2631
- catch (e) {
2632
- console.warn('[hmr-client] resetRootView:create navigate failed', e);
2633
- }
2634
- setRootFrame(fr);
2635
- return fr;
2636
- }
2637
- else {
2638
- const fr = preparedRoot;
2639
- setRootFrame(fr);
2640
- return fr;
2641
- }
2642
- },
2643
- };
2644
- // Always use an entry with a create() function to avoid cross‑realm instanceof checks on Android.
2645
- App2.resetRootView(entry);
2646
- // After authoritative reset, it's safe to detach the early placeholder launch handler
2647
- try {
2648
- const restore = globalThis.__NS_DEV_RESTORE_PLACEHOLDER__;
2649
- if (typeof restore === 'function') {
2650
- restore();
2651
- }
2652
- }
2653
- catch { }
2654
- return true;
2655
- }
2656
- catch (e) {
2657
- console.warn('[hmr-client] resetRootView failed', e);
2658
- try {
2659
- if (VERBOSE)
2660
- console.warn('[hmr-client] resetRootView stack', e?.stack);
2661
- }
2662
- catch { }
2663
- return false;
2664
- }
2665
- finally {
2666
- try {
2667
- globalThis.__NS_DEV_RESET_IN_PROGRESS__ = false;
2668
- }
2669
- catch { }
2670
- }
2671
- }
97
+ // Route incoming socket messages through the protocol dispatcher.
98
+ setHmrMessageHandler(handleHmrMessage);
2672
99
  export function initHmrClient(opts) {
2673
100
  if (opts?.wsUrl) {
2674
101
  setHMRWsUrl(opts.wsUrl);
@@ -2684,20 +111,6 @@ export function initHmrClient(opts) {
2684
111
  }
2685
112
  g.__NS_HMR_CLIENT_ACTIVE__ = true;
2686
113
  ensureCoreAliasesOnGlobalThis();
2687
- // XML flavor: record string-module modals from the moment the client is up
2688
- // so an already-open modal can be re-presented when its files change.
2689
- // Installed at init (not first-update time) because the wrap can only
2690
- // observe showModal calls made AFTER it lands. Retried briefly because
2691
- // getCore('View') may not resolve until the vendor realm finishes booting.
2692
- if (TS_LIKE_FLAVOR) {
2693
- const tryInstallModalTracking = (attempts) => {
2694
- ensureModalTracking();
2695
- if (!modalTrackingInstalled && attempts > 0) {
2696
- setTimeout(() => tryInstallModalTracking(attempts - 1), 250);
2697
- }
2698
- };
2699
- tryInstallModalTracking(40);
2700
- }
2701
114
  // Defer WebSocket connection until boot completes to avoid native V8 crashes
2702
115
  // caused by concurrent WebSocket message handling + HTTP fetch during early startup.
2703
116
  // The WebSocket is only needed for HMR updates, not the initial boot sequence.
@@ -2721,7 +134,7 @@ export function initHmrClient(opts) {
2721
134
  }
2722
135
  // Best-effort: install back wrapper even before first remount; original root may be captured later.
2723
136
  // Deferred until the dynamically-imported strategy resolves.
2724
- void CLIENT_STRATEGY_READY.then(() => CLIENT_STRATEGY?.installBackWrapper?.(performResetRoot, getCore));
137
+ void CLIENT_STRATEGY_READY.then(() => getClientStrategy()?.installBackWrapper?.(performResetRoot, getCore));
2725
138
  }
2726
139
  export default function startViteHMR(opts) {
2727
140
  if (VERBOSE)