diff --git a/AGENTS.md b/AGENTS.md index 3aa30b40..8c27ab45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,6 +108,99 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users. +## Build System + +Shakespeare includes a browser-based build system that compiles projects entirely in the browser using esbuild-wasm. The build system supports multiple project types and automatically detects the appropriate build strategy. + +### Supported Project Types + +#### React/Vite Projects +- **Detection**: Projects with `index.html` at the root +- **Entry Point**: Script tags in `index.html` with `type="module"` +- **Static Assets**: Files in `public/` directory +- **Build Output**: Bundled JavaScript, CSS, and HTML in `dist/` directory + +#### SvelteKit Projects +- **Detection**: Projects with `src/app.html` or `svelte.config.js`/`svelte.config.ts` +- **Entry Point**: Svelte components in `src/routes/` +- **Static Assets**: Files in `static/` directory +- **Build Output**: Compiled Svelte components with client-side rendering + +### Build System Architecture + +The build system is located in `src/lib/build/` and consists of several plugins: + +- **esmPlugin**: Resolves npm packages from esm.sh CDN, handles package-lock.json and yarn.lock +- **fsPlugin**: Provides filesystem access for imports, handles path aliases like `@/` +- **sveltePlugin**: Compiles `.svelte` files using the Svelte compiler from CDN +- **shakespearePlugin**: Provides polyfills and workarounds for browser compatibility + +### Project Detection + +The build system automatically detects project type using the following logic: + +```typescript +// A project is considered SvelteKit if: +// 1. It has src/app.html OR svelte.config.js/ts, AND +// 2. It does NOT have a root index.html (which indicates React/Vite) + +// Otherwise, it's treated as a React/Vite project +``` + +This detection is used in two places: +- `buildProject()` in `src/lib/build/index.ts` - for building projects +- `useIsProjectPreviewable()` in `src/hooks/useIsProjectPreviewable.ts` - for determining if preview is available + +### Building Projects + +Projects can be built using the `BuildProjectTool` or by calling `buildProject()` directly: + +```typescript +const result = await buildProject({ + fs, // Virtual filesystem + projectPath, // Project directory path + domParser, // DOMParser instance + target: "esnext", // ECMAScript target + esmUrl, // ESM CDN URL + outputPath, // Optional output directory +}); +``` + +The build process: +1. Detects project type (React/Vite or SvelteKit) +2. Reads package.json, tsconfig.json, and lock files +3. Bundles code with esbuild and appropriate plugins +4. Processes HTML template (index.html or app.html) +5. Copies static assets from public/ or static/ +6. Writes output to dist/ directory +7. Emits `buildComplete` event for preview refresh + +### SvelteKit-Specific Features + +When building SvelteKit projects: +- Compiles `.svelte` components using Svelte 5 compiler from esm.sh +- Replaces SvelteKit placeholders in app.html: + - `%sveltekit.head%` - Replaced with script/style tags + - `%sveltekit.body%` - Replaced with `
` + - `%sveltekit.assets%` - Replaced with empty string + - `%sveltekit.nonce%` - Replaced with empty string +- Looks for entry points in `src/routes/` directory +- Copies static assets from `static/` instead of `public/` + +### Preview System + +The preview system uses `useIsProjectPreviewable()` to determine if a project can be previewed: + +- Returns `true` for React/Vite projects with `index.html` and `package.json` +- Returns `true` for SvelteKit projects with (`src/app.html` OR `svelte.config.*`) and `package.json` +- Returns `false` otherwise + +When a project is previewable, the PreviewPane component shows: +- Build button to trigger compilation +- Live preview iframe with the built application +- Console output and error messages +- Browser-like address bar + ## AI Message Format Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions: @@ -198,7 +291,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `useNWCContext`: Access NWC context provider - `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages) - `/src/lib/`: Utility functions and shared logic - - `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin) + - `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin, sveltePlugin) + - Supports both React/Vite projects and SvelteKit projects + - Automatic project type detection based on file structure - `/src/lib/commands/`: Shell command implementations for virtual filesystem - `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.) - Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc. diff --git a/package-lock.json b/package-lock.json index 856c6143..c31f1a04 100644 --- a/package-lock.json +++ b/package-lock.json @@ -114,6 +114,7 @@ "globals": "^15.9.0", "jsdom": "^26.1.0", "postcss": "^8.4.47", + "svelte": "^5.40.1", "tailwindcss": "^3.4.11", "typescript": "^5.5.3", "typescript-eslint": "^8.0.1", @@ -1249,6 +1250,17 @@ "node": ">=6.0.0" } }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -3250,6 +3262,16 @@ "resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/1.0.10.tgz", "integrity": "sha512-WK2njnDTyKefroRNk2Ooq7GStp6Y0ccAvr4To+Z/zecRAGe7+OSvH9DbiaHpAKwEi2KQbmpWMOYsdNt+TsdmSw==" }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.6.tgz", + "integrity": "sha512-4awhxtMh4cx9blePWl10HRHj8Iivtqj+2QdDCSMDzxG+XKa9+VCNupQuCuvzEhYPzZSrX+0gC+0lHA/0fFKKQQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, "node_modules/@swc/core": { "version": "1.11.24", "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz", @@ -4465,6 +4487,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/bail": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", @@ -5672,6 +5704,13 @@ "node": ">= 4" } }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "dev": true, + "license": "MIT" + }, "node_modules/espree": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", @@ -5703,6 +5742,16 @@ "node": ">=0.10" } }, + "node_modules/esrap": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.1.0.tgz", + "integrity": "sha512-yzmPNpl7TBbMRC5Lj2JlJZNPml0tzqoqP5B1JXycNUwtqma9AKCO0M2wHrdgsHcy1WRW7S9rJknAMtByg3usgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + } + }, "node_modules/esrecurse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", @@ -6706,6 +6755,16 @@ "dev": true, "license": "MIT" }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, "node_modules/is-typed-array": { "version": "1.1.15", "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", @@ -7044,6 +7103,13 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "dev": true, + "license": "MIT" + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -10055,6 +10121,42 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svelte": { + "version": "5.40.1", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.40.1.tgz", + "integrity": "sha512-0R3t2oiLxJNJb2buz61MNfPdkjeyj2qTCM7TtIv/4ZfF12zD7Ig8iIo+C8febroy+9S4QJ7qfijtearSdO/1ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.5", + "@types/estree": "^1.0.5", + "acorn": "^8.12.1", + "aria-query": "^5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "esm-env": "^1.2.1", + "esrap": "^2.1.0", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte/node_modules/aria-query": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", @@ -11485,6 +11587,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/zimmerframe": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", + "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", + "dev": true, + "license": "MIT" + }, "node_modules/zod": { "version": "3.25.76", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", diff --git a/package.json b/package.json index 640f2719..bbe4ae54 100644 --- a/package.json +++ b/package.json @@ -117,6 +117,7 @@ "globals": "^15.9.0", "jsdom": "^26.1.0", "postcss": "^8.4.47", + "svelte": "^5.40.1", "tailwindcss": "^3.4.11", "typescript": "^5.5.3", "typescript-eslint": "^8.0.1", diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index 725335f1..4f1dba77 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -325,7 +325,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { ? `${cdnName}@${version}${packagePath}` : `${cdnName}${packagePath}`; - const url = new URL(`${esmUrl}/*${specifier}`); + const url = new URL(`${esmUrl}/${specifier}`); if (target) url.searchParams.set("target", target); if (childLockPath) url.searchParams.set("lp", encodeURIComponent(childLockPath)); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index bb8799fa..6f050d18 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -9,6 +9,7 @@ import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; import { sveltePlugin } from "./sveltePlugin"; import { convertYarnLockToPackageLock } from "./yarnLockConverter"; +import { convertPnpmLockToPackageLock } from "./pnpmLockConverter"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -105,7 +106,7 @@ async function bundleSvelteKit( console.log('Merged Svelte aliases into tsconfig paths:', tsconfig.compilerOptions.paths); } - // Try to read package-lock.json first, fall back to yarn.lock + // Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml let packageLock; let buildMode: string; try { @@ -124,8 +125,17 @@ async function bundleSvelteKit( packageLock = convertYarnLockToPackageLock(yarnLockText); buildMode = "yarn (yarn.lock)"; } catch { - packageLock = { packages: {} }; - buildMode = "package.json only (no lock file)"; + try { + const pnpmLockText = await fs.readFile( + `${projectPath}/pnpm-lock.yaml`, + "utf8", + ); + packageLock = convertPnpmLockToPackageLock(pnpmLockText); + buildMode = "pnpm (pnpm-lock.yaml)"; + } catch { + packageLock = { packages: {} }; + buildMode = "package.json only (no lock file)"; + } } } @@ -191,22 +201,19 @@ async function bundleSvelteKit( const dist: Record = {}; const doc = domParser.parseFromString(appHtmlText, "text/html"); + // Track the main component file for mounting + let mainComponentPath: string | undefined; + // Process output files for (const file of results.outputFiles) { const ext = file.path.split('.').pop(); const filename = `${file.path.slice(1)}`; + const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, ''); if (ext === "js") { - const script = document.createElement("script"); - script.type = "module"; - script.src = "/" + filename; - - // Insert before %sveltekit.head% placeholder or in head - const head = doc.head; - if (head.textContent?.includes("%sveltekit.head%")) { - head.innerHTML = head.innerHTML.replace("%sveltekit.head%", script.outerHTML); - } else { - head.appendChild(script); + // Track the main component for mounting + if (entryPoint && entryPoints.includes(entryPoint)) { + mainComponentPath = "/" + filename; } dist[filename] = file.contents; @@ -227,6 +234,33 @@ async function bundleSvelteKit( } } + // Create a mounting script for the Svelte component + if (mainComponentPath) { + // Get svelte version from package.json + const svelteVersion = packageJson.dependencies?.svelte || + packageJson.devDependencies?.svelte || + '5'; + + const mountScript = ` + import Component from '${mainComponentPath}'; + import { mount } from '${esmUrl}/svelte@${svelteVersion}'; + + // Mount the component to the target element + const target = document.getElementById('svelte') || document.body; + mount(Component, { target }); + `; + + const mountScriptHash = Math.random().toString(36).substring(7); + const mountScriptFilename = `mount-${mountScriptHash}.js`; + dist[mountScriptFilename] = new TextEncoder().encode(mountScript); + + // Add the mount script to the HTML + const script = document.createElement("script"); + script.type = "module"; + script.src = "/" + mountScriptFilename; + doc.head.appendChild(script); + } + // Replace SvelteKit placeholders let htmlContent = doc.documentElement.outerHTML; @@ -283,7 +317,7 @@ async function bundle( tsconfig = undefined; } - // Try to read package-lock.json first, fall back to yarn.lock + // Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml let packageLock; let buildMode: string; try { @@ -303,9 +337,19 @@ async function bundle( packageLock = convertYarnLockToPackageLock(yarnLockText); buildMode = "yarn (yarn.lock)"; } catch { - // If neither exists, use empty packages object - packageLock = { packages: {} }; - buildMode = "package.json only (no lock file)"; + // If yarn.lock doesn't exist, try pnpm-lock.yaml + try { + const pnpmLockText = await fs.readFile( + `${projectPath}/pnpm-lock.yaml`, + "utf8", + ); + packageLock = convertPnpmLockToPackageLock(pnpmLockText); + buildMode = "pnpm (pnpm-lock.yaml)"; + } catch { + // If no lock file exists, use empty packages object + packageLock = { packages: {} }; + buildMode = "package.json only (no lock file)"; + } } } diff --git a/src/lib/build/pnpmLockConverter.test.ts b/src/lib/build/pnpmLockConverter.test.ts new file mode 100644 index 00000000..b2e9a551 --- /dev/null +++ b/src/lib/build/pnpmLockConverter.test.ts @@ -0,0 +1,270 @@ +import { describe, it, expect } from 'vitest'; +import { convertPnpmLockToPackageLock } from './pnpmLockConverter'; + +describe('convertPnpmLockToPackageLock', () => { + it('should convert a simple pnpm-lock.yaml entry', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /react@18.2.0: + version: 18.2.0 + resolution: {integrity: sha512-...} +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + expect(result.packages['node_modules/react']).toEqual({ + name: 'react', + version: '18.2.0', + }); + }); + + it('should convert scoped packages', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /@babel/core@7.23.0: + version: 7.23.0 + resolution: {integrity: sha512-...} +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + expect(result.packages['node_modules/@babel/core']).toEqual({ + name: '@babel/core', + version: '7.23.0', + }); + }); + + it('should parse dependencies', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /react-dom@18.2.0(react@18.2.0): + version: 18.2.0 + resolution: {integrity: sha512-...} + dependencies: + loose-envify: 1.4.0 + scheduler: 0.23.0 + peerDependencies: + react: ^18.2.0 +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + expect(result.packages['node_modules/react-dom']).toEqual({ + name: 'react-dom', + version: '18.2.0', + dependencies: { + 'loose-envify': '1.4.0', + 'scheduler': '0.23.0', + }, + peerDependencies: { + 'react': '^18.2.0', + }, + }); + }); + + it('should parse peer dependencies', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /@testing-library/react@14.0.0(react-dom@18.2.0)(react@18.2.0): + version: 14.0.0 + resolution: {integrity: sha512-...} + peerDependencies: + react: ^18.0.0 + react-dom: ^18.0.0 +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + 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 pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /react@18.2.0: + version: 18.2.0 + resolution: {integrity: sha512-...} + + /react-dom@18.2.0(react@18.2.0): + version: 18.2.0 + resolution: {integrity: sha512-...} + dependencies: + react: 18.2.0 +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + 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.2.0', + }, + }); + }); + + it('should skip entries without version', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /invalid-entry@1.0.0: + resolution: {integrity: sha512-...} + + /valid-entry@1.0.0: + version: 1.0.0 + resolution: {integrity: sha512-...} +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + 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 pnpm-lock.yaml', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + expect(result.packages).toEqual({}); + }); + + it('should handle packages with peer dependency specifiers in key', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /styled-components@6.0.0(react-dom@18.2.0)(react@18.2.0): + version: 6.0.0 + resolution: {integrity: sha512-...} + dependencies: + some-dep: 1.0.0 + peerDependencies: + react: '>= 16.8.0' + react-dom: '>= 16.8.0' +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + expect(result.packages['node_modules/styled-components']).toEqual({ + name: 'styled-components', + version: '6.0.0', + dependencies: { + 'some-dep': '1.0.0', + }, + peerDependencies: { + react: '>= 16.8.0', + 'react-dom': '>= 16.8.0', + }, + }); + }); + + it('should stop parsing after packages section ends', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /react@18.2.0: + version: 18.2.0 + resolution: {integrity: sha512-...} + +snapshots: + /react@18.2.0: + dependencies: + loose-envify: 1.4.0 +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + // Should only have the package from packages section, not from snapshots + expect(result.packages['node_modules/react']).toEqual({ + name: 'react', + version: '18.2.0', + }); + expect(Object.keys(result.packages).length).toBe(1); + }); + + it('should handle multiple installations of same package@version with different peer deps', () => { + const pnpmLock = ` +lockfileVersion: '9.0' + +packages: + + /eslint-plugin-svelte@3.9.3(eslint@9.34.0)(svelte@5.39.8): + version: 3.9.3 + resolution: {integrity: sha512-...} + peerDependencies: + eslint: ^8.0.0 || ^9.0.0 + svelte: ^4.0.0 || ^5.0.0 + + /eslint-plugin-svelte@3.9.3(eslint@8.57.1)(svelte@5.39.8): + version: 3.9.3 + resolution: {integrity: sha512-...} + peerDependencies: + eslint: ^8.0.0 || ^9.0.0 + svelte: ^4.0.0 || ^5.0.0 +`; + + const result = convertPnpmLockToPackageLock(pnpmLock); + + // First installation should use simple path + expect(result.packages['node_modules/eslint-plugin-svelte']).toEqual({ + name: 'eslint-plugin-svelte', + version: '3.9.3', + peerDependencies: { + eslint: '^8.0.0 || ^9.0.0', + svelte: '^4.0.0 || ^5.0.0', + }, + }); + + // Second installation should use nested path + expect(result.packages['node_modules/.pnpm/eslint-plugin-svelte_1']).toEqual({ + name: 'eslint-plugin-svelte', + version: '3.9.3', + peerDependencies: { + eslint: '^8.0.0 || ^9.0.0', + svelte: '^4.0.0 || ^5.0.0', + }, + }); + + expect(Object.keys(result.packages).length).toBe(2); + }); +}); diff --git a/src/lib/build/pnpmLockConverter.ts b/src/lib/build/pnpmLockConverter.ts new file mode 100644 index 00000000..209ed16a --- /dev/null +++ b/src/lib/build/pnpmLockConverter.ts @@ -0,0 +1,215 @@ +/** + * Converts pnpm-lock.yaml format to package-lock.json format for use with esmPlugin. + * This is a simplified converter that extracts enough information for dependency resolution. + */ + +interface PnpmLockPackage { + version?: string; + dependencies?: Record; + peerDependencies?: Record; +} + +interface PackageLockPackage { + name?: string; + version: string; + dependencies?: Record; + peerDependencies?: Record; +} + +interface PackageLock { + packages: { + [key: string]: PackageLockPackage; + }; +} + +/** + * Parse a pnpm-lock.yaml file and convert it to package-lock.json format + */ +export function convertPnpmLockToPackageLock(pnpmLockContent: string): PackageLock { + const packages: Record = {}; + + // Parse pnpm-lock.yaml entries + const entries = parsePnpmLock(pnpmLockContent); + + // Track which package@version combinations we've seen to handle duplicates + const seenVersions = new Map(); + + for (const [key, entry] of Object.entries(entries)) { + if (!entry.version) continue; + + const packageName = extractPackageName(key); + if (!packageName) continue; + + const versionKey = `${packageName}@${entry.version}`; + const count = seenVersions.get(versionKey) || 0; + seenVersions.set(versionKey, count + 1); + + // Determine the lock path + let lockPath: string; + + if (count === 0) { + // First occurrence - use simple node_modules path + lockPath = `node_modules/${packageName}`; + } else { + // Subsequent occurrences - create unique nested paths + // This handles cases where the same package@version is installed + // multiple times with different peer dependencies + lockPath = `node_modules/.pnpm/${packageName}_${count}`; + } + + packages[lockPath] = { + name: packageName, + version: entry.version, + dependencies: entry.dependencies, + peerDependencies: entry.peerDependencies, + }; + } + + return { packages }; +} + +/** + * Parse pnpm-lock.yaml content into a map of entries + * This is a simple YAML parser focused on the packages section + */ +function parsePnpmLock(content: string): Record { + const entries: Record = {}; + const lines = content.split('\n'); + + let inPackagesSection = false; + 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.trim().startsWith('#') || line.trim() === '') { + continue; + } + + // Detect the packages section + if (line.match(/^packages:/)) { + inPackagesSection = true; + continue; + } + + // Exit packages section when we hit another top-level key + if (inPackagesSection && line.match(/^[a-zA-Z]/)) { + inPackagesSection = false; + // Save last entry before exiting + if (currentKey && currentEntry.version) { + entries[currentKey] = currentEntry as PnpmLockPackage; + } + break; + } + + if (!inPackagesSection) continue; + + // Get indentation level + const indent = line.search(/\S/); + if (indent === -1) continue; + + // Package entry (2-space indent from packages:) + // Example: " /@babel/core@7.23.0:" + const packageMatch = line.match(/^ {2}(\/[^:]+):\s*$/); + if (packageMatch) { + // Save previous entry + if (currentKey && currentEntry.version) { + entries[currentKey] = currentEntry as PnpmLockPackage; + } + + // Start new entry + currentKey = packageMatch[1]; + currentEntry = {}; + inDependencies = false; + inPeerDependencies = false; + continue; + } + + // Skip if we don't have a current package + if (!currentKey) continue; + + // Property lines (4-space indent from package key) + const propertyMatch = line.match(/^ {4}([a-zA-Z]+):\s*$/); + const valueMatch = line.match(/^ {4}([a-zA-Z]+):\s*(.+)\s*$/); + const depMatch = line.match(/^ {6}([^:]+):\s*(.+)\s*$/); + + if (propertyMatch) { + 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 && !inDependencies && !inPeerDependencies) { + const [, key, value] = valueMatch; + + if (key === 'version') { + currentEntry.version = value.trim(); + } + } else if (depMatch) { + const [, key, value] = depMatch; + const cleanKey = key.trim(); + // Remove quotes from value if present + const cleanValue = value.trim().replace(/^['"]|['"]$/g, ''); + + if (inDependencies && currentEntry.dependencies) { + currentEntry.dependencies[cleanKey] = cleanValue; + } else if (inPeerDependencies && currentEntry.peerDependencies) { + currentEntry.peerDependencies[cleanKey] = cleanValue; + } + } + } + + // Save last entry + if (currentKey && currentEntry.version) { + entries[currentKey] = currentEntry as PnpmLockPackage; + } + + return entries; +} + +/** + * Extract the package name from a pnpm-lock.yaml key + * Examples: + * "/@babel/core@7.23.0" -> "@babel/core" + * "/react@18.2.0" -> "react" + * "/react-dom@18.2.0(react@18.2.0)" -> "react-dom" + */ +function extractPackageName(key: string): string | null { + // Remove leading slash + let cleaned = key.startsWith('/') ? key.slice(1) : key; + + // Remove peer dependency specifications in parentheses + // Example: "react-dom@18.2.0(react@18.2.0)" -> "react-dom@18.2.0" + cleaned = cleaned.replace(/\([^)]*\)$/, ''); + + // Handle scoped packages: "@scope/package@version" + if (cleaned.startsWith('@')) { + const parts = cleaned.split('@'); + // parts will be: ['', 'scope/package', 'version'] + if (parts.length >= 2) { + return `@${parts[1]}`; + } + } + + // Handle regular packages: "package@version" + const atIndex = cleaned.indexOf('@'); + if (atIndex > 0) { + return cleaned.substring(0, atIndex); + } + + // If no @ found, return the whole string + return cleaned || null; +}