|
| 1 | +// Low-level wrapper around the File System Access API plus persistence of the |
| 2 | +// chosen directory handle and the "last-synced" manifest. This module knows |
| 3 | +// nothing about ProjectDoc — the diff/apply logic lives in localFolderSync.ts. |
| 4 | +// |
| 5 | +// The File System Access API is only available in Chromium-based browsers, so |
| 6 | +// every entry point is gated behind isSupported() by the callers. The DOM lib |
| 7 | +// does not reliably ship these types, so handles are typed loosely as `any`. |
| 8 | + |
| 9 | +import { Dexie } from "dexie"; |
| 10 | + |
| 11 | +/** A FileSystemDirectoryHandle (typed loosely; see file header). */ |
| 12 | +export type DirHandle = any; |
| 13 | + |
| 14 | +/** Whether the current browser supports the File System Access API. */ |
| 15 | +export function isSupported(): boolean { |
| 16 | + return typeof (window as any).showDirectoryPicker === "function"; |
| 17 | +} |
| 18 | + |
| 19 | +/** Prompt the user to pick a folder with read/write access. */ |
| 20 | +export async function pickFolder(): Promise<DirHandle> { |
| 21 | + return await (window as any).showDirectoryPicker({ mode: "readwrite" }); |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Ensure we have permission on a (possibly persisted) handle. Must be called |
| 26 | + * from a user gesture, because requestPermission() may show a prompt. |
| 27 | + */ |
| 28 | +export async function verifyPermission( |
| 29 | + handle: DirHandle, |
| 30 | + readWrite: boolean |
| 31 | +): Promise<boolean> { |
| 32 | + const opts = { mode: readWrite ? "readwrite" : "read" }; |
| 33 | + if ((await handle.queryPermission(opts)) === "granted") return true; |
| 34 | + if ((await handle.requestPermission(opts)) === "granted") return true; |
| 35 | + return false; |
| 36 | +} |
| 37 | + |
| 38 | +export interface LocalEntry { |
| 39 | + path: string; |
| 40 | + kind: "file" | "directory"; |
| 41 | +} |
| 42 | + |
| 43 | +/** Directory/file names that are never mirrored. */ |
| 44 | +const IGNORED = new Set([".git", "node_modules", ".DS_Store"]); |
| 45 | + |
| 46 | +/** Recursively list every file/folder below `handle` as POSIX-style paths. */ |
| 47 | +export async function readTree(handle: DirHandle): Promise<LocalEntry[]> { |
| 48 | + const out: LocalEntry[] = []; |
| 49 | + async function walk(dir: DirHandle, prefix: string) { |
| 50 | + for await (const entry of dir.values()) { |
| 51 | + if (IGNORED.has(entry.name)) continue; |
| 52 | + const path = prefix ? prefix + "/" + entry.name : entry.name; |
| 53 | + if (entry.kind === "directory") { |
| 54 | + out.push({ path, kind: "directory" }); |
| 55 | + await walk(entry, path); |
| 56 | + } else { |
| 57 | + out.push({ path, kind: "file" }); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + await walk(handle, ""); |
| 62 | + return out; |
| 63 | +} |
| 64 | + |
| 65 | +/** Resolve the directory handle that contains `path`, optionally creating it. */ |
| 66 | +async function parentDir( |
| 67 | + root: DirHandle, |
| 68 | + path: string, |
| 69 | + create: boolean |
| 70 | +): Promise<{ dir: DirHandle; name: string }> { |
| 71 | + const parts = path.split("/").filter(Boolean); |
| 72 | + const name = parts.pop()!; |
| 73 | + let dir = root; |
| 74 | + for (const part of parts) { |
| 75 | + dir = await dir.getDirectoryHandle(part, { create }); |
| 76 | + } |
| 77 | + return { dir, name }; |
| 78 | +} |
| 79 | + |
| 80 | +/** Read a file's bytes, or undefined if it does not exist. */ |
| 81 | +export async function readBytes( |
| 82 | + handle: DirHandle, |
| 83 | + path: string |
| 84 | +): Promise<Uint8Array | undefined> { |
| 85 | + try { |
| 86 | + const { dir, name } = await parentDir(handle, path, false); |
| 87 | + const fileHandle = await dir.getFileHandle(name, { create: false }); |
| 88 | + const file = await fileHandle.getFile(); |
| 89 | + return new Uint8Array(await file.arrayBuffer()); |
| 90 | + } catch { |
| 91 | + return undefined; |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +/** Write a file, creating any intermediate folders. */ |
| 96 | +export async function writeBytes( |
| 97 | + handle: DirHandle, |
| 98 | + path: string, |
| 99 | + bytes: Uint8Array |
| 100 | +): Promise<void> { |
| 101 | + const { dir, name } = await parentDir(handle, path, true); |
| 102 | + const fileHandle = await dir.getFileHandle(name, { create: true }); |
| 103 | + const writable = await fileHandle.createWritable(); |
| 104 | + await writable.write(bytes); |
| 105 | + await writable.close(); |
| 106 | +} |
| 107 | + |
| 108 | +/** Delete a file (or folder, recursively); silently ignores missing paths. */ |
| 109 | +export async function removePath(handle: DirHandle, path: string): Promise<void> { |
| 110 | + try { |
| 111 | + const { dir, name } = await parentDir(handle, path, false); |
| 112 | + await dir.removeEntry(name, { recursive: true }); |
| 113 | + } catch { |
| 114 | + /* already gone */ |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +/** Stable content hash (SHA-256, hex) used for the manifest and the diff. */ |
| 119 | +export async function hashBytes(bytes: Uint8Array): Promise<string> { |
| 120 | + const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource); |
| 121 | + return Array.from(new Uint8Array(digest)) |
| 122 | + .map((b) => b.toString(16).padStart(2, "0")) |
| 123 | + .join(""); |
| 124 | +} |
| 125 | + |
| 126 | +// ----------------------------------------------------------------------------- |
| 127 | +// persistence: directory handle + last-synced manifest, keyed by storageId |
| 128 | +// (separate Dexie database so the existing "LiveEditor" schema stays untouched) |
| 129 | +// ----------------------------------------------------------------------------- |
| 130 | + |
| 131 | +interface FolderRecord { |
| 132 | + id: string; |
| 133 | + handle: DirHandle; |
| 134 | + name: string; |
| 135 | + /** path -> content hash at the time of the last successful sync */ |
| 136 | + manifest: Record<string, string>; |
| 137 | +} |
| 138 | + |
| 139 | +const db = new Dexie("LiveEditorFS"); |
| 140 | +db.version(1).stores({ folders: "&id" }); |
| 141 | +const folders = () => db.table<FolderRecord, string>("folders"); |
| 142 | + |
| 143 | +export async function loadFolder(storageId: string): Promise<FolderRecord | undefined> { |
| 144 | + return await folders().get(storageId); |
| 145 | +} |
| 146 | + |
| 147 | +export async function loadHandle(storageId: string): Promise<DirHandle | undefined> { |
| 148 | + return (await loadFolder(storageId))?.handle; |
| 149 | +} |
| 150 | + |
| 151 | +/** Persist a freshly picked handle, preserving any existing manifest. */ |
| 152 | +export async function saveHandle(storageId: string, handle: DirHandle): Promise<void> { |
| 153 | + const existing = await loadFolder(storageId); |
| 154 | + await folders().put({ |
| 155 | + id: storageId, |
| 156 | + handle, |
| 157 | + name: handle.name, |
| 158 | + manifest: existing?.manifest || {}, |
| 159 | + }); |
| 160 | +} |
| 161 | + |
| 162 | +export async function clearHandle(storageId: string): Promise<void> { |
| 163 | + await folders().delete(storageId); |
| 164 | +} |
| 165 | + |
| 166 | +export async function loadManifest(storageId: string): Promise<Map<string, string>> { |
| 167 | + const record = await loadFolder(storageId); |
| 168 | + return new Map(Object.entries(record?.manifest || {})); |
| 169 | +} |
| 170 | + |
| 171 | +export async function saveManifest( |
| 172 | + storageId: string, |
| 173 | + manifest: Map<string, string> |
| 174 | +): Promise<void> { |
| 175 | + const record = await loadFolder(storageId); |
| 176 | + if (!record) return; |
| 177 | + record.manifest = Object.fromEntries(manifest); |
| 178 | + await folders().put(record); |
| 179 | +} |
0 commit comments