|
| 1 | +import { readdir, readFile } from 'node:fs/promises'; |
| 2 | +import { join, relative } from 'node:path'; |
| 3 | + |
| 4 | +const STORAGE_ZONE = process.env.BUNNY_STORAGE_ZONE; |
| 5 | +const STORAGE_PASSWORD = process.env.BUNNY_STORAGE_PASSWORD; |
| 6 | +const API_KEY = process.env.BUNNY_API_KEY; |
| 7 | +const PULLZONE_URL = process.env.BUNNY_PULLZONE_URL; |
| 8 | +const STORAGE_URL = `https://storage.bunnycdn.com/${STORAGE_ZONE}`; |
| 9 | + |
| 10 | +const EXCLUDE = new Set(['node_modules', 'scripts', 'package.json', 'package-lock.json', 'README.md']); |
| 11 | + |
| 12 | +async function getFiles(dir) { |
| 13 | + const entries = await readdir(dir, { withFileTypes: true, recursive: true }); |
| 14 | + return entries |
| 15 | + .filter((e) => { |
| 16 | + if (!e.isFile()) return false; |
| 17 | + const rel = relative(dir, join(e.parentPath, e.name)); |
| 18 | + return !rel.split('/').some((part) => EXCLUDE.has(part)); |
| 19 | + }) |
| 20 | + .map((e) => join(e.parentPath, e.name)); |
| 21 | +} |
| 22 | + |
| 23 | +async function uploadFile(localPath, remotePath) { |
| 24 | + const content = await readFile(localPath); |
| 25 | + const res = await fetch(`${STORAGE_URL}/${remotePath}`, { |
| 26 | + method: 'PUT', |
| 27 | + headers: { AccessKey: STORAGE_PASSWORD, 'Content-Type': 'application/octet-stream' }, |
| 28 | + body: content, |
| 29 | + }); |
| 30 | + if (!res.ok) throw new Error(`Upload failed: ${remotePath} (${res.status})`); |
| 31 | + console.log(`✓ ${remotePath}`); |
| 32 | +} |
| 33 | + |
| 34 | +async function purgeCache() { |
| 35 | + const res = await fetch(`https://api.bunny.net/purge?url=${encodeURIComponent(`${PULLZONE_URL}/*`)}`, { |
| 36 | + method: 'POST', |
| 37 | + headers: { AccessKey: API_KEY }, |
| 38 | + }); |
| 39 | + if (!res.ok) { |
| 40 | + const text = await res.text(); |
| 41 | + throw new Error(`Purge failed: ${res.status} - ${text}`); |
| 42 | + } |
| 43 | + console.log('✓ Cache purged'); |
| 44 | +} |
| 45 | + |
| 46 | +async function deploy() { |
| 47 | + const files = await getFiles('.'); |
| 48 | + console.log(`Uploading ${files.length} files...`); |
| 49 | + |
| 50 | + for (const file of files) { |
| 51 | + const remotePath = relative('.', file); |
| 52 | + await uploadFile(file, remotePath); |
| 53 | + } |
| 54 | + |
| 55 | + await purgeCache(); |
| 56 | + console.log('Deploy complete!'); |
| 57 | +} |
| 58 | + |
| 59 | +deploy().catch((e) => { |
| 60 | + console.error(e); |
| 61 | + process.exit(1); |
| 62 | +}); |
0 commit comments