import {
  toBuffer
} from "./chunk-J6MN42LG.js";

// runtime/subsystems/storage/storage.local-backend.ts
import {
  createReadStream,
  existsSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  unlinkSync,
  writeFileSync
} from "fs";
import { dirname, join, relative, resolve, sep } from "path";
import { Readable } from "stream";
var LocalStorageBackend = class {
  basePath;
  constructor(basePath = "./storage") {
    this.basePath = resolve(basePath);
  }
  async upload(key, data, contentType) {
    const filePath = this.resolvePath(key);
    mkdirSync(dirname(filePath), { recursive: true });
    const buffer = await toBuffer(data);
    writeFileSync(filePath, buffer);
    return key;
  }
  async download(key) {
    const filePath = this.resolvePath(key);
    if (!existsSync(filePath)) {
      throw new Error(`Storage: file not found: ${key}`);
    }
    return readFileSync(filePath);
  }
  async delete(key) {
    const filePath = this.resolvePath(key);
    if (!existsSync(filePath)) {
      throw new Error(`Storage: file not found: ${key}`);
    }
    unlinkSync(filePath);
  }
  async getUrl(key, _expiresInSeconds) {
    const filePath = this.resolvePath(key);
    if (!existsSync(filePath)) {
      throw new Error(`Storage: file not found: ${key}`);
    }
    return `file://${filePath}`;
  }
  async exists(key) {
    try {
      return existsSync(this.resolvePath(key));
    } catch {
      return false;
    }
  }
  async list(prefix) {
    const keys = this.listRecursive(this.basePath);
    if (prefix === void 0) return keys;
    return keys.filter((k) => k.startsWith(prefix));
  }
  async downloadStream(key) {
    const filePath = this.resolvePath(key);
    if (!existsSync(filePath)) {
      throw new Error(`Storage: file not found: ${key}`);
    }
    const nodeStream = createReadStream(filePath);
    return Readable.toWeb(nodeStream);
  }
  resolvePath(key) {
    const resolved = resolve(this.basePath, key);
    if (!resolved.startsWith(this.basePath + sep)) {
      throw new Error(`Invalid storage key (path traversal attempt): ${key}`);
    }
    return resolved;
  }
  /** Recursively list all files under dir, returning keys relative to basePath. */
  listRecursive(dir) {
    if (!existsSync(dir)) return [];
    const keys = [];
    for (const entry of readdirSync(dir, { withFileTypes: true })) {
      const full = join(dir, entry.name);
      if (entry.isDirectory()) {
        keys.push(...this.listRecursive(full));
      } else {
        keys.push(relative(this.basePath, full));
      }
    }
    return keys;
  }
};

export {
  LocalStorageBackend
};
//# sourceMappingURL=chunk-JWNHNUYL.js.map