Init
This commit is contained in:
10
src/lib/Counter.svelte
Normal file
10
src/lib/Counter.svelte
Normal file
@ -0,0 +1,10 @@
|
||||
<script lang="ts">
|
||||
let count: number = $state(0)
|
||||
const increment = () => {
|
||||
count += 1
|
||||
}
|
||||
</script>
|
||||
|
||||
<button onclick={increment}>
|
||||
count is {count}
|
||||
</button>
|
||||
166
src/lib/project-system/compression.ts
Normal file
166
src/lib/project-system/compression.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import pako from 'pako';
|
||||
import type { CsoundProject, CompressedProject } from './types';
|
||||
|
||||
const COMPRESSION_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Convert a string to a Uint8Array
|
||||
*/
|
||||
function stringToUint8Array(str: string): Uint8Array {
|
||||
const encoder = new TextEncoder();
|
||||
return encoder.encode(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Uint8Array to a string
|
||||
*/
|
||||
function uint8ArrayToString(arr: Uint8Array): string {
|
||||
const decoder = new TextDecoder();
|
||||
return decoder.decode(arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert Uint8Array to base64 string (URL-safe)
|
||||
*/
|
||||
function uint8ArrayToBase64(arr: Uint8Array): string {
|
||||
let binary = '';
|
||||
const len = arr.byteLength;
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(arr[i]);
|
||||
}
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert base64 string (URL-safe) to Uint8Array
|
||||
*/
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
// Restore standard base64
|
||||
const standardBase64 = base64
|
||||
.replace(/-/g, '+')
|
||||
.replace(/_/g, '/');
|
||||
|
||||
// Add padding if needed
|
||||
const padding = '='.repeat((4 - (standardBase64.length % 4)) % 4);
|
||||
const paddedBase64 = standardBase64 + padding;
|
||||
|
||||
const binary = atob(paddedBase64);
|
||||
const len = binary.length;
|
||||
const arr = new Uint8Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr[i] = binary.charCodeAt(i);
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress a project to a base64 string for sharing
|
||||
*/
|
||||
export function compressProject(project: CsoundProject): CompressedProject {
|
||||
try {
|
||||
// Convert project to JSON string
|
||||
const jsonString = JSON.stringify(project);
|
||||
|
||||
// Convert to Uint8Array
|
||||
const uint8Array = stringToUint8Array(jsonString);
|
||||
|
||||
// Compress using pako (gzip)
|
||||
const compressed = pako.deflate(uint8Array, { level: 9 });
|
||||
|
||||
// Convert to base64
|
||||
const base64 = uint8ArrayToBase64(compressed);
|
||||
|
||||
return {
|
||||
data: base64,
|
||||
version: COMPRESSION_VERSION,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to compress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompress a base64 string back to a project
|
||||
*/
|
||||
export function decompressProject(compressed: CompressedProject): CsoundProject {
|
||||
try {
|
||||
// Check version compatibility
|
||||
if (compressed.version !== COMPRESSION_VERSION) {
|
||||
throw new Error(`Unsupported compression version: ${compressed.version}`);
|
||||
}
|
||||
|
||||
// Convert base64 to Uint8Array
|
||||
const uint8Array = base64ToUint8Array(compressed.data);
|
||||
|
||||
// Decompress using pako
|
||||
const decompressed = pako.inflate(uint8Array);
|
||||
|
||||
// Convert to string
|
||||
const jsonString = uint8ArrayToString(decompressed);
|
||||
|
||||
// Parse JSON
|
||||
const project = JSON.parse(jsonString) as CsoundProject;
|
||||
|
||||
// Validate that we have the required fields
|
||||
if (!project.id || !project.title || !project.content === undefined) {
|
||||
throw new Error('Invalid project data structure');
|
||||
}
|
||||
|
||||
return project;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to decompress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shareable URL from a project
|
||||
*/
|
||||
export function projectToShareUrl(project: CsoundProject, baseUrl: string = window.location.origin): string {
|
||||
const compressed = compressProject(project);
|
||||
const params = new URLSearchParams({
|
||||
v: compressed.version.toString(),
|
||||
d: compressed.data,
|
||||
});
|
||||
|
||||
return `${baseUrl}?${params.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a project from a URL
|
||||
*/
|
||||
export function projectFromShareUrl(url: string): CsoundProject {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
const params = urlObj.searchParams;
|
||||
|
||||
const version = parseInt(params.get('v') || '1', 10);
|
||||
const data = params.get('d');
|
||||
|
||||
if (!data) {
|
||||
throw new Error('No project data found in URL');
|
||||
}
|
||||
|
||||
const compressed: CompressedProject = { version, data };
|
||||
return decompressProject(compressed);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse project from URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the approximate compression ratio
|
||||
*/
|
||||
export function getCompressionRatio(project: CsoundProject): number {
|
||||
const original = JSON.stringify(project);
|
||||
const compressed = compressProject(project);
|
||||
|
||||
const originalSize = new TextEncoder().encode(original).length;
|
||||
const compressedSize = base64ToUint8Array(compressed.data).length;
|
||||
|
||||
return originalSize / compressedSize;
|
||||
}
|
||||
233
src/lib/project-system/db.ts
Normal file
233
src/lib/project-system/db.ts
Normal file
@ -0,0 +1,233 @@
|
||||
import type { CsoundProject } from './types';
|
||||
|
||||
const DB_NAME = 'csound-projects-db';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = 'projects';
|
||||
|
||||
/**
|
||||
* Database wrapper for IndexedDB operations
|
||||
*/
|
||||
class ProjectDatabase {
|
||||
private db: IDBDatabase | null = null;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
|
||||
/**
|
||||
* Initialize the database connection
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
if (this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initPromise) {
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
this.initPromise = new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to open database: ${request.error?.message}`));
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
this.db = request.result;
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
// Create object store if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
const objectStore = db.createObjectStore(STORE_NAME, {
|
||||
keyPath: 'id',
|
||||
});
|
||||
|
||||
// Create indexes for efficient querying
|
||||
objectStore.createIndex('title', 'title', { unique: false });
|
||||
objectStore.createIndex('author', 'author', { unique: false });
|
||||
objectStore.createIndex('dateCreated', 'dateCreated', { unique: false });
|
||||
objectStore.createIndex('dateModified', 'dateModified', { unique: false });
|
||||
objectStore.createIndex('tags', 'tags', { unique: false, multiEntry: true });
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure database is initialized
|
||||
*/
|
||||
private async ensureDb(): Promise<IDBDatabase> {
|
||||
await this.init();
|
||||
if (!this.db) {
|
||||
throw new Error('Database not initialized');
|
||||
}
|
||||
return this.db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID
|
||||
*/
|
||||
async get(id: string): Promise<CsoundProject | null> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.get(id);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || null);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all projects
|
||||
*/
|
||||
async getAll(): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.getAll();
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get all projects: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save or update a project
|
||||
*/
|
||||
async put(project: CsoundProject): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.put(project);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to save project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project by ID
|
||||
*/
|
||||
async delete(id: string): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.delete(id);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to delete project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by tag
|
||||
*/
|
||||
async getByTag(tag: string): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const index = store.index('tags');
|
||||
const request = index.getAll(tag);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get projects by tag: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by author
|
||||
*/
|
||||
async getByAuthor(author: string): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const index = store.index('author');
|
||||
const request = index.getAll(author);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get projects by author: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all projects (use with caution!)
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.clear();
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to clear projects: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the database connection
|
||||
*/
|
||||
close(): void {
|
||||
if (this.db) {
|
||||
this.db.close();
|
||||
this.db = null;
|
||||
this.initPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const projectDb = new ProjectDatabase();
|
||||
56
src/lib/project-system/index.ts
Normal file
56
src/lib/project-system/index.ts
Normal file
@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Csound Project Management System
|
||||
*
|
||||
* This module provides a complete project system for managing Csound code files
|
||||
* with browser-based storage (IndexedDB) and import/export functionality via
|
||||
* compressed URLs.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { projectManager } from './lib/project-system';
|
||||
*
|
||||
* // Initialize
|
||||
* await projectManager.init();
|
||||
*
|
||||
* // Create a new project
|
||||
* const result = await projectManager.createProject({
|
||||
* title: 'My First Csound Project',
|
||||
* author: 'John Doe',
|
||||
* content: '<CsoundSynthesizer>...</CsoundSynthesizer>',
|
||||
* tags: ['synth', 'experiment']
|
||||
* });
|
||||
*
|
||||
* // Get all projects
|
||||
* const projects = await projectManager.getAllProjects();
|
||||
*
|
||||
* // Export to shareable URL
|
||||
* const urlResult = await projectManager.exportProjectToUrl(result.data.id);
|
||||
*
|
||||
* // Import from URL
|
||||
* const imported = await projectManager.importProjectFromUrl(url);
|
||||
* ```
|
||||
*/
|
||||
|
||||
// Export types
|
||||
export type {
|
||||
CsoundProject,
|
||||
CreateProjectData,
|
||||
UpdateProjectData,
|
||||
CompressedProject,
|
||||
Result,
|
||||
} from './types';
|
||||
|
||||
// Export main API
|
||||
export { ProjectManager, projectManager } from './project-manager';
|
||||
|
||||
// Export database (for advanced usage)
|
||||
export { projectDb } from './db';
|
||||
|
||||
// Export compression utilities (for advanced usage)
|
||||
export {
|
||||
compressProject,
|
||||
decompressProject,
|
||||
projectToShareUrl,
|
||||
projectFromShareUrl,
|
||||
getCompressionRatio,
|
||||
} from './compression';
|
||||
343
src/lib/project-system/project-manager.ts
Normal file
343
src/lib/project-system/project-manager.ts
Normal file
@ -0,0 +1,343 @@
|
||||
import type { CsoundProject, CreateProjectData, UpdateProjectData, Result } from './types';
|
||||
import { projectDb } from './db';
|
||||
import { compressProject, decompressProject, projectToShareUrl, projectFromShareUrl } from './compression';
|
||||
|
||||
const CSOUND_VERSION = '7.0.0'; // This should be detected from @csound/browser
|
||||
|
||||
/**
|
||||
* Generate a unique ID for a project
|
||||
*/
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current ISO timestamp
|
||||
*/
|
||||
function getCurrentTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Project Manager - Main API for managing Csound projects
|
||||
*/
|
||||
export class ProjectManager {
|
||||
/**
|
||||
* Initialize the project manager (initializes database)
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
await projectDb.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new project
|
||||
*/
|
||||
async createProject(data: CreateProjectData): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const now = getCurrentTimestamp();
|
||||
|
||||
const project: CsoundProject = {
|
||||
id: generateId(),
|
||||
title: data.title,
|
||||
author: data.author,
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
content: data.content || '',
|
||||
tags: data.tags || [],
|
||||
csoundVersion: CSOUND_VERSION,
|
||||
};
|
||||
|
||||
await projectDb.put(project);
|
||||
|
||||
return { success: true, data: project };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to create project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID
|
||||
*/
|
||||
async getProject(id: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: project };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all projects
|
||||
*/
|
||||
async getAllProjects(): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getAll();
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get projects'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing project
|
||||
*/
|
||||
async updateProject(data: UpdateProjectData): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const existingProject = await projectDb.get(data.id);
|
||||
|
||||
if (!existingProject) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${data.id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const updatedProject: CsoundProject = {
|
||||
...existingProject,
|
||||
...(data.title !== undefined && { title: data.title }),
|
||||
...(data.author !== undefined && { author: data.author }),
|
||||
...(data.content !== undefined && { content: data.content }),
|
||||
...(data.tags !== undefined && { tags: data.tags }),
|
||||
dateModified: getCurrentTimestamp(),
|
||||
saveCount: existingProject.saveCount + 1,
|
||||
};
|
||||
|
||||
await projectDb.put(updatedProject);
|
||||
|
||||
return { success: true, data: updatedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to update project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project
|
||||
*/
|
||||
async deleteProject(id: string): Promise<Result<void>> {
|
||||
try {
|
||||
await projectDb.delete(id);
|
||||
return { success: true, data: undefined };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to delete project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by tag
|
||||
*/
|
||||
async getProjectsByTag(tag: string): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getByTag(tag);
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to search projects by tag'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by author
|
||||
*/
|
||||
async getProjectsByAuthor(author: string): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getByAuthor(author);
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to search projects by author'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a project to a shareable URL
|
||||
*/
|
||||
async exportProjectToUrl(id: string, baseUrl?: string): Promise<Result<string>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const url = projectToShareUrl(project, baseUrl);
|
||||
|
||||
return { success: true, data: url };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to export project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a project to compressed data (for copying to clipboard, etc.)
|
||||
*/
|
||||
async exportProjectToCompressed(id: string): Promise<Result<string>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const compressed = compressProject(project);
|
||||
|
||||
return { success: true, data: compressed.data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to export project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a project from a URL
|
||||
*/
|
||||
async importProjectFromUrl(url: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = projectFromShareUrl(url);
|
||||
|
||||
// Generate a new ID and reset timestamps
|
||||
const now = getCurrentTimestamp();
|
||||
const importedProject: CsoundProject = {
|
||||
...project,
|
||||
id: generateId(),
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
title: `${project.title} (imported)`,
|
||||
};
|
||||
|
||||
await projectDb.put(importedProject);
|
||||
|
||||
return { success: true, data: importedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to import project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a project from compressed data
|
||||
*/
|
||||
async importProjectFromCompressed(compressedData: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = decompressProject({
|
||||
data: compressedData,
|
||||
version: 1,
|
||||
});
|
||||
|
||||
// Generate a new ID and reset timestamps
|
||||
const now = getCurrentTimestamp();
|
||||
const importedProject: CsoundProject = {
|
||||
...project,
|
||||
id: generateId(),
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
title: `${project.title} (imported)`,
|
||||
};
|
||||
|
||||
await projectDb.put(importedProject);
|
||||
|
||||
return { success: true, data: importedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to import project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicate a project
|
||||
*/
|
||||
async duplicateProject(id: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const originalProject = await projectDb.get(id);
|
||||
|
||||
if (!originalProject) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const now = getCurrentTimestamp();
|
||||
const duplicatedProject: CsoundProject = {
|
||||
...originalProject,
|
||||
id: generateId(),
|
||||
title: `${originalProject.title} (copy)`,
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
};
|
||||
|
||||
await projectDb.put(duplicatedProject);
|
||||
|
||||
return { success: true, data: duplicatedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to duplicate project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all projects (use with caution!)
|
||||
*/
|
||||
async clearAllProjects(): Promise<Result<void>> {
|
||||
try {
|
||||
await projectDb.clear();
|
||||
return { success: true, data: undefined };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to clear projects'),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const projectManager = new ProjectManager();
|
||||
70
src/lib/project-system/types.ts
Normal file
70
src/lib/project-system/types.ts
Normal file
@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Core data structure for a Csound project
|
||||
*/
|
||||
export interface CsoundProject {
|
||||
/** Unique identifier for the project */
|
||||
id: string;
|
||||
|
||||
/** User-defined project title */
|
||||
title: string;
|
||||
|
||||
/** Project author name */
|
||||
author: string;
|
||||
|
||||
/** Date when the project was created (ISO string) */
|
||||
dateCreated: string;
|
||||
|
||||
/** Date when the project was last modified (ISO string) */
|
||||
dateModified: string;
|
||||
|
||||
/** Number of times the project has been saved */
|
||||
saveCount: number;
|
||||
|
||||
/** The Csound code content */
|
||||
content: string;
|
||||
|
||||
/** Optional tags for categorization */
|
||||
tags: string[];
|
||||
|
||||
/** Csound version used to create this project */
|
||||
csoundVersion: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for creating a new project (omits auto-generated fields)
|
||||
*/
|
||||
export interface CreateProjectData {
|
||||
title: string;
|
||||
author: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for updating an existing project
|
||||
*/
|
||||
export interface UpdateProjectData {
|
||||
id: string;
|
||||
title?: string;
|
||||
author?: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Compressed project data for import/export via links
|
||||
*/
|
||||
export interface CompressedProject {
|
||||
/** Base64-encoded compressed project data */
|
||||
data: string;
|
||||
|
||||
/** Version of the compression format (for future compatibility) */
|
||||
version: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result type for async operations
|
||||
*/
|
||||
export type Result<T, E = Error> =
|
||||
| { success: true; data: T }
|
||||
| { success: false; error: E };
|
||||
Reference in New Issue
Block a user