Give up on CapacitorFS, just use IndexedDB

This commit is contained in:
Alex Gleason committed 2025-10-03 23:21:30 -05:00
1 parent f06e4cef89
commit 72df9e1e98
3 files changed
+3 -698

No files matched your search

+3 -26
View File
@@ -6,7 +6,6 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import { Capacitor } from '@capacitor/core';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -20,8 +19,6 @@ import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { CapacitorFSAdapter } from '@/lib/CapacitorFSAdapter';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import AppRouter from './AppRouter';
@@ -54,29 +51,9 @@ const presetRelays = [
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
/**
* Initialize filesystem based on platform
*/
function initializeFilesystem(): JSRuntimeFS {
const isNative = Capacitor.isNativePlatform();
const platform = Capacitor.getPlatform();
console.log(`Initializing filesystem for platform: ${platform} (native: ${isNative})`);
if (isNative) {
// Use native filesystem on Android/iOS
console.log('Using Capacitor native filesystem');
return new CapacitorFSAdapter();
} else {
// Use IndexedDB-based filesystem on web
console.log('Using LightningFS (IndexedDB)');
const lightningFS = new LightningFS('shakespeare-fs');
return new LightningFSAdapter(lightningFS.promises);
}
}
// Initialize the appropriate filesystem
const fs = initializeFilesystem();
// Initialize the filesystem
const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises);
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from /tmp directory
-345
View File
@@ -1,345 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CapacitorFSAdapter } from './CapacitorFSAdapter';
import * as Filesystem from '@capacitor/filesystem';
// Mock Capacitor Filesystem
vi.mock('@capacitor/filesystem', () => ({
Filesystem: {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
deleteFile: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
},
Directory: {
Data: 'DATA',
},
Encoding: {
UTF8: 'utf8',
},
}));
describe('CapacitorFSAdapter', () => {
let adapter: CapacitorFSAdapter;
beforeEach(() => {
adapter = new CapacitorFSAdapter();
vi.clearAllMocks();
});
describe('readFile', () => {
it('should read text file with utf8 encoding', async () => {
vi.mocked(Filesystem.Filesystem.readFile).mockResolvedValue({
data: 'hello world',
});
const result = await adapter.readFile('/test.txt', 'utf8');
expect(result).toBe('hello world');
expect(Filesystem.Filesystem.readFile).toHaveBeenCalledWith({
path: 'test.txt',
directory: 'DATA',
encoding: 'utf8',
});
});
it('should read binary file and convert from base64', async () => {
// Binary data returned as base64 when no encoding specified
vi.mocked(Filesystem.Filesystem.readFile).mockResolvedValue({
data: 'aGVsbG8=', // 'hello' in base64
});
const result = await adapter.readFile('/test.bin');
expect(result).toBeInstanceOf(Uint8Array);
expect(Array.from(result as Uint8Array)).toEqual([104, 101, 108, 108, 111]);
expect(Filesystem.Filesystem.readFile).toHaveBeenCalledWith({
path: 'test.bin',
directory: 'DATA',
});
});
it('should throw error for non-existent file', async () => {
vi.mocked(Filesystem.Filesystem.readFile).mockRejectedValue(
new Error('File not found')
);
await expect(adapter.readFile('/missing.txt')).rejects.toThrow();
});
});
describe('writeFile', () => {
it('should write text file with utf8 encoding', async () => {
vi.mocked(Filesystem.Filesystem.writeFile).mockResolvedValue({ uri: '' });
await adapter.writeFile('/test.txt', 'hello world', 'utf8');
expect(Filesystem.Filesystem.writeFile).toHaveBeenCalledWith({
path: 'test.txt',
directory: 'DATA',
data: 'hello world',
encoding: 'utf8',
});
});
it('should write binary file as base64', async () => {
vi.mocked(Filesystem.Filesystem.writeFile).mockResolvedValue({ uri: '' });
const data = new Uint8Array([104, 101, 108, 108, 111]); // 'hello'
await adapter.writeFile('/test.bin', data);
expect(Filesystem.Filesystem.writeFile).toHaveBeenCalledWith({
path: 'test.bin',
directory: 'DATA',
data: 'aGVsbG8=', // base64 encoded
});
});
it('should normalize paths and remove trailing slashes', async () => {
vi.mocked(Filesystem.Filesystem.writeFile).mockResolvedValue({ uri: '' });
const data = new Uint8Array([104, 101, 108, 108, 111]);
await adapter.writeFile('/test.bin/', data); // Note the trailing slash
expect(Filesystem.Filesystem.writeFile).toHaveBeenCalledWith({
path: 'test.bin', // Trailing slash should be removed
directory: 'DATA',
data: 'aGVsbG8=', // base64 encoded
});
});
});
describe('readdir', () => {
it('should list directory contents', async () => {
vi.mocked(Filesystem.Filesystem.readdir).mockResolvedValue({
files: [
{ name: 'file1.txt', type: 'file', size: 100, ctime: 0, mtime: 0, uri: '' },
{ name: 'file2.txt', type: 'file', size: 200, ctime: 0, mtime: 0, uri: '' },
],
});
const result = await adapter.readdir('/test');
expect(result).toEqual(['file1.txt', 'file2.txt']);
});
it('should list directory with file types', async () => {
vi.mocked(Filesystem.Filesystem.readdir).mockResolvedValue({
files: [
{ name: 'file.txt', type: 'file', size: 100, ctime: 0, mtime: 0, uri: '' },
{ name: 'subdir', type: 'directory', size: 0, ctime: 0, mtime: 0, uri: '' },
],
});
vi.mocked(Filesystem.Filesystem.stat)
.mockResolvedValueOnce({
type: 'file',
size: 100,
ctime: 0,
mtime: 0,
uri: '',
name: 'file.txt',
})
.mockResolvedValueOnce({
type: 'directory',
size: 0,
ctime: 0,
mtime: 0,
uri: '',
name: 'subdir',
});
const result = await adapter.readdir('/test', { withFileTypes: true });
expect(result).toHaveLength(2);
expect(result[0].name).toBe('file.txt');
expect(result[0].isFile()).toBe(true);
expect(result[0].isDirectory()).toBe(false);
expect(result[1].name).toBe('subdir');
expect(result[1].isFile()).toBe(false);
expect(result[1].isDirectory()).toBe(true);
});
});
describe('mkdir', () => {
it('should create directory', async () => {
vi.mocked(Filesystem.Filesystem.mkdir).mockResolvedValue();
await adapter.mkdir('/test');
expect(Filesystem.Filesystem.mkdir).toHaveBeenCalledWith({
path: 'test',
directory: 'DATA',
recursive: true,
});
});
it('should create directory recursively', async () => {
vi.mocked(Filesystem.Filesystem.mkdir).mockResolvedValue();
await adapter.mkdir('/test/nested/path', { recursive: true });
expect(Filesystem.Filesystem.mkdir).toHaveBeenCalledWith({
path: 'test/nested/path',
directory: 'DATA',
recursive: true,
});
});
it('should ignore exists error when recursive', async () => {
vi.mocked(Filesystem.Filesystem.mkdir).mockRejectedValue(
new Error('Directory already exists')
);
await expect(adapter.mkdir('/test', { recursive: true })).resolves.toBeUndefined();
});
});
describe('stat', () => {
it('should get file stats', async () => {
vi.mocked(Filesystem.Filesystem.stat).mockResolvedValue({
type: 'file',
size: 1024,
ctime: 1000,
mtime: 2000,
uri: '',
name: 'test.txt',
});
const result = await adapter.stat('/test.txt');
expect(result.isFile()).toBe(true);
expect(result.isDirectory()).toBe(false);
expect(result.size).toBe(1024);
expect(result.mtimeMs).toBe(2000);
});
it('should get directory stats', async () => {
vi.mocked(Filesystem.Filesystem.stat).mockResolvedValue({
type: 'directory',
size: 0,
ctime: 1000,
mtime: 2000,
uri: '',
name: 'test',
});
const result = await adapter.stat('/test');
expect(result.isFile()).toBe(false);
expect(result.isDirectory()).toBe(true);
});
});
describe('unlink', () => {
it('should delete file', async () => {
vi.mocked(Filesystem.Filesystem.deleteFile).mockResolvedValue(undefined);
await adapter.unlink('/test.txt');
expect(Filesystem.Filesystem.deleteFile).toHaveBeenCalledWith({
path: 'test.txt',
directory: 'DATA',
});
});
});
describe('rmdir', () => {
it('should remove directory', async () => {
vi.mocked(Filesystem.Filesystem.rmdir).mockResolvedValue(undefined);
await adapter.rmdir('/test');
expect(Filesystem.Filesystem.rmdir).toHaveBeenCalledWith({
path: 'test',
directory: 'DATA',
recursive: false,
});
});
});
describe('rename', () => {
it('should rename file', async () => {
vi.mocked(Filesystem.Filesystem.rename).mockResolvedValue(undefined);
await adapter.rename('/old.txt', '/new.txt');
expect(Filesystem.Filesystem.rename).toHaveBeenCalledWith({
from: 'old.txt',
to: 'new.txt',
directory: 'DATA',
});
});
});
describe('symlink operations', () => {
it('should create symlink by copying file', async () => {
vi.mocked(Filesystem.Filesystem.readFile).mockResolvedValue({
data: 'aGVsbG8=', // base64
});
vi.mocked(Filesystem.Filesystem.writeFile).mockResolvedValue({ uri: '' });
await adapter.symlink('/target.txt', '/link.txt');
expect(Filesystem.Filesystem.readFile).toHaveBeenCalledWith({
path: 'target.txt',
directory: 'DATA',
});
expect(Filesystem.Filesystem.writeFile).toHaveBeenCalledTimes(2);
// First call writes the actual file
// Second call writes the .symlink metadata file
});
it('should read symlink target from metadata', async () => {
vi.mocked(Filesystem.Filesystem.readFile).mockResolvedValue({
data: '/target.txt',
});
const result = await adapter.readlink('/link.txt');
expect(result).toBe('/target.txt');
expect(Filesystem.Filesystem.readFile).toHaveBeenCalledWith({
path: 'link.txt.symlink',
directory: 'DATA',
encoding: 'utf8',
});
});
});
describe('path normalization', () => {
it('should handle root path', async () => {
vi.mocked(Filesystem.Filesystem.readdir).mockResolvedValue({
files: [],
});
await adapter.readdir('/');
expect(Filesystem.Filesystem.readdir).toHaveBeenCalledWith({
path: '.',
directory: 'DATA',
});
});
it('should remove leading slash from paths', async () => {
vi.mocked(Filesystem.Filesystem.stat).mockResolvedValue({
type: 'file',
size: 0,
ctime: 0,
mtime: 0,
uri: '',
name: 'file.txt',
});
await adapter.stat('/some/path/file.txt');
expect(Filesystem.Filesystem.stat).toHaveBeenCalledWith({
path: 'some/path/file.txt',
directory: 'DATA',
});
});
});
});
-327
View File
@@ -1,327 +0,0 @@
/**
* Capacitor Filesystem Adapter
*
* Adapts Capacitor's Filesystem plugin to work with the JSRuntimeFS interface.
* This enables native filesystem storage on Android/iOS while maintaining
* compatibility with existing code.
*/
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { Buffer } from 'buffer';
import path from 'path-browserify';
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
export class CapacitorFSAdapter implements JSRuntimeFS {
/**
* Base directory for all file operations
* Directory.Data is app-private and included in backups
*/
private baseDirectory = Directory.Data;
/**
* Convert absolute paths to relative paths for Capacitor
* Capacitor expects paths relative to the base directory
*/
private normalizePath(inputPath: string): string {
// Normalize the path using path-browserify
let normalized = path.normalize(inputPath);
// Remove leading slash for Capacitor
normalized = normalized.startsWith('/') ? normalized.slice(1) : normalized;
// Remove ALL trailing slashes (important for file operations)
// Capacitor treats paths with trailing slashes as directories
// Use regex to remove all trailing slashes
normalized = normalized.replace(/\/+$/, '');
// Ensure we don't have empty path
if (normalized === '' || normalized === '.') {
normalized = '.';
}
return normalized;
}
/**
* Read file as Uint8Array or string
*/
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const normalizedPath = this.normalizePath(path);
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8') {
// Read as UTF-8 text
const result = await Filesystem.readFile({
path: normalizedPath,
directory: this.baseDirectory,
encoding: Encoding.UTF8,
});
if (result.data instanceof Blob) {
return await result.data.text();
} else {
return result.data;
}
} else {
// Read as base64 (no encoding specified)
const result = await Filesystem.readFile({
path: normalizedPath,
directory: this.baseDirectory,
});
let base64: string;
if (result.data instanceof Blob) {
base64 = await result.data.text();
} else {
base64 = result.data;
}
// Decode base64 and return as Buffer for compatibility with isomorphic-git
return Buffer.from(base64, 'base64');
}
}
/**
* Write file from string or Uint8Array
*/
async writeFile(filePath: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const normalizedPath = this.normalizePath(filePath);
if (data instanceof Uint8Array) {
// Write binary data as base64 using Buffer for consistency with readFile
const base64Data = Buffer.from(data).toString('base64');
await Filesystem.writeFile({
path: normalizedPath,
directory: this.baseDirectory,
data: base64Data,
});
} else {
// Write string data as UTF-8
await Filesystem.writeFile({
path: normalizedPath,
directory: this.baseDirectory,
data: data,
encoding: Encoding.UTF8,
});
}
}
/**
* Read directory contents
*/
async readdir(dirPath: string): Promise<string[]>;
async readdir(dirPath: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(dirPath: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(dirPath: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
try {
const normalizedPath = this.normalizePath(dirPath);
const result = await Filesystem.readdir({
path: normalizedPath,
directory: this.baseDirectory,
});
if (options?.withFileTypes) {
// Get file type information for each entry
const entries: DirectoryEntry[] = [];
for (const file of result.files) {
const fullPath = path.join(dirPath, file.name);
try {
const stat = await this.stat(fullPath);
entries.push({
name: file.name,
isDirectory: () => stat.isDirectory(),
isFile: () => stat.isFile(),
});
} catch {
// If stat fails, assume it's a file
entries.push({
name: file.name,
isDirectory: () => false,
isFile: () => true,
});
}
}
return entries;
}
return result.files.map(f => f.name);
} catch {
const nodeError = new Error(`ENOENT: no such file or directory, scandir '${dirPath}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'scandir';
nodeError.path = dirPath;
throw nodeError;
}
}
/**
* Create directory
*/
async mkdir(path: string): Promise<void> {
try {
await Filesystem.mkdir({
path: this.normalizePath(path),
directory: this.baseDirectory,
recursive: true,
});
} catch (error) {
// Ignore "directory exists" errors when recursive is true
if (error instanceof Error && (error.message.includes('exists') || error.message.includes('EEXIST'))) {
return;
} else {
throw error;
}
}
}
/**
* Get file/directory stats
*/
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isSymbolicLink(): boolean;
size?: number;
mtimeMs?: number;
}> {
try {
const normalizedPath = this.normalizePath(path);
const result = await Filesystem.stat({
path: normalizedPath,
directory: this.baseDirectory,
});
return {
isDirectory: () => result.type === 'directory',
isFile: () => result.type === 'file',
isSymbolicLink: () => false, // Capacitor doesn't support symlinks
size: result.size,
mtimeMs: result.mtime ?? Date.now(), // Default to current time if not provided
};
} catch {
// Create a proper Node.js-style error
const nodeError = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'stat';
nodeError.path = path;
throw nodeError;
}
}
/**
* Get file/directory stats (same as stat for Capacitor)
*/
async lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isSymbolicLink(): boolean;
size?: number;
mtimeMs?: number;
}> {
try {
const normalizedPath = this.normalizePath(path);
const result = await Filesystem.stat({
path: normalizedPath,
directory: this.baseDirectory,
});
return {
isDirectory: () => result.type === 'directory',
isFile: () => result.type === 'file',
isSymbolicLink: () => false, // Capacitor doesn't support symlinks
size: result.size,
mtimeMs: result.mtime ?? Date.now(), // Default to current time if not provided
};
} catch {
// Create a proper Node.js-style error
const nodeError = new Error(`ENOENT: no such file or directory, lstat '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'lstat';
nodeError.path = path;
throw nodeError;
}
}
/**
* Delete file
*/
async unlink(path: string): Promise<void> {
try {
const normalizedPath = this.normalizePath(path);
await Filesystem.deleteFile({
path: normalizedPath,
directory: this.baseDirectory,
});
} catch {
const nodeError = new Error(`ENOENT: no such file or directory, unlink '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'unlink';
nodeError.path = path;
throw nodeError;
}
}
/**
* Remove directory
*/
async rmdir(path: string): Promise<void> {
await Filesystem.rmdir({
path: this.normalizePath(path),
directory: this.baseDirectory,
recursive: false, // Only remove if empty
});
}
/**
* Rename/move file or directory
*/
async rename(oldPath: string, newPath: string): Promise<void> {
await Filesystem.rename({
from: this.normalizePath(oldPath),
to: this.normalizePath(newPath),
directory: this.baseDirectory,
});
}
/**
* Read symbolic link
* Note: Capacitor doesn't support symlinks, so we implement a workaround
* by storing symlink info in a special file
*/
async readlink(path: string): Promise<string> {
try {
// Try to read symlink metadata file
const symlinkPath = `${path}.symlink`;
const target = await this.readFile(symlinkPath, 'utf8');
return target;
} catch {
throw new Error(`Symbolic links are not fully supported on this platform: ${path}`);
}
}
/**
* Create symbolic link
* Note: Capacitor doesn't support symlinks, so we implement a workaround
* by copying the file instead and storing symlink metadata
*/
async symlink(target: string, path: string): Promise<void> {
// Copy the target file to the symlink location
const data = await this.readFile(target);
await this.writeFile(path, data);
// Store symlink metadata for readlink
const symlinkPath = `${path}.symlink`;
await this.writeFile(symlinkPath, target);
}
}