Files
phx-frontend-plugin-webcomp…/scripts/copy-latest.mjs

63 lines
1.6 KiB
JavaScript

import { watch } from 'node:fs';
import { access, constants, copyFile, mkdir, readdir, unlink } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..');
const sourceDir = join(root, 'dist/phx-frontend-plugin-demo/browser');
const destDir = join(root, 'latest');
async function copyJsFiles() {
try {
await access(sourceDir, constants.F_OK);
await mkdir(destDir, { recursive: true });
const files = (await readdir(sourceDir)).filter((f) => f.endsWith('.js'));
for (const file of files) {
await copyFile(join(sourceDir, file), join(destDir, file));
}
const destFiles = (await readdir(destDir)).filter((f) => f.endsWith('.js'));
for (const file of destFiles) {
if (!files.includes(file)) {
await unlink(join(destDir, file));
}
}
console.log(`[latest] Copied ${files.length} JS file(s)`);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error('[latest] Copy failed:', err.message);
}
}
}
function watchJsFiles() {
let timeout;
const debouncedCopy = () => {
clearTimeout(timeout);
timeout = setTimeout(copyJsFiles, 100);
};
const tryWatch = () => {
access(sourceDir, constants.F_OK)
.then(() => {
copyJsFiles();
watch(sourceDir, debouncedCopy);
console.log('[latest] Watching for JS changes in dist');
})
.catch(() => setTimeout(tryWatch, 500));
};
tryWatch();
}
if (process.argv.includes('--watch')) {
watchJsFiles();
} else {
copyJsFiles();
}