puffin-app/scripts/inject-sw-version.js
Matt 207fb261e6
Some checks failed
Build and Push Docker Images / docker (push) Failing after 2m13s
Fix build script to use ES modules instead of CommonJS
Convert inject-sw-version.js to ES module syntax since package.json has "type": "module". This fixes the build error in Docker.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 15:35:49 +01:00

57 lines
1.7 KiB
JavaScript

#!/usr/bin/env node
/**
* Inject build timestamp into service worker
* This script replaces __BUILD_TIMESTAMP__ with the current timestamp
* to force cache invalidation on new deployments
*/
import fs from 'fs';
import path from 'path';
import { execFileSync } from 'child_process';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const SW_SOURCE = path.join(__dirname, '..', 'public', 'sw.js');
try {
// Read the service worker file
let swContent = fs.readFileSync(SW_SOURCE, 'utf8');
// Check if placeholder exists
if (!swContent.includes('__BUILD_TIMESTAMP__')) {
console.log('⚠️ Service worker appears to be already processed');
process.exit(0);
}
// Generate version (use git commit hash if available, otherwise use timestamp)
let version;
try {
// Try to get git commit hash using safe execFileSync
version = execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore']
}).trim();
console.log(`📦 Using git commit hash: ${version}`);
} catch (error) {
// Fallback to timestamp
version = Date.now().toString();
console.log(`📦 Using timestamp: ${version}`);
}
// Replace the placeholder with the version
swContent = swContent.replace(/__BUILD_TIMESTAMP__/g, version);
// Write the updated service worker
fs.writeFileSync(SW_SOURCE, swContent);
console.log(`✅ Service worker version injected: ${version}`);
console.log(`📝 Updated: ${SW_SOURCE}`);
} catch (error) {
console.error('❌ Error injecting service worker version:', error);
process.exit(1);
}