Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ If your project is started through another tool, set `runtimeExecutable` and `ru

#### Vite projects

Projects using the Vite bundler (`bundler: 'vite'` in `nativescript.config.ts`) are debugged with `--no-hmr`, because hot module replacement serves app code without source maps. File changes still rebuild and restart the app, and the debugger reattaches. Pass `--hmr` in `tnsArgs` to keep HMR on (breakpoints in app code won't bind). Debugging unit tests that use the Vitest runner is not supported yet.
Projects using the Vite bundler (`bundler: 'vite'` in `nativescript.config.ts`) are debugged with hot module replacement when `@nativescript/vite` is 8.0.23 or later, which serves app modules with source maps. Breakpoints stay bound as you edit, because HMR updates replace modules in the running app without restarting it. With older versions, and for Vue projects (whose `.vue` components are still served without source maps), the extension adds `--no-hmr`. File changes then rebuild and restart the app, and the debugger reattaches. An explicit `--hmr` or `--no-hmr` in `tnsArgs` is always used as given. Debugging unit tests that use the Vitest runner is not supported yet.

### NativeScript commands

Expand Down
32 changes: 27 additions & 5 deletions src/project/projectInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ export function readPackageJson(appRoot: string): { name?: string; [key: string]
}
}

export function hasDependency(appRoot: string, packageName: string): boolean {
const packageJson = readPackageJson(appRoot);
return ['dependencies', 'devDependencies'].some((field) => {
const deps = packageJson?.[field];
return typeof deps === 'object' && deps !== null && packageName in deps;
});
}

/** Mirrors the CLI's ProjectData.getAppDirectoryRelativePath. */
export function getAppDirectory(appRoot: string): string {
const legacyConfig = readFile(path.join(appRoot, 'nsconfig.json'));
Expand All @@ -58,15 +66,14 @@ export function getBundler(appRoot: string): Bundler {
}

/**
* Finds a locally installed CLI (`node_modules/.bin/ns`) in appRoot or any parent directory, like npx does, so
* monorepos that install it at the workspace root are covered.
* Finds `node_modules/<relativePath>` in appRoot or any parent directory, like Node resolution and npx do, so
* monorepos that install packages at the workspace root are covered.
*/
export function findLocalCli(appRoot: string, platform: NodeJS.Platform = process.platform): string | undefined {
const binName = platform === 'win32' ? 'ns.cmd' : 'ns';
function findInNodeModules(appRoot: string, relativePath: string): string | undefined {
let dir = path.resolve(appRoot);

while (true) {
const candidate = path.join(dir, 'node_modules', '.bin', binName);
const candidate = path.join(dir, 'node_modules', relativePath);
if (fs.existsSync(candidate)) return candidate;

const parent = path.dirname(dir);
Expand All @@ -75,6 +82,21 @@ export function findLocalCli(appRoot: string, platform: NodeJS.Platform = proces
}
}

export function findLocalCli(appRoot: string, platform: NodeJS.Platform = process.platform): string | undefined {
return findInNodeModules(appRoot, path.join('.bin', platform === 'win32' ? 'ns.cmd' : 'ns'));
}

export function getInstalledPackageVersion(appRoot: string, packageName: string): string | undefined {
const packageJson = findInNodeModules(appRoot, path.join(packageName, 'package.json'));
if (!packageJson) return undefined;
try {
const version = (JSON.parse(fs.readFileSync(packageJson, 'utf8')) as { version?: unknown }).version;
return typeof version === 'string' ? version : undefined;
} catch {
return undefined;
}
}

export function isVitestProject(appRoot: string): boolean {
return ['ts', 'mts', 'js', 'mjs'].some((ext) => fs.existsSync(path.join(appRoot, `vitest.config.${ext}`)));
}
28 changes: 25 additions & 3 deletions src/services/buildService.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import * as fs from 'fs';
import * as path from 'path';
import * as semver from 'semver';
import { ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
import { ILogger } from '../common/logger';
import * as utils from '../common/utilities';
import { getBundler, isVitestProject } from '../project/projectInfo';
import { getBundler, getInstalledPackageVersion, hasDependency, isVitestProject } from '../project/projectInfo';
import { AndroidProject } from '../project/androidProject';
import { IosProject } from '../project/iosProject';
import { NativeScriptCli } from '../project/nativeScriptCli';
Expand All @@ -31,6 +32,9 @@ export interface BuildArgs {
/** Ignore repeated port announcements closer together than this; the CLI can print the same port twice. */
const DUPLICATE_PORT_WINDOW_MS = 2000;

/** First @nativescript/vite release whose HMR server attaches source maps to the app modules it serves. */
export const VITE_HMR_SOURCE_MAPS_VERSION = '8.0.23';

/** How long the CLI gets to clean up after SIGINT before it is killed. */
export const CLI_EXIT_TIMEOUT_MS = 5000;

Expand Down Expand Up @@ -168,8 +172,11 @@ export class BuildService {
let tnsArgs = [...(args.tnsArgs ?? [])];

if (getBundler(args.appRoot) === 'vite' && !tnsArgs.some((arg) => /^--(no-)?hmr$/.test(arg))) {
// Vite HMR serves app code over HTTP without source maps, so breakpoints can't bind.
tnsArgs.push('--no-hmr');
const reason = this.getHmrDebuggingBlocker(args.appRoot);
if (reason) {
this.logger.log(`[NativeScript] ${reason}, so debugging with --no-hmr.\n`);
tnsArgs.push('--no-hmr');
}
}

if (args.request === 'launch' && platform === 'ios' && !this.getTeamId(args.appRoot, tnsArgs)) {
Expand Down Expand Up @@ -227,6 +234,21 @@ export class BuildService {
return new BuildSession(project.monitor(child, runtimeArgs), this.logger);
}

/** Why breakpoints in app code could not bind under Vite HMR, or undefined when they can. */
private getHmrDebuggingBlocker(appRoot: string): string | undefined {
const viteVersion = getInstalledPackageVersion(appRoot, '@nativescript/vite');
if (
!viteVersion ||
!semver.satisfies(viteVersion, `>=${VITE_HMR_SOURCE_MAPS_VERSION}`, { includePrerelease: true })
) {
return `@nativescript/vite ${viteVersion ?? '(not found)'} serves HMR modules without source maps (fixed in ${VITE_HMR_SOURCE_MAPS_VERSION})`;
}
if (hasDependency(appRoot, 'nativescript-vue')) {
return 'Vue single-file components are served without source maps under HMR';
}
return undefined;
}

private createProject(platform: string, appRoot: string, cli: NativeScriptCli, options: ProjectOptions): Project {
return platform === 'ios' ? new IosProject(appRoot, cli, options) : new AndroidProject(appRoot, cli, options);
}
Expand Down
35 changes: 33 additions & 2 deletions src/tests/buildService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ import { AnalyticsService } from '../analytics/analyticsService';
import * as utils from '../common/utilities';
import { NativeScriptCli } from '../project/nativeScriptCli';
import { IDebugResult, ProjectOptions } from '../project/project';
import { BuildArgs, BuildService, BuildSession, CLI_EXIT_TIMEOUT_MS } from '../services/buildService';
import {
BuildArgs,
BuildService,
BuildSession,
CLI_EXIT_TIMEOUT_MS,
VITE_HMR_SOURCE_MAPS_VERSION,
} from '../services/buildService';
import { services } from '../services/extensionHostServices';
import { iOSTeamService } from '../services/iOSTeamService';

Expand Down Expand Up @@ -347,11 +353,36 @@ describe('BuildService.startBuild', () => {
});

describe('Vite projects', () => {
const installVite = (version: string) =>
writeAppFile('node_modules/@nativescript/vite/package.json', JSON.stringify({ version }));

beforeEach(() => {
writeAppFile('nativescript.config.ts', "export default { id: 'org.demo', bundler: 'vite' };\n");
});

it('appends --no-hmr', async () => {
it.each(['8.0.22', '8.0.23-alpha.0'])('appends --no-hmr for @nativescript/vite %s', async (version) => {
installVite(version);
await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] }));
expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']);
});

it('appends --no-hmr when the @nativescript/vite version is unknown', async () => {
await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] }));
expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']);
});

it.each([VITE_HMR_SOURCE_MAPS_VERSION, '8.1.0-alpha.0', '9.0.0'])(
'keeps HMR for @nativescript/vite %s',
async (version) => {
installVite(version);
await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] }));
expect(debugTnsArgs()).toEqual(['--env.foo']);
},
);

it('appends --no-hmr for Vue projects, whose single-file components have no HMR source maps', async () => {
installVite(VITE_HMR_SOURCE_MAPS_VERSION);
writeAppFile('package.json', JSON.stringify({ dependencies: { 'nativescript-vue': '^3.1.1' } }));
await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] }));
expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']);
});
Expand Down
52 changes: 51 additions & 1 deletion src/tests/projectInfo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@ import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { findLocalCli, getAppDirectory, getBundler, isVitestProject, readPackageJson } from '../project/projectInfo';
import {
findLocalCli,
getAppDirectory,
getBundler,
getInstalledPackageVersion,
hasDependency,
isVitestProject,
readPackageJson,
} from '../project/projectInfo';

describe('projectInfo', () => {
let appRoot: string;
Expand Down Expand Up @@ -101,6 +109,48 @@ describe('projectInfo', () => {
});
});

describe('hasDependency', () => {
it('finds runtime and dev dependencies', () => {
writeAppFile('package.json', JSON.stringify({ dependencies: { a: '1' }, devDependencies: { b: '1' } }));

expect(hasDependency(appRoot, 'a')).toBe(true);
expect(hasDependency(appRoot, 'b')).toBe(true);
expect(hasDependency(appRoot, 'c')).toBe(false);
});

it('is false without a package.json', () => {
expect(hasDependency(appRoot, 'a')).toBe(false);
});
});

describe('getInstalledPackageVersion', () => {
const installPackage = (dir: string, content: string) =>
writeAppFile(path.join(dir, 'node_modules', '@nativescript', 'vite', 'package.json'), content);

it('reads the version from the nearest install', () => {
installPackage('.', JSON.stringify({ version: '8.0.22' }));
installPackage('apps/mobile', JSON.stringify({ version: '8.1.0' }));

expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBe('8.0.22');
expect(getInstalledPackageVersion(path.join(appRoot, 'apps', 'mobile'), '@nativescript/vite')).toBe('8.1.0');
});

it('walks up to a workspace root install', () => {
installPackage('.', JSON.stringify({ version: '8.0.23' }));
const nested = path.join(appRoot, 'apps', 'mobile');
fs.mkdirSync(nested, { recursive: true });

expect(getInstalledPackageVersion(nested, '@nativescript/vite')).toBe('8.0.23');
});

it('is undefined when the package is missing or its package.json is unreadable', () => {
expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBeUndefined();

installPackage('.', '{ not json');
expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBeUndefined();
});
});

describe('findLocalCli', () => {
const installCli = (dir: string, bin = 'ns') => {
const file = path.join(appRoot, dir, 'node_modules', '.bin', bin);
Expand Down
Loading