about summary refs log tree commit diff stats
path: root/build.js
blob: 2f3f77199eeeb5b14f0f32cfab16a9292553387c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/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(); });

}