@nativescript/vite 0.0.1-alpha.0 → 0.0.1-alpha.2

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 (55) hide show
  1. package/dist/configuration/base.js +178 -71
  2. package/dist/helpers/external-configs.js +1 -1
  3. package/dist/helpers/global-defines.d.ts +1 -0
  4. package/dist/helpers/global-defines.js +2 -0
  5. package/dist/helpers/main-entry-hmr-includes.d.ts +1 -0
  6. package/dist/helpers/main-entry-hmr-includes.js +18 -0
  7. package/dist/helpers/main-entry.d.ts +3 -3
  8. package/dist/helpers/main-entry.js +61 -54
  9. package/dist/helpers/module-runner-patch.d.ts +3 -0
  10. package/dist/helpers/module-runner-patch.js +65 -0
  11. package/dist/helpers/ns-cli-plugins.d.ts +4 -14
  12. package/dist/helpers/ns-cli-plugins.js +124 -101
  13. package/dist/helpers/package-platform-aliases.d.ts +1 -1
  14. package/dist/helpers/package-platform-aliases.js +4 -4
  15. package/dist/helpers/preserve-imports.d.ts +2 -0
  16. package/dist/helpers/preserve-imports.js +19 -0
  17. package/dist/helpers/ts-config-paths.d.ts +1 -1
  18. package/dist/helpers/ts-config-paths.js +6 -4
  19. package/dist/hmr/client-vue.d.ts +6 -0
  20. package/dist/hmr/client-vue.js +563 -0
  21. package/dist/hmr/component-tracker.d.ts +23 -0
  22. package/dist/hmr/component-tracker.js +193 -0
  23. package/dist/hmr/css-handler.d.ts +4 -0
  24. package/dist/hmr/css-handler.js +77 -0
  25. package/dist/hmr/message-handler.d.ts +1 -0
  26. package/dist/hmr/message-handler.js +590 -0
  27. package/dist/hmr/nsv-hooks.d.ts +2 -0
  28. package/dist/hmr/nsv-hooks.js +481 -0
  29. package/dist/hmr/plugin-vue.d.ts +2 -0
  30. package/dist/hmr/plugin-vue.js +38 -0
  31. package/dist/hmr/plugins/index.d.ts +1 -0
  32. package/dist/hmr/plugins/index.js +16 -0
  33. package/dist/hmr/plugins/plugin-vue.d.ts +2 -0
  34. package/dist/hmr/plugins/plugin-vue.js +41 -0
  35. package/dist/hmr/plugins/websocket-vue.d.ts +2 -0
  36. package/dist/hmr/plugins/websocket-vue.js +882 -0
  37. package/dist/hmr/runtime-vue.d.ts +13 -0
  38. package/dist/hmr/runtime-vue.js +2306 -0
  39. package/dist/hmr/types.d.ts +24 -0
  40. package/dist/hmr/types.js +2 -0
  41. package/dist/hmr/websocket-vue.d.ts +2 -0
  42. package/dist/hmr/websocket-vue.js +875 -0
  43. package/dist/shims/node-module.d.ts +5 -0
  44. package/dist/shims/node-module.js +12 -0
  45. package/package.json +2 -1
  46. package/dist/configuration/old-without-merge-base.d.ts +0 -13
  47. package/dist/configuration/old-without-merge-base.js +0 -249
  48. package/dist/hmr/hmr-angular.d.ts +0 -1
  49. package/dist/hmr/hmr-angular.js +0 -34
  50. package/dist/hmr/hmr-bridge.d.ts +0 -18
  51. package/dist/hmr/hmr-bridge.js +0 -154
  52. package/dist/hmr/hmr-client.d.ts +0 -5
  53. package/dist/hmr/hmr-client.js +0 -93
  54. package/dist/hmr/hmr-server.d.ts +0 -20
  55. package/dist/hmr/hmr-server.js +0 -179
