-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ts
More file actions
370 lines (292 loc) · 10.3 KB
/
Copy pathbuild.ts
File metadata and controls
370 lines (292 loc) · 10.3 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* Torchfinder build script (Deno)
*
* Steps:
* 0. Bundle src/app.ts + src/worker.ts -> staging/js/ via esbuild.
* 1. Fetch torchfinder-dataset.jsonl from torchfinder-data.
* 2. Generate feed.xml (RSS 2.0) from the data.
* 3. Cache-bust assets (SHA-256, first 8 hex chars).
* 4. Assemble the staging/ deploy payload.
*
* Exit code is nonzero on any failure; a bad build never writes partial output.
*/
import * as esbuild from "esbuild";
import { denoPlugins } from "@luca/esbuild-deno-loader";
const DATA_RELEASE_URL =
"https://github.com/Lodes-and-Lanterns/torchfinder-data/releases/latest/download/torchfinder-dataset.jsonl";
const SITE_URL = "https://torchfinder.lodesandlanterns.com";
const FEED_ITEM_LIMIT = 50;
// UTILITIES
////////////
function xmlEscape(str: string): string {
return String(str ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
async function sha256hex(content: string | Uint8Array): Promise<string> {
const data = typeof content === "string"
? new TextEncoder().encode(content)
: content;
const buf = await crypto.subtle.digest("SHA-256", data as BufferSource);
return Array.from(new Uint8Array(buf)).map((b) =>
b.toString(16).padStart(2, "0")
).join("");
}
async function readDir(dir: string, ext: string): Promise<string[]> {
const names: string[] = [];
for await (const entry of Deno.readDir(dir)) {
if (entry.isFile && entry.name.endsWith(ext)) names.push(entry.name);
}
return names.sort();
}
// RSS FEED
///////////
interface Adventure {
id: string;
title?: string;
desc?: string;
authors?: string[];
categories?: string[];
date?: string;
links?: { title: string; url: string; language: string; type?: string }[];
[key: string]: unknown;
}
function generateFeed(adventures: Adventure[]): string {
const sorted = [...adventures]
.filter((a) => a.date)
.sort((a, b) => (b.date ?? "").localeCompare(a.date ?? ""))
.slice(0, FEED_ITEM_LIMIT);
const buildDate = new Date().toUTCString();
const items = sorted.map((entry) => {
const description = entry.desc ??
[(entry.categories ?? []).join(", "), (entry.authors ?? []).join(", ")]
.filter(Boolean)
.join(" by ");
const authorStr = (entry.authors ?? []).join(", ");
const link = `${SITE_URL}/?id=${encodeURIComponent(entry.id)}`;
const pubDate = entry.date
? new Date(entry.date + "T00:00:00Z").toUTCString()
: "";
return ` <item>
<title>${xmlEscape(entry.title ?? "")} -- Lodes & Lanterns</title>
<description>${xmlEscape(description)}</description>
<author>${xmlEscape(authorStr)}</author>
<link>${xmlEscape(link)}</link>
<guid isPermaLink="true">${xmlEscape(link)}</guid>
${pubDate ? `<pubDate>${pubDate}</pubDate>` : ""}
</item>`;
});
return `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Torchfinder -- Lodes & Lanterns</title>
<description>Content lookup for Shadowdark. Find adventures, supplements, and zines.</description>
<link>${SITE_URL}</link>
<language>en</language>
<lastBuildDate>${buildDate}</lastBuildDate>
<atom:link href="${SITE_URL}/dist/feed.xml" rel="self" type="application/rss+xml" xmlns:atom="http://www.w3.org/2005/Atom"/>
${items.join("\n")}
</channel>
</rss>
`;
}
// MAIN
///////
console.log("Torchfinder build starting...");
// STEP 0: BUNDLE
/////////////////
console.log("Bundling src/app.ts + src/worker.ts -> staging/js/...");
await Deno.mkdir("staging/js", { recursive: true });
await esbuild.build({
entryPoints: ["src/app.ts", "src/worker.ts"],
bundle: true,
plugins: [...denoPlugins()],
outdir: "staging/js",
format: "esm",
platform: "browser",
target: "es2022",
sourcemap: false,
minify: false,
});
await esbuild.stop();
console.log("Bundle complete.");
// STEP 1: FETCH DATASET
////////////////////////
console.log(`Fetching ${DATA_RELEASE_URL}`);
const dataResponse = await fetch(DATA_RELEASE_URL);
if (!dataResponse.ok) {
console.error(
`Failed to fetch torchfinder-dataset.jsonl: HTTP ${dataResponse.status}`,
);
Deno.exit(1);
}
const datasetJsonl = await dataResponse.text();
const adventures: Adventure[] = datasetJsonl
.split("\n")
.filter((l) => l.trim())
.map((l) => JSON.parse(l));
console.log(`Fetched ${adventures.length} entries.`);
// STEP 1(b): FETCH DATASET RELEASE DATE
let dataReleaseDate: string | null = null;
try {
const releaseResp = await fetch(
"https://api.github.com/repos/Lodes-and-Lanterns/torchfinder-data/releases/latest",
{ headers: { "Accept": "application/vnd.github+json" } },
);
if (releaseResp.ok) {
const release = await releaseResp.json();
dataReleaseDate = typeof release.published_at === "string"
? release.published_at.slice(0, 10)
: null;
console.log(`Data release date: ${dataReleaseDate ?? "unavailable"}`);
} else {
console.warn(
`GitHub API returned HTTP ${releaseResp.status}; skipping data date.`,
);
}
} catch (err) {
console.warn(`Could not fetch data release date: ${err}; skipping.`);
}
// STEP 2: GENERATE RSS FEED
////////////////////////////
console.log("Generating RSS feed...");
const feedXml = generateFeed(adventures);
// STEP 3: COMPUTE ASSET HASHES
///////////////////////////////
console.log("Computing asset hashes...");
// Hash the dataset so its URL is versioned independently of JS/CSS
const dataHash = (await sha256hex(datasetJsonl)).slice(0, 8);
console.log(`dataset hash: ${dataHash}`);
// Hash bundle outputs combined with dataHash
const jsFiles = await readDir("staging/js", ".js");
const jsContents = await Promise.all(
jsFiles.map((f) => Deno.readTextFile(`staging/js/${f}`)),
);
const appHash = (await sha256hex(jsContents.join("\n") + dataHash)).slice(
0,
8,
);
console.log(`staging/js/ hash: ${appHash}`);
// Post-process bundle: inject versioned dataset URL and worker URL
let appJs = await Deno.readTextFile("staging/js/app.js");
appJs = appJs.replace(
/"\/dist\/torchfinder-dataset\.jsonl"/g,
`"/dist/torchfinder-dataset.jsonl?v=${dataHash}"`,
);
appJs = appJs.replace(
/new URL\("worker\.js",\s*import\.meta\.url\)/g,
`new URL("worker.js?v=${appHash}", import.meta.url)`,
);
await Deno.writeTextFile("staging/js/app.js", appJs);
// Hash CSS
const styleFiles = await readDir("styles", ".css");
const styleContents = await Promise.all(
styleFiles.map((f) => Deno.readTextFile(`styles/${f}`)),
);
const commonWebCssFiles = await readDir("common-web", ".css");
const commonWebCssContents = await Promise.all(
commonWebCssFiles.map((f) => Deno.readTextFile(`common-web/${f}`)),
);
const styleHash = (await sha256hex(
[...commonWebCssContents, ...styleContents].join("\n"),
)).slice(0, 8);
console.log(`styles/ hash: ${styleHash}`);
// Rewrite index.html
let indexHtml = await Deno.readTextFile("index.html");
indexHtml = indexHtml.replace(
/(<script\b[^>]*\bsrc=")js\/([^"?]+\.js)(")/g,
`$1js/$2?v=${appHash}$3`,
);
indexHtml = indexHtml.replace(
/(<link\b[^>]*\bhref=")styles\/([^"?]+\.css)(")/g,
`$1styles/$2?v=${styleHash}$3`,
);
indexHtml = indexHtml.replace(
/(<link\b[^>]*\bhref=")common-web\/([^"?]+\.css)(")/g,
`$1common-web/$2?v=${styleHash}$3`,
);
let appDate = new Date().toISOString().slice(0, 10);
try {
const appCommitResp = await fetch(
"https://api.github.com/repos/Lodes-and-Lanterns/torchfinder/commits/main",
{ headers: { "Accept": "application/vnd.github+json" } },
);
if (appCommitResp.ok) {
const appCommit = await appCommitResp.json();
const commitDate = appCommit?.commit?.committer?.date;
if (typeof commitDate === "string") {
appDate = commitDate.slice(0, 10);
console.log(`App commit date: ${appDate}`);
} else {
console.warn("App commit date unavailable; using build date.");
}
} else {
console.warn(
`GitHub API returned HTTP ${appCommitResp.status}; using build date for app.`,
);
}
} catch (err) {
console.warn(`Could not fetch app commit date: ${err}; using build date.`);
}
const appLink =
`<a href="https://github.com/Lodes-and-Lanterns/torchfinder" target="_blank" rel="noopener">app</a>`;
const dataLink =
`<a href="https://github.com/Lodes-and-Lanterns/torchfinder-data" target="_blank" rel="noopener">data</a>`;
const timestampText = dataReleaseDate
? `Last updated ${appLink} on ${appDate}, ${dataLink} on ${dataReleaseDate}`
: `Last updated ${appLink} on ${appDate}`;
indexHtml = indexHtml.replace(
/<p id="footer-timestamps"><\/p>/,
`<p id="footer-timestamps">${timestampText}</p>`,
);
// STEP 4: ASSEMBLE staging/
////////////////////////////
console.log("Assembling staging/ directory...");
await Deno.writeTextFile("staging/index.html", indexHtml);
// Copy styles/ to staging/styles/
await Deno.mkdir("staging/styles", { recursive: true });
for (const name of styleFiles) {
let src = await Deno.readTextFile(`styles/${name}`);
// Version the common-web @import so tokens.css cache busts with style hash
src = src.replace(
/@import '(\.\.\/common-web\/[^'?]+\.css)'/g,
`@import '$1?v=${styleHash}'`,
);
await Deno.writeTextFile(`staging/styles/${name}`, src);
}
console.log(`Copied ${styleFiles.length} CSS files.`);
// Copy common-web/ to staging/common-web/
await Deno.mkdir("staging/common-web", { recursive: true });
for (const name of commonWebCssFiles) {
await Deno.copyFile(`common-web/${name}`, `staging/common-web/${name}`);
}
for (const name of ["theme.js", "favicon.png", "apple-touch-icon.png"]) {
try {
await Deno.copyFile(`common-web/${name}`, `staging/common-web/${name}`);
} catch {
console.warn(`common-web/${name} not found, skipping.`);
}
}
console.log("Copied common-web assets.");
// Write dataset and feed to staging/dist/
await Deno.mkdir("staging/dist", { recursive: true });
await Deno.writeTextFile(
"staging/dist/torchfinder-dataset.jsonl",
datasetJsonl,
);
await Deno.writeTextFile("staging/dist/feed.xml", feedXml);
console.log("Wrote dataset and feed.");
// Copy robots.txt
try {
await Deno.copyFile("robots.txt", "staging/robots.txt");
console.log("Copied robots.txt.");
} catch { /* optional */ }
// Copy CNAME if present
try {
await Deno.copyFile("CNAME", "staging/CNAME");
console.log("Copied CNAME.");
} catch { /* optional */ }
console.log("Build complete. Output in staging/");