From d0c039b37be4aa0b80f9dfe8f041387e7f17d6ef Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 6 Oct 2025 09:02:41 -0500 Subject: [PATCH] Let esmPlugin accept a package.json, make packageLock optional --- src/lib/build/esmPlugin.ts | 42 ++++++++++++++++++++------- src/lib/build/index.test.ts | 58 +++++++++++++++++++++++++++++++++++++ src/lib/build/index.ts | 15 +++++++++- 3 files changed, 104 insertions(+), 11 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index 73321150..9c2da0d0 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -13,7 +13,20 @@ interface PackageLock { }; } -export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { +interface PackageJson { + dependencies?: { [key: string]: string }; + devDependencies?: { [key: string]: string }; + peerDependencies?: { [key: string]: string }; +} + +interface EsmPluginOptions { + packageJson: PackageJson; + packageLock?: PackageLock; + target?: string; +} + +export function esmPlugin(options: EsmPluginOptions): Plugin { + const { packageJson, packageLock, target } = options; /** Cache of URL redirects */ const redirectedURLs = new Map(); @@ -21,9 +34,11 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { const urlLockPath = new Map(); /** Build quick indexes from the lockfile */ - const packagesEntries = Object.entries(packageLock.packages || {}).filter( - (e): e is [string, NonNullable] => Boolean(e[1]) - ); + const packagesEntries = packageLock + ? Object.entries(packageLock.packages || {}).filter( + (e): e is [string, NonNullable] => Boolean(e[1]) + ) + : []; // Map of `${name}@${version}` -> array of lock paths where that exact install exists const nameVersionToPaths = new Map(); @@ -101,10 +116,10 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { const resolveFrom = (lockPath: string | undefined, depName: string): string | undefined => { const dep = normalizeNameForLock(depName); - const has = (p: string): boolean => Boolean(packageLock.packages?.[p]); + const has = (p: string): boolean => Boolean(packageLock?.packages?.[p]); // Self-import: if the importer package name matches the requested dep, return the same lock path - if (lockPath) { + if (lockPath && packageLock) { const importerInfo = packageLock.packages?.[lockPath]; const importerNameFromInfo = importerInfo?.name ? normalizeNameForLock(importerInfo.name) : undefined; const importerNameFromPath = lockPath.replace(/^.*\bnode_modules\//, ""); @@ -161,7 +176,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { if (m) { const jsrAlias = `@jsr/${m[1]}__${m[2]}`; // Read importer deps from lockPath - const importerDeps = lockPath ? packageLock.packages?.[lockPath]?.dependencies : undefined; + const importerDeps = lockPath && packageLock ? packageLock.packages?.[lockPath]?.dependencies : undefined; if (importerDeps && Object.prototype.hasOwnProperty.call(importerDeps, jsrAlias)) { searchOrder = [jsrAlias, dep]; } else { @@ -253,11 +268,18 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { const childLockPath = resolveFrom(importerLockPath, packageName); // Determine CDN name and version - const childInfo = childLockPath ? packageLock.packages?.[childLockPath] : undefined; - const version = childInfo?.version; // exact installed version from lock + const childInfo = childLockPath && packageLock ? packageLock.packages?.[childLockPath] : undefined; + let version = childInfo?.version; // exact installed version from lock + + // If no version found in lock file, fall back to package.json + if (!version) { + version = packageJson.dependencies?.[packageName] + ?? packageJson.devDependencies?.[packageName] + ?? packageJson.peerDependencies?.[packageName]; + } // Decide CDN package name. Prefer explicit @jsr alias, then installed name, then canonical normalized name. - const importerInfo = importerLockPath ? packageLock.packages?.[importerLockPath] : undefined; + const importerInfo = importerLockPath && packageLock ? packageLock.packages?.[importerLockPath] : undefined; const importerDeps = importerInfo?.dependencies ?? undefined; // Determine CDN package name diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index b2bbe985..bc202928 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -408,4 +408,62 @@ react@^18.0.0: expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package-lock.json', 'utf8'); expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/yarn.lock', 'utf8'); }); + + it('should use package.json dependencies as fallback when no lock file exists', async () => { + const packageJsonWithDeps = JSON.stringify({ + name: "test-project", + dependencies: { + "react": "^18.2.0", + "react-dom": "^18.2.0" + } + }); + + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return packageJsonWithDeps; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json') || path.endsWith('yarn.lock')) { + throw new Error('File not found'); + } + throw new Error(`File not found: ${path}`); + }); + + // Mock stat to indicate no public directory + vi.mocked(mockFS.stat) + .mockImplementation(async (path: string) => { + if (path === '/test/project/public') { + throw new Error('Directory not found'); + } + return { isDirectory: () => false, isFile: () => true }; + }); + + // Mock additional filesystem operations for buildProject + vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => { + if (path === '/test/project/dist') { + return []; + } + return []; + }); + + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await buildProject({ + fs: mockFS, + projectPath: '/test/project', + domParser: mockDOMParser, + }); + + // Should successfully build using package.json dependencies + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['index.html']).toBeDefined(); + + // Verify package.json was read + expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8'); + }); }); \ No newline at end of file diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 920d4f86..a2d34e8e 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -30,14 +30,23 @@ async function bundle( "utf8", ); + // Read package.json + const packageJsonText = await fs.readFile( + `${projectPath}/package.json`, + "utf8", + ); + const packageJson = JSON.parse(packageJsonText); + // Try to read package-lock.json first, fall back to yarn.lock let packageLock; + let buildMode: string; try { const packageLockText = await fs.readFile( `${projectPath}/package-lock.json`, "utf8", ); packageLock = JSON.parse(packageLockText); + buildMode = "npm (package-lock.json)"; } catch { // If package-lock.json doesn't exist, try yarn.lock try { @@ -46,12 +55,16 @@ async function bundle( "utf8", ); packageLock = convertYarnLockToPackageLock(yarnLockText); + buildMode = "yarn (yarn.lock)"; } catch { // If neither exists, use empty packages object packageLock = { packages: {} }; + buildMode = "package.json only (no lock file)"; } } + console.log(`Building with ${buildMode}`); + const doc = domParser.parseFromString(indexHtmlText, "text/html"); const entryPoints: string[] = []; const entryScripts: Record = {}; @@ -99,7 +112,7 @@ async function bundle( plugins: [ shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), - esmPlugin(packageLock, target), + esmPlugin({ packageJson, packageLock, target }), ], define: { "import.meta.env": JSON.stringify({}),