#!/usr/bin/env node import * as esbuild from 'esbuild'; import { copyFileSync, readFileSync, unlinkSync } from 'fs'; import { writeFile } from 'fs/promises'; import { globSync } from 'glob'; import less from 'less'; import chokidar from 'chokidar'; import path from 'path'; import { execSync } from 'child_process'; function getBuildVersion() { try { const output = execSync('git --no-pager log --pretty=%ct-%h -n1 HEAD', { encoding: 'utf8' }).trim(); const [ts, shortHash] = output.split('-'); const commitTs = parseInt(ts, 10); const date = new Date(commitTs * 1000); const yy = date.getUTCFullYear().toString().slice(-2); const mm = String(date.getUTCMonth() + 1).padStart(2, '0'); return `v${yy}.${mm}-${shortHash}`; } catch { return 'v00.00-unknown'; } } const LIB_FILES = [ 'lib/bootstrap/v3/js/jquery.js', 'lib/bootstrap/v3/js/bootstrap.min.js', 'node_modules/jszip/dist/jszip.min.js', 'lib/epub.js/dist/epub.js', 'node_modules/localforage/dist/localforage.js', 'lib/jquery.mobile.custom.js', 'lib/hyphen/en-us.js', 'lib/hyphen/hyphen.js', 'lib/hyphen/ru.js', ]; // top level files const LESS_FILES = [ "css/app.less", "css/reader_iframe.less" ] const JS_FILES = [ 'src/http.ts', 'src/app.ts', 'src/reader.ts' ]; // Files that should be precached by the service worker // These are the actual output files produced by the build const CACHE_ASSETS = [ 'dist/app-libs.min.js', 'dist/app.min.js', 'dist/app.min.css', 'dist/reader_iframe.min.css', 'manifest.json', 'worker.js', 'offline.html', 'read.html', ]; async function buildLibs() { console.log('building libs...'); const content = LIB_FILES.map(f => readFileSync(f, 'utf8')).join('\n'); await esbuild.build({ stdin: { contents: content, resolveDir: process.cwd(), loader: 'js' }, bundle: false, minify: true, outfile: 'dist/app-libs.min.js', }); console.log('libs build done.'); } async function buildApp() { console.log('building app...'); const content = JS_FILES.map(f => readFileSync(f, 'utf8')).join('\n'); const CACHE_VERSION = `v${Date.now()}`; const BUILD_VERSION = getBuildVersion(); console.log(`build version: ${BUILD_VERSION}`); await esbuild.build({ stdin: { contents: content, resolveDir: process.cwd(), loader: 'ts' }, bundle: false, minify: true, outfile: 'dist/app.min.js', define: { 'BUILD_CACHE_VERSION': JSON.stringify(CACHE_VERSION), 'BUILD_VERSION': JSON.stringify(BUILD_VERSION), } }); console.log('creating timestamped js files...'); // remove stale timestamped files from previous builds const oldVersioned = globSync('dist/*_v[0-9]*'); for (const f of oldVersioned) { try { unlinkSync(f); } catch { /* ignore */ } } // also create suffixed filenames for our worker to determine proper replica (a pseudo-atomic build) const builtFiles = globSync('dist/**/*.js'); for (const file of builtFiles) { const newFileName = `${file}_${CACHE_VERSION}`; copyFileSync(file, newFileName); } console.log('building service worker...'); const workerContent = readFileSync("src/worker.ts"); // Use suffixed JS filenames in manifest (stripped by worker for cache keys) // worker.js itself is the service worker — not versioned, replaced atomically by deploy let MANIFEST_ASSETS = CACHE_ASSETS.map(asset => asset.endsWith('.js') && asset !== 'worker.js' ? `${asset}_${CACHE_VERSION}` : asset ); // Add fonts and images MANIFEST_ASSETS.push(...globSync('lib/fonts/*')); MANIFEST_ASSETS.push(...globSync('img/*.png')); // Add bootstrap fonts MANIFEST_ASSETS.push(...globSync('lib/bootstrap/v3/fonts/*')); // deduplicate MANIFEST_ASSETS = [...new Set(MANIFEST_ASSETS)]; await esbuild.build({ stdin: { contents: workerContent, resolveDir: process.cwd(), loader: 'ts' }, bundle: false, minify: true, outfile: 'worker.js', define: { 'BUILD_CACHE_VERSION': JSON.stringify(CACHE_VERSION), 'BUILD_MANIFEST_ASSETS': JSON.stringify(MANIFEST_ASSETS), 'BUILD_VERSION': JSON.stringify(BUILD_VERSION), } }); console.log('app build done.'); } async function buildCSSfile(file) { try { console.log(`building css file: ${file}...`); const source = readFileSync(file, 'utf-8'); const outputFile = "dist/" + path.basename(file.replace(/\.less$/, '.min.css')); const lessResult = await less.render(source, { paths: [path.dirname(file)], compress: true }); await writeFile(outputFile, lessResult.css); } catch (e) { console.warn(`css build failed for ${file}: `, e.message || e); } } async function buildCSS() { console.log('building css...'); await Promise.all(LESS_FILES.map((file) => buildCSSfile(file))); } async function build() { console.log('performing full build...'); await buildLibs(); await buildApp(); await buildCSS(); console.log('build done.'); } await build(); const isWatch = process.argv.includes('--watch') || process.argv.includes('-w'); if (isWatch) { console.log('watching for changes...'); chokidar.watch(LIB_FILES, { ignoreInitial: true }) .on('change', () => { buildLibs(); }); chokidar.watch(['src/**/*.js'], { ignoreInitial: true }) .on('change', () => { buildApp(); }); chokidar.watch(['css/**/*.less'], { ignoreInitial: true }) .on('change', () => { buildCSS(); }); }