diff --git a/package-lock.json b/package-lock.json index 8aea64c8..0b3bdaf8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -60,6 +60,7 @@ "ignore": "^7.0.5", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", + "jsonc-parser": "^3.3.1", "jszip": "^3.10.1", "lucide-react": "^0.525.0", "nostr-tools": "^2.15.2", @@ -6892,6 +6893,12 @@ "dev": true, "license": "MIT" }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "license": "MIT" + }, "node_modules/jszip": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", diff --git a/package.json b/package.json index cfb24d13..20cf933c 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "ignore": "^7.0.5", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", + "jsonc-parser": "^3.3.1", "jszip": "^3.10.1", "lucide-react": "^0.525.0", "nostr-tools": "^2.15.2", diff --git a/src/hooks/useIsProjectPreviewable.test.ts b/src/hooks/useIsProjectPreviewable.test.ts index 70e4b23f..a577ae1d 100644 --- a/src/hooks/useIsProjectPreviewable.test.ts +++ b/src/hooks/useIsProjectPreviewable.test.ts @@ -31,7 +31,6 @@ describe('useIsProjectPreviewable', () => { expect(result.current.data).toBe(true); expect(mockFileExists).toHaveBeenCalledWith('test-project', 'index.html'); expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json'); - expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package-lock.json'); }); it('returns false when index.html is missing', async () => { @@ -70,7 +69,7 @@ describe('useIsProjectPreviewable', () => { expect(result.current.data).toBe(false); }); - it('returns false when package-lock.json is missing', async () => { + it('returns true even when package-lock.json is missing (yarn.lock or no lock file is acceptable)', async () => { mockFileExists.mockImplementation((projectId: string, filePath: string) => { if (filePath === 'package-lock.json') return Promise.resolve(false); return Promise.resolve(true); @@ -85,7 +84,9 @@ describe('useIsProjectPreviewable', () => { expect(result.current.isSuccess).toBe(true); }); - expect(result.current.data).toBe(false); + // Should still be previewable since package-lock.json is not required + // (projects can use yarn.lock or no lock file) + expect(result.current.data).toBe(true); }); it('returns false when projectId is empty', async () => { diff --git a/src/hooks/useIsProjectPreviewable.ts b/src/hooks/useIsProjectPreviewable.ts index 52f019bd..e3c919ae 100644 --- a/src/hooks/useIsProjectPreviewable.ts +++ b/src/hooks/useIsProjectPreviewable.ts @@ -3,7 +3,7 @@ import { useProjectsManager } from './useProjectsManager'; /** * Hook to check if a project is previewable - * A project is previewable if it has index.html, package.json, and package-lock.json + * A project is previewable if it has index.html and package.json */ export function useIsProjectPreviewable(projectId: string) { const projectsManager = useProjectsManager(); @@ -13,13 +13,12 @@ export function useIsProjectPreviewable(projectId: string) { queryFn: async () => { try { // Check for required files - const [hasIndexHtml, hasPackageJson, hasPackageLock] = await Promise.all([ + const [hasIndexHtml, hasPackageJson] = await Promise.all([ projectsManager.fileExists(projectId, 'index.html'), projectsManager.fileExists(projectId, 'package.json'), - projectsManager.fileExists(projectId, 'package-lock.json'), ]); - return hasIndexHtml && hasPackageJson && hasPackageLock; + return hasIndexHtml && hasPackageJson; } catch (error) { console.error('Failed to check if project is previewable:', error); return false; 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/fsPlugin.ts b/src/lib/build/fsPlugin.ts index a6abf2ea..553a2aa2 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -3,7 +3,21 @@ import { join, dirname, extname } from "path-browserify"; import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; -export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { +interface TsConfig { + compilerOptions?: { + baseUrl?: string; + paths?: Record; + }; +} + +interface FsPluginOptions { + fs: JSRuntimeFS; + cwd: string; + tsconfig?: TsConfig; +} + +export function fsPlugin(options: FsPluginOptions): Plugin { + const { fs, cwd, tsconfig } = options; return { name: "fs", @@ -25,18 +39,17 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { if (args.path.startsWith("/")) { resolved = args.path; } else if (args.path.startsWith("@/")) { - resolved = join(cwd, args.path.slice(2)); - } else if (args.kind === "entry-point") { - resolved = join(cwd, args.path); - } else if (args.importer) { + resolved = join(cwd, "src", args.path.slice(2)); + } else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { resolved = join(dirname(args.importer), args.path); + } else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { + resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path); } else { return; } // Security: prevent accessing files outside the project directory - const projectDir = join(cwd, ".."); - if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) { + if (resolved.startsWith("/") && !resolved.startsWith(cwd)) { throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); } diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index b8f52ac9..865ece6f 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -293,4 +293,239 @@ describe('buildProject', () => { // Should try to copy public files but directory is empty expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); }); + + it('should support yarn.lock when package-lock.json is missing', async () => { + const yarnLock = ` +# yarn lockfile v1 + +react@^18.0.0: + version "18.2.0" + resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz" + integrity sha512-... + dependencies: + loose-envify "^1.1.0" +`; + + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + throw new Error('File not found: package-lock.json'); + } + if (path.endsWith('yarn.lock')) { + return yarnLock; + } + 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 with yarn.lock + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['index.html']).toBeDefined(); + + // Verify yarn.lock was read + expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/yarn.lock', 'utf8'); + }); + + it('should work with no lock file at all', async () => { + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + 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 with empty packages object + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['index.html']).toBeDefined(); + + // Verify both lock files were attempted to be read + 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'); + }); + + it('should read tsconfig.json when available', async () => { + const tsconfigContent = JSON.stringify({ + compilerOptions: { + baseUrl: "./src", + paths: { + "@/*": ["*"] + } + } + }); + + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + return '{"dependencies": {}}'; + } + if (path.endsWith('tsconfig.json')) { + return tsconfigContent; + } + 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 with tsconfig.json + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['index.html']).toBeDefined(); + + // Verify tsconfig.json was attempted to be read + expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8'); + }); }); \ No newline at end of file diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index a424c05b..933c36f1 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,3 +1,4 @@ +import * as JSONC from "jsonc-parser"; import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; @@ -6,6 +7,7 @@ import { addDomainToCSP } from "@/lib/csp"; import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; +import { convertYarnLockToPackageLock } from "./yarnLockConverter"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -28,10 +30,54 @@ async function bundle( `${projectPath}/index.html`, "utf8", ); - const packageLockText = await fs.readFile( - `${projectPath}/package-lock.json`, + + // Read package.json + const packageJsonText = await fs.readFile( + `${projectPath}/package.json`, "utf8", ); + const packageJson = JSON.parse(packageJsonText); + + // Try to read tsconfig.json + let tsconfig; + try { + const tsconfigText = await fs.readFile( + `${projectPath}/tsconfig.json`, + "utf8", + ); + tsconfig = JSONC.parse(tsconfigText); + } catch { + // tsconfig.json is optional + tsconfig = undefined; + } + + // 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 { + const yarnLockText = await fs.readFile( + `${projectPath}/yarn.lock`, + "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[] = []; @@ -79,8 +125,8 @@ async function bundle( assetNames: "[name]-[hash]", plugins: [ shakespearePlugin(), - fsPlugin(fs, `${projectPath}/src`), - esmPlugin(JSON.parse(packageLockText), target), + fsPlugin({ fs, cwd: projectPath, tsconfig }), + esmPlugin({ packageJson, packageLock, target }), ], define: { "import.meta.env": JSON.stringify({}), diff --git a/src/lib/build/yarnLockConverter.test.ts b/src/lib/build/yarnLockConverter.test.ts new file mode 100644 index 00000000..aa76eb62 --- /dev/null +++ b/src/lib/build/yarnLockConverter.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect } from 'vitest'; +import { convertYarnLockToPackageLock } from './yarnLockConverter'; + +describe('convertYarnLockToPackageLock', () => { + it('should convert a simple yarn.lock entry', () => { + const yarnLock = ` +# yarn lockfile v1 + +react@^18.0.0: + version "18.2.0" + resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz" + integrity sha512-... +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/react']).toEqual({ + name: 'react', + version: '18.2.0', + }); + }); + + it('should convert scoped packages', () => { + const yarnLock = ` +"@babel/core@^7.0.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.23.0.tgz" + integrity sha512-... +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/@babel/core']).toEqual({ + name: '@babel/core', + version: '7.23.0', + }); + }); + + it('should parse dependencies', () => { + const yarnLock = ` +react-dom@^18.0.0: + version "18.2.0" + resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.2.0.tgz" + integrity sha512-... + dependencies: + loose-envify "^1.1.0" + scheduler "^0.23.0" +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/react-dom']).toEqual({ + name: 'react-dom', + version: '18.2.0', + dependencies: { + 'loose-envify': '^1.1.0', + 'scheduler': '^0.23.0', + }, + }); + }); + + it('should parse peer dependencies', () => { + const yarnLock = ` +"@testing-library/react@^14.0.0": + version "14.0.0" + resolved "https://registry.yarnpkg.com/@testing-library/react/-/react-14.0.0.tgz" + integrity sha512-... + peerDependencies: + react "^18.0.0" + react-dom "^18.0.0" +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/@testing-library/react']).toEqual({ + name: '@testing-library/react', + version: '14.0.0', + peerDependencies: { + react: '^18.0.0', + 'react-dom': '^18.0.0', + }, + }); + }); + + it('should handle multiple packages', () => { + const yarnLock = ` +react@^18.0.0: + version "18.2.0" + resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz" + +react-dom@^18.0.0: + version "18.2.0" + resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.2.0.tgz" + dependencies: + react "^18.0.0" +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/react']).toEqual({ + name: 'react', + version: '18.2.0', + }); + + expect(result.packages['node_modules/react-dom']).toEqual({ + name: 'react-dom', + version: '18.2.0', + dependencies: { + react: '^18.0.0', + }, + }); + }); + + it('should handle npm alias syntax', () => { + const yarnLock = ` +"package@npm:other-package@^1.0.0": + version "1.2.3" + resolved "https://registry.yarnpkg.com/other-package/-/other-package-1.2.3.tgz" +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/package']).toEqual({ + name: 'package', + version: '1.2.3', + }); + }); + + it('should skip entries without version', () => { + const yarnLock = ` +invalid-entry@^1.0.0: + resolved "https://registry.yarnpkg.com/invalid/-/invalid-1.0.0.tgz" + +valid-entry@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/valid/-/valid-1.0.0.tgz" +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages['node_modules/invalid-entry']).toBeUndefined(); + expect(result.packages['node_modules/valid-entry']).toEqual({ + name: 'valid-entry', + version: '1.0.0', + }); + }); + + it('should handle empty yarn.lock', () => { + const yarnLock = ` +# yarn lockfile v1 +`; + + const result = convertYarnLockToPackageLock(yarnLock); + + expect(result.packages).toEqual({}); + }); +}); diff --git a/src/lib/build/yarnLockConverter.ts b/src/lib/build/yarnLockConverter.ts new file mode 100644 index 00000000..b2f89db2 --- /dev/null +++ b/src/lib/build/yarnLockConverter.ts @@ -0,0 +1,172 @@ +/** + * Converts yarn.lock format to package-lock.json format for use with esmPlugin. + * This is a simplified converter that extracts enough information for dependency resolution. + */ + +interface YarnLockEntry { + version: string; + dependencies?: Record; + peerDependencies?: Record; +} + +interface PackageLockPackage { + name?: string; + version: string; + dependencies?: Record; + peerDependencies?: Record; +} + +interface PackageLock { + packages: { + [key: string]: PackageLockPackage; + }; +} + +/** + * Parse a yarn.lock file and convert it to package-lock.json format + */ +export function convertYarnLockToPackageLock(yarnLockContent: string): PackageLock { + const packages: Record = {}; + + // Parse yarn.lock entries + const entries = parseYarnLock(yarnLockContent); + + // Convert each entry to package-lock format + for (const [key, entry] of Object.entries(entries)) { + // Extract package name from the yarn.lock key + // Keys can be like: "package@^1.0.0" or "@scope/package@^1.0.0" or "package@npm:other@^1.0.0" + const packageName = extractPackageName(key); + + if (!packageName) continue; + + // Create a node_modules path for this package + const lockPath = `node_modules/${packageName}`; + + packages[lockPath] = { + name: packageName, + version: entry.version, + dependencies: entry.dependencies, + peerDependencies: entry.peerDependencies, + }; + } + + return { packages }; +} + +/** + * Parse yarn.lock content into a map of entries + */ +function parseYarnLock(content: string): Record { + const entries: Record = {}; + const lines = content.split('\n'); + + let currentKey: string | null = null; + let currentEntry: Partial = {}; + let inDependencies = false; + let inPeerDependencies = false; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Skip comments and empty lines + if (line.startsWith('#') || line.trim() === '') { + continue; + } + + // Check if this is a package header (starts without indentation and ends with :) + if (line.match(/^[^"\s].*:$/) || line.match(/^".*":$/)) { + // Save previous entry if exists + if (currentKey && currentEntry.version) { + entries[currentKey] = currentEntry as YarnLockEntry; + } + + // Start new entry + currentKey = line.replace(/:$/, '').replace(/^"|"$/g, ''); + currentEntry = {}; + inDependencies = false; + inPeerDependencies = false; + continue; + } + + // Parse indented properties + const propertyMatch = line.match(/^\s{2}(\S+):\s*$/); + const valueMatch = line.match(/^\s{2}(\S+)\s+"?([^"]+)"?\s*$/); + const depMatch = line.match(/^\s{4}(\S+)\s+"?([^"]+)"?\s*$/); + + if (propertyMatch && currentKey) { + const [, key] = propertyMatch; + + if (key === 'dependencies') { + inDependencies = true; + inPeerDependencies = false; + currentEntry.dependencies = {}; + } else if (key === 'peerDependencies') { + inPeerDependencies = true; + inDependencies = false; + currentEntry.peerDependencies = {}; + } else { + inDependencies = false; + inPeerDependencies = false; + } + } else if (valueMatch && currentKey && !inDependencies && !inPeerDependencies) { + const [, key, value] = valueMatch; + const cleanValue = value.replace(/^"|"$/g, ''); + + if (key === 'version') { + currentEntry.version = cleanValue; + } + } else if (depMatch && currentKey) { + const [, key, value] = depMatch; + const cleanValue = value.replace(/^"|"$/g, ''); + + if (inDependencies && currentEntry.dependencies) { + currentEntry.dependencies[key] = cleanValue; + } else if (inPeerDependencies && currentEntry.peerDependencies) { + currentEntry.peerDependencies[key] = cleanValue; + } + } + } + + // Save last entry + if (currentKey && currentEntry.version) { + entries[currentKey] = currentEntry as YarnLockEntry; + } + + return entries; +} + +/** + * Extract the package name from a yarn.lock key + * Examples: + * "react@^18.0.0" -> "react" + * "@babel/core@^7.0.0" -> "@babel/core" + * "package@npm:other@^1.0.0" -> "package" + */ +function extractPackageName(key: string): string | null { + // Remove quotes if present + const cleaned = key.replace(/^"|"$/g, ''); + + // Handle npm alias syntax: "package@npm:other@^1.0.0" + if (cleaned.includes('@npm:')) { + const beforeNpm = cleaned.split('@npm:')[0]; + return beforeNpm.replace(/@[^@]*$/, '') || null; + } + + // Handle scoped packages: "@scope/package@^1.0.0" + if (cleaned.startsWith('@')) { + const parts = cleaned.split('@'); + // parts will be: ['', 'scope/package', '^1.0.0'] or ['', 'scope/package', 'npm:...'] + if (parts.length >= 2) { + return `@${parts[1]}`; + } + } + + // Handle regular packages: "package@^1.0.0" + const atIndex = cleaned.indexOf('@'); + if (atIndex > 0) { + return cleaned.substring(0, atIndex); + } + + // If no @ found, return the whole string (shouldn't happen in valid yarn.lock) + return cleaned || null; +}