mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Experimental yarn.lock conversion
This commit is contained in:
5 files changed
+471
-9
No files matched your search
@@ -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;
|
||||
|
||||
@@ -293,4 +293,119 @@ 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 '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
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 '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
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');
|
||||
});
|
||||
});
|
||||
+24
-5
@@ -6,6 +6,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 +29,28 @@ async function bundle(
|
||||
`${projectPath}/index.html`,
|
||||
"utf8",
|
||||
);
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
let packageLock;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
} catch {
|
||||
// If package-lock.json doesn't exist, try yarn.lock
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
}
|
||||
}
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
const entryPoints: string[] = [];
|
||||
@@ -80,7 +99,7 @@ async function bundle(
|
||||
plugins: [
|
||||
shakespearePlugin(),
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
esmPlugin(packageLock, target),
|
||||
],
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
|
||||
@@ -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({});
|
||||
});
|
||||
});
|
||||
@@ -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<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface PackageLockPackage {
|
||||
name?: string;
|
||||
version: string;
|
||||
dependencies?: Record<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
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<string, PackageLockPackage> = {};
|
||||
|
||||
// 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<string, YarnLockEntry> {
|
||||
const entries: Record<string, YarnLockEntry> = {};
|
||||
const lines = content.split('\n');
|
||||
|
||||
let currentKey: string | null = null;
|
||||
let currentEntry: Partial<YarnLockEntry> = {};
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user