@@ -0,0 +1,5 @@
1
+ export declare function createRequire(_url: string): any;
2
+ declare const _default: {
3
+ createRequire: typeof createRequire;
4
+ };
5
+ export default _default;
@@ -0,0 +1,12 @@
1
+ // Minimal shim for `node:module` to satisfy imports from vite/module-runner.
2
+ // We only provide createRequire to avoid hard crashes; it is a noop in NS.
3
+ export function createRequire(_url) {
4
+ const req = function () {
5
+ throw new Error("createRequire is not supported in NativeScript runtime");
6
+ };
7
+ req.resolve = function () {
8
+ throw new Error("require.resolve is not supported in NativeScript runtime");
9
+ };
10
+ return req;
11
+ }
12
+ export default { createRequire };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativescript/vite",
3
- "version": "0.0.1-alpha.0",
3
+ "version": "0.0.1-alpha.2",
4
4
  "description": "Vite for NativeScript",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -19,6 +19,7 @@
19
19
  "@angular/build": "^20.0.0",
20
20
  "@rollup/plugin-alias": "^5.1.1",
21
21
  "@rollup/plugin-commonjs": "^28.0.0",
22
+ "@rollup/plugin-replace": "^6.0.2",
22
23
  "@vitejs/plugin-vue": "^6.0.1",
23
24
  "@vitejs/plugin-vue-jsx": "^5.1.1",
24
25
  "minimist": "^1.2.8",
@@ -1,13 +0,0 @@
1
- import type { UserConfig } from "vite";
2
- export declare const baseConfig: ({ mode, skipCommonjsPackages, customCommonjsPlugins, commonjsIgnoreList, optimizeDeps, }: {
3
- mode: string;
4
- skipCommonjsPackages?: string[];
5
- customCommonjsPlugins?: {
6
- name: string;
7
- enforce: string;
8
- resolveId(id: any): any;
9
- load(id: any): string;
10
- }[];
11
- commonjsIgnoreList?: string[];
12
- optimizeDeps?: string[];
13
- }) => UserConfig;
@@ -1,249 +0,0 @@
1
- import path from "path";
2
- import minimist from "minimist";
3
- import commonjs from "@rollup/plugin-commonjs";
4
- import NativeScriptPlugin from "../helpers/resolver.js";
5
- import nsConfigAsJsonPlugin from "../helpers/config-as-json.js";
6
- import { getProjectRootPath } from "../helpers/project.js";
7
- import { aliasCssTree } from "../helpers/css-tree.js";
8
- import { packagePlatformAliases } from "../helpers/package-platform-aliases.js";
9
- import { getGlobalDefines } from "../helpers/global-defines.js";
10
- import { getWorkerPlugins, workerUrlPlugin } from "../helpers/workers.js";
11
- import { getTsConfigData } from "../helpers/ts-config-paths.js";
12
- import { commonjsPlugins } from "../helpers/commonjs-plugins.js";
13
- import { nativescriptPackageResolver } from "../helpers/nativescript-package-resolver.js";
14
- import { hmrPlugin, cliPlugin } from "../helpers/ns-cli-plugins.js";
15
- import { dynamicImportPlugin } from "../helpers/dynamic-import-plugin.js";
16
- import { mainEntryPlugin } from "../helpers/main-entry.js";
17
- import { determineProjectFlavor } from "../helpers/flavor.js";
18
- const debugViteLogs = !!process.env.VITE_DEBUG_PATHS;
19
- const projectRoot = getProjectRootPath();
20
- // NOTE: just testing with angular directly temporarily
21
- // change this to pick up environment for flavors dynamically
22
- // import { angularPlugins } from "./angular.js";
23
- // import { getReactPlugins } from "./react.js";
24
- // import { getSolidPlugins } from "./solid.js";
25
- // import { vuePlugins } from "./vue.js";
26
- export const baseConfig = ({ mode, skipCommonjsPackages, customCommonjsPlugins, commonjsIgnoreList, optimizeDeps, }) => {
27
- const platform = mode;
28
- const targetMode = process.env.production ? "production" : "development";
29
- const cliArgs = minimist(process.argv.slice(2), { "--": true });
30
- const cliFlags = (cliArgs["--"] || []).reduce((obj, flag) => {
31
- // remove env prefix
32
- const [rawKey, ...rest] = flag.replace(/^--env\./, "").split("=");
33
- obj[rawKey] = rest.length === 0 ? true : rest.join("=");
34
- return obj;
35
- }, {});
36
- console.log("cliFlags:", cliFlags);
37
- const debug = !!cliFlags.viteDebug || !!process.env.DEBUG || targetMode === "development";
38
- if (debug) {
39
- console.log("--------------");
40
- console.log("Vite config mode:", mode);
41
- console.log("Target mode:", targetMode);
42
- console.log("Platform:", platform);
43
- console.log("--------------");
44
- }
45
- const flavor = determineProjectFlavor();
46
- console.log(`Building with ${flavor}`);
47
- // let flavorPlugins: any[] = [];
48
- switch (flavor) {
49
- // case "angular":
50
- // flavorPlugins = angularPlugins;
51
- // break;
52
- // case "react":
53
- // flavorPlugins = getReactPlugins(!debug);
54
- // break;
55
- // case "vue":
56
- // flavorPlugins = vuePlugins;
57
- // break;
58
- // case "solid":
59
- // flavorPlugins = getSolidPlugins(!debug);
60
- // break;
61
- }
62
- // Create TypeScript aliases with platform support
63
- const tsConfigData = getTsConfigData(debugViteLogs, platform);
64
- // Common resolve configuration for both main and worker builds
65
- const resolveConfig = {
66
- // ensures Vite prefers ESM entry‑points
67
- mainFields: ["module", "main"],
68
- // Make sure ESM conditions win during resolution
69
- conditions: ["module", "import", "browser", "default"],
70
- // use this with merge config instead or could list common dedupes in base here altogether
71
- dedupe: ["@nativescript/core", "nativescript-vue", "vue"],
72
- // Alias "@" and "~" to your src directory for cleaner imports
73
- alias: [
74
- ...aliasCssTree,
75
- // 1) Catch exactly `~/package.json` → virtual module (MUST be first!)
76
- { find: /^~\/package\.json$/, replacement: "~/package.json" },
77
- // TypeScript path aliases from tsconfig.json
78
- ...tsConfigData.aliases,
79
- // Generic platform resolution for any npm package
80
- packagePlatformAliases(tsConfigData, platform, true),
81
- // 2) Catch everything else under "~/" → your src/
82
- { find: /^~\/(.*)$/, replacement: path.resolve(projectRoot, "src/$1") },
83
- // optional: "@" → src/
84
- { find: "@", replacement: path.resolve(projectRoot, "src") },
85
- ],
86
- extensions: [
87
- ".ios.tsx",
88
- ".android.tsx",
89
- ".tsx",
90
- ".ios.jsx",
91
- ".android.jsx",
92
- ".jsx",
93
- ".ios.ts",
94
- ".android.ts",
95
- ".ts",
96
- ".ios.js",
97
- ".android.js",
98
- ".js",
99
- ".mjs",
100
- ".json",
101
- ],
102
- preserveSymlinks: true,
103
- };
104
- // Common define configuration for both main and worker builds
105
- const defineConfig = getGlobalDefines(platform, targetMode);
106
- return {
107
- resolve: resolveConfig,
108
- define: defineConfig,
109
- // Vite's built-in solution for CommonJS/ESM compatibility issues
110
- optimizeDeps: {
111
- // Force pre-bundling of problematic CommonJS packages
112
- include: [
113
- // "source-map-js",
114
- "@valor/nativescript-websockets",
115
- // React and related packages for proper module resolution
116
- "react",
117
- "react-reconciler",
118
- "react-nativescript",
119
- ...(optimizeDeps || []),
120
- // Add any other problematic packages here
121
- ],
122
- // Handle Node.js built-ins and other edge cases
123
- esbuildOptions: {
124
- // Pass the same conditions to ESBuild for css-tree compatibility
125
- conditions: ["module", "import", "browser", "default"],
126
- // Define globals for Node.js built-ins if needed
127
- define: {
128
- global: "globalThis",
129
- },
130
- },
131
- },
132
- plugins: [
133
- // TODO: make flavor plugins dynamic
134
- // ...flavorPlugins,
135
- ...commonjsPlugins,
136
- ...(customCommonjsPlugins || []),
137
- // Platform-specific package resolver - MUST come before commonjs plugin
138
- nativescriptPackageResolver(platform),
139
- // Simplified CommonJS handling - let Vite's optimizeDeps do the heavy lifting
140
- commonjs({
141
- include: [/node_modules/],
142
- // Force specific problematic modules to be treated as CommonJS
143
- requireReturnsDefault: "auto",
144
- defaultIsModuleExports: "auto",
145
- transformMixedEsModules: true,
146
- // Ignore optional dependencies that are meant to fail gracefully
147
- ignore: [
148
- "@nativescript/android",
149
- "@nativescript/ios",
150
- ...(commonjsIgnoreList || []),
151
- ],
152
- }),
153
- nsConfigAsJsonPlugin(),
154
- NativeScriptPlugin({ platform }),
155
- mainEntryPlugin(cliFlags, debug),
156
- // NativeScript HMR integration - track changes for incremental builds
157
- hmrPlugin(targetMode),
158
- // NativeScript CLI integration - enhanced IPC communication for HMR
159
- cliPlugin(targetMode, cliFlags),
160
- dynamicImportPlugin(),
161
- // Transform Vite worker URLs to NativeScript format AFTER bundling
162
- workerUrlPlugin(),
163
- ],
164
- css: {
165
- postcss: "./postcss.config.js",
166
- },
167
- // Development server configuration for HMR
168
- server: targetMode === "development"
169
- ? {
170
- hmr: {
171
- // Enable Vite's built-in HMR
172
- port: 24678, // Different port to avoid conflicts with our custom WebSocket
173
- },
174
- // CORS for development
175
- cors: true,
176
- }
177
- : {},
178
- // Configure worker builds to bundle everything into standalone workers
179
- worker: {
180
- format: "es",
181
- plugins: () => getWorkerPlugins(platform),
182
- rollupOptions: {
183
- // Don't externalize anything - bundle everything into the worker
184
- external: [],
185
- output: {
186
- // Inline all dynamic imports to create standalone bundle
187
- inlineDynamicImports: true,
188
- },
189
- },
190
- },
191
- build: {
192
- target: "esnext",
193
- minify: !debug,
194
- // Generate source maps for debugging
195
- // Note: just disabling for now until can hook up to angular vite/analog plugin
196
- sourcemap: false, //debug,
197
- // Disable module preloading to avoid browser APIs
198
- modulePreload: false,
199
- // Optimize for development speed
200
- ...(targetMode === "development" && {
201
- // Faster builds in development
202
- reportCompressedSize: false,
203
- chunkSizeWarningLimit: 2000,
204
- }),
205
- commonjsOptions: {
206
- include: [/node_modules/],
207
- },
208
- rollupOptions: {
209
- input: "virtual:entry-with-polyfills",
210
- output: {
211
- dir: path.resolve(projectRoot, "dist"),
212
- format: "es", // Emit ES modules (.mjs)
213
- entryFileNames: "bundle.mjs", // <- no hash here
214
- chunkFileNames: (chunk) => {
215
- if (chunk.name === "vendor")
216
- return "vendor.mjs";
217
- // Place worker files at root level, not in assets/
218
- if (chunk.name && chunk.name.includes("worker")) {
219
- return "[name]-[hash].js";
220
- }
221
- return "[name]-[hash].mjs";
222
- },
223
- assetFileNames: "assets/[name][extname]",
224
- // Create single vendor chunk - no separate globals chunk to avoid circular deps
225
- manualChunks(id) {
226
- if (id.includes("node_modules")) {
227
- // Note: this is work in progress on best setup
228
- // Keep polyfills and Zone-dependent packages in main bundle to ensure correct execution order
229
- if ([
230
- "@nativescript/core",
231
- "@nativescript/angular",
232
- "@nativescript/zone-js",
233
- "@valor/nativescript-websockets",
234
- "make-error",
235
- // "source-map-js",
236
- "zone.js",
237
- "/globals",
238
- "/polyfills",
239
- ].includes(id)) {
240
- return undefined; // Keep in main bundle
241
- }
242
- return "vendor";
243
- }
244
- },
245
- },
246
- },
247
- },
248
- };
249
- };
@@ -1 +0,0 @@
1
- export declare function handleAngularHmrUpdate(): void;
@@ -1,34 +0,0 @@
1
- import { isDevMode, ɵresetCompiledComponents,
2
- // @ts-ignore
3
- } from "@angular/core";
4
- export function handleAngularHmrUpdate() {
5
- // Reset JIT compiled components cache
6
- ɵresetCompiledComponents();
7
- try {
8
- console.log(`typeof global["__cleanup_ng_hot__"]`, typeof global["__cleanup_ng_hot__"]);
9
- if (global["__cleanup_ng_hot__"])
10
- global["__cleanup_ng_hot__"]();
11
- global["__reboot_ng_modules__"]();
12
- console.log('angular called __reboot_ng_modules__!');
13
- // need to call some kind of apply here?
14
- // Webpack would call in this order with angular-hot-loader/hmr-accept:
15
- /**
16
- * angular hot dispose called!
17
- hot dispose called here?!
18
- __cleanup_ng_hot__ called!
19
- angular hot accept about to be called!
20
- Angular is running in development mode.
21
- [HMR][bd598ae5b97083449f33] success | Successfully applied update.
22
- calling global.__onLiveSync!
23
- */
24
- global.__onLiveSync();
25
- }
26
- catch (e) {
27
- console.error("[NG HMR] Error disposing previous module");
28
- console.error(e, e?.stack);
29
- // HMR breaks when rejecting the main module dispose, so we manually trigger an HMR restart
30
- // const hash = __webpack_require__.h();
31
- // console.log(`[HMR][${hash}] failure | Error disposing previous module`);
32
- // throw e;
33
- }
34
- }
@@ -1,18 +0,0 @@
1
- /**
2
- * Simple HMR Notification Bridge
3
- *
4
- * This creates a lightweight WebSocket server that the NativeScript CLI
5
- * can notify when builds complete, and forwards those to the app.
6
- */
7
- declare class SimpleHMRBridge {
8
- private wsServer;
9
- private connectedClients;
10
- private buildProcess;
11
- start(): Promise<void>;
12
- private startWebSocketServer;
13
- private startNativeScriptBuild;
14
- private parseBuildOutput;
15
- private notifyClients;
16
- stop(): Promise<void>;
17
- }
18
- export { SimpleHMRBridge };
@@ -1,154 +0,0 @@
1
- /**
2
- * Simple HMR Notification Bridge
3
- *
4
- * This creates a lightweight WebSocket server that the NativeScript CLI
5
- * can notify when builds complete, and forwards those to the app.
6
- */
7
- import { WebSocketServer } from 'ws';
8
- import WebSocketType from 'ws';
9
- import { spawn } from 'child_process';
10
- import { pathToFileURL } from 'node:url';
11
- import { resolve } from 'node:path';
12
- const isMain = () => typeof process !== 'undefined' &&
13
- !!process.argv?.[1] &&
14
- import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
15
- class SimpleHMRBridge {
16
- constructor() {
17
- this.connectedClients = new Set();
18
- }
19
- async start() {
20
- console.log('šŸ”„ Starting Simple HMR Bridge...');
21
- // Start WebSocket server for NativeScript app
22
- this.startWebSocketServer();
23
- // Start NativeScript build process
24
- this.startNativeScriptBuild();
25
- console.log('šŸ”„ HMR Bridge ready!');
26
- }
27
- startWebSocketServer() {
28
- const HMR_WS_PORT = 24678;
29
- this.wsServer = new WebSocketServer({ port: HMR_WS_PORT });
30
- this.wsServer.on('connection', (ws) => {
31
- console.log('šŸ”„ NativeScript client connected to HMR bridge');
32
- this.connectedClients.add(ws);
33
- // Send connection confirmation
34
- ws.send(JSON.stringify({
35
- type: 'connected',
36
- timestamp: Date.now()
37
- }));
38
- ws.on('close', () => {
39
- console.log('šŸ”„ NativeScript client disconnected');
40
- this.connectedClients.delete(ws);
41
- });
42
- ws.on('message', (message) => {
43
- try {
44
- const data = JSON.parse(message.toString());
45
- console.log('šŸ”„ Received from NativeScript:', data);
46
- }
47
- catch (e) {
48
- console.error('šŸ”„ Invalid message from NativeScript:', e);
49
- }
50
- });
51
- });
52
- console.log(`šŸ”„ HMR bridge listening on ws://localhost:${HMR_WS_PORT}`);
53
- }
54
- startNativeScriptBuild() {
55
- console.log('šŸ”„ Starting NativeScript build with HMR notifications...');
56
- // Get platform from command line arguments (default to 'ios' if not provided)
57
- const platform = process.argv[2] || 'ios';
58
- console.log(`šŸ”„ Building for platform: ${platform}`);
59
- // Start ns run with specified platform
60
- const args = ['debug', platform];
61
- this.buildProcess = spawn('ns', args, {
62
- cwd: process.cwd(),
63
- stdio: ['inherit', 'pipe', 'pipe'],
64
- env: {
65
- ...process.env,
66
- NS_HMR_BRIDGE: 'true' // Signal to our Vite config that HMR bridge is active
67
- }
68
- });
69
- this.buildProcess.stdout.on('data', (data) => {
70
- const output = data.toString();
71
- process.stdout.write(output);
72
- // Listen for build completion messages
73
- this.parseBuildOutput(output);
74
- });
75
- this.buildProcess.stderr.on('data', (data) => {
76
- process.stderr.write(data);
77
- });
78
- this.buildProcess.on('close', (code) => {
79
- console.log(`šŸ”„ NativeScript build process exited with code ${code}`);
80
- });
81
- }
82
- parseBuildOutput(output) {
83
- // Look for our HMR indicators in the build output
84
- const lines = output.split('\n');
85
- for (const line of lines) {
86
- // Look for our HMR build completion messages
87
- if (line.includes('šŸ”„ HMR update - copying only changed files')) {
88
- // Extract changed files from the next lines
89
- const changedFilesMatch = line.match(/šŸ”„ HMR update - copying only changed files for: (.+)/);
90
- if (changedFilesMatch) {
91
- try {
92
- const changedFiles = JSON.parse(changedFilesMatch[1].replace(/'/g, '"'));
93
- this.notifyClients({
94
- type: 'build-complete',
95
- timestamp: Date.now(),
96
- changedFiles,
97
- buildType: 'incremental',
98
- isHMR: true
99
- });
100
- }
101
- catch (e) {
102
- console.log('šŸ”„ Could not parse changed files from:', changedFilesMatch[1]);
103
- }
104
- }
105
- }
106
- else if (line.includes('šŸ”„ Full build - copying all files')) {
107
- this.notifyClients({
108
- type: 'build-complete',
109
- timestamp: Date.now(),
110
- buildType: 'full',
111
- isHMR: false
112
- });
113
- }
114
- else if (line.includes('Vite build completed!')) {
115
- // Build is done, notify clients
116
- console.log('šŸ”„ Build completed, notifying clients...');
117
- }
118
- }
119
- }
120
- notifyClients(update) {
121
- const message = JSON.stringify(update);
122
- let sentCount = 0;
123
- this.connectedClients.forEach((client) => {
124
- if (client.readyState === WebSocketType.OPEN) {
125
- client.send(message);
126
- sentCount++;
127
- }
128
- });
129
- if (sentCount > 0) {
130
- console.log(`šŸ”„ Notified ${sentCount} clients of update:`, update.type);
131
- }
132
- }
133
- async stop() {
134
- console.log('šŸ”„ Stopping HMR bridge...');
135
- if (this.buildProcess) {
136
- this.buildProcess.kill('SIGTERM');
137
- }
138
- if (this.wsServer) {
139
- this.wsServer.close();
140
- }
141
- }
142
- }
143
- // Export for use in startup script
144
- export { SimpleHMRBridge };
145
- // Auto-start if run directly
146
- if (isMain()) {
147
- const bridge = new SimpleHMRBridge();
148
- bridge.start().catch(console.error);
149
- // Handle graceful shutdown
150
- process.on('SIGINT', () => {
151
- console.log('\nšŸ”„ Shutting down HMR bridge...');
152
- bridge.stop().then(() => process.exit(0));
153
- });
154
- }
@@ -1,5 +0,0 @@
1
- /**
2
- * Simple NativeScript HMR Client for Vite
3
- * Based on @nativescript/webpack loaders but simplified for Vite
4
- */
5
- export {};
@@ -1,93 +0,0 @@
1
- /**
2
- * Simple NativeScript HMR Client for Vite
3
- * Based on @nativescript/webpack loaders but simplified for Vite
4
- */
5
- // Import WebSocket polyfill directly
6
- import { WebSocket as NativeScriptWebSocket } from '@valor/nativescript-websockets/websocket';
7
- // Ensure WebSocket is available globally for other code
8
- if (typeof global !== 'undefined') {
9
- global.WebSocket = NativeScriptWebSocket;
10
- }
11
- // Make WebSocket available in current scope
12
- const WebSocket = NativeScriptWebSocket;
13
- // import { Application } from "@nativescript/core";
14
- let hmrBootEmittedSymbol = Symbol.for("HMRBootEmitted");
15
- let originalLiveSyncSymbol = Symbol.for("OriginalLiveSync");
16
- let hmrRuntimeLastLiveSyncSymbol = Symbol.for("HMRRuntimeLastLiveSync");
17
- if (global.__onLiveSync !== global[hmrRuntimeLastLiveSyncSymbol]) {
18
- // we store the original liveSync here in case this code runs again
19
- // which happens when you module.hot.accept() the main file
20
- global[originalLiveSyncSymbol] = global.__onLiveSync;
21
- }
22
- global[hmrRuntimeLastLiveSyncSymbol] = async function () {
23
- console.log(`calling global[hmrRuntimeLastLiveSyncSymbol]`);
24
- await global[originalLiveSyncSymbol]();
25
- };
26
- global.__onLiveSync = global[hmrRuntimeLastLiveSyncSymbol];
27
- if (!global[hmrBootEmittedSymbol]) {
28
- global[hmrBootEmittedSymbol] = true;
29
- }
30
- /**
31
- * Note: allow vite to inject each flavor client handling
32
- * Start Manual Flavor Testing
33
- */
34
- const flavor = "angular";
35
- import { handleAngularHmrUpdate } from "./hmr-angular.js";
36
- /**
37
- * End Manual Flavor Testing
38
- */
39
- class SimpleNativeScriptHMRClient {
40
- constructor() {
41
- this.ws = null;
42
- console.log("šŸ”„ Simple HMR Client starting...");
43
- console.log("šŸ”„ WebSocket available:", typeof WebSocket !== 'undefined');
44
- console.log("šŸ”„ global.WebSocket available:", typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined');
45
- this.connect();
46
- }
47
- connect() {
48
- try {
49
- // Check if WebSocket is available
50
- if (typeof WebSocket === 'undefined') {
51
- console.error("šŸ”„ WebSocket is not available - HMR disabled");
52
- return;
53
- }
54
- this.ws = new WebSocket("ws://localhost:24678");
55
- this.ws.onopen = () => {
56
- console.log("šŸ”„ HMR connected");
57
- };
58
- this.ws.onmessage = (event) => {
59
- try {
60
- const update = JSON.parse(event.data);
61
- this.handleUpdate(update);
62
- }
63
- catch (error) {
64
- console.error("šŸ”„ HMR message error:", error);
65
- }
66
- };
67
- }
68
- catch (error) {
69
- console.error("šŸ”„ HMR connection failed:", error);
70
- }
71
- }
72
- handleUpdate(update) {
73
- console.log("šŸ”„ HMR update received:", update.type);
74
- if (update.type === "build-complete" && update.isHMR) {
75
- // skip very first one since it's initial build
76
- console.log("šŸ”„ Applying HMR update for:", update.changedFiles);
77
- switch (flavor) {
78
- case "angular":
79
- // Handle Angular specific HMR updates
80
- handleAngularHmrUpdate();
81
- break;
82
- }
83
- }
84
- }
85
- }
86
- // Initialize on app launch
87
- let hmrClient;
88
- if (!hmrClient) {
89
- console.log("šŸ”„ Initializing Simple NativeScript HMR Client");
90
- // Application.on(Application.launchEvent, () => {
91
- hmrClient = new SimpleNativeScriptHMRClient();
92
- // });
93
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * NativeScript True HMR Implementation
3
- *
4
- * This creates a bridge between Vite's dev server HMR and NativeScript runtime
5
- * to enable true hot module replacement without losing application state.
6
- */
7
- declare class NativeScriptHMRServer {
8
- private viteServer;
9
- private wsServer;
10
- private buildProcess;
11
- private connectedClients;
12
- start(): Promise<void>;
13
- private startViteDevServer;
14
- private startHMRBridge;
15
- private handleViteHMRMessage;
16
- private broadcastToClients;
17
- private startBuildProcess;
18
- stop(): Promise<void>;
19
- }
20
- export { NativeScriptHMRServer };