Repository navigation
Expand file tree
/
Copy pathbuild.mjs
More file actions
310 lines (291 loc) · 17.1 KB
/
Copy pathbuild.mjs
File metadata and controls
310 lines (291 loc) · 17.1 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
// Prism build — concatenates all source files in load order, then runs
// esbuild to transform JSX and minify into dist/bundle.js.
// No module bundling needed: files share the global scope via window.X.
import * as esbuild from 'esbuild';
import { readFileSync, writeFileSync, unlinkSync, mkdirSync, rmSync, copyFileSync, readdirSync } from 'fs';
import { createHash } from 'crypto';
import { publishedPages, renderPage } from './content/pages.mjs';
import { sourceFiles, portalFiles } from './build-files.mjs';
// ── Advisor help guides (round 23) ─────────────────────────────────────
// Authored ONCE in docs/guides/*.md, rendered TWICE from this single source:
// 1. embedded into the ADVISOR bundle as window.__pxGuides (the in-app
// searchable Help drawer in app.jsx), and
// 2. a print-styled /guides/<slug>/ page (browser Print → searchable PDF,
// the advisor-requested training artifact).
// The markdown subset below is deliberately small (h1-h3, bold/em/code,
// lists with wrapped lines, tables, paragraphs) - keep the guides within it.
function mdToHtml(md) {
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const inline = (s) => s
.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
.replace(/`([^`]+)`/g, '<code>$1</code>');
const out = [];
let list = null, table = null, para = [];
const flushPara = () => { if (para.length) { out.push(`<p>${inline(para.join(' '))}</p>`); para = []; } };
const flushList = () => { if (list) { out.push(`</${list}>`); list = null; } };
const flushTable = () => {
if (!table) return;
const [head, ...rows] = table;
out.push('<table><thead><tr>' + head.map(c => `<th>${inline(c)}</th>`).join('')
+ '</tr></thead><tbody>'
+ rows.map(r => '<tr>' + r.map(c => `<td>${inline(c)}</td>`).join('') + '</tr>').join('')
+ '</tbody></table>');
table = null;
};
for (const raw of esc(md).split(/\r?\n/)) {
const t = raw.trim();
if (!t) { flushPara(); flushList(); flushTable(); continue; }
const h = t.match(/^(#{1,3}) (.+)$/);
if (h) { flushPara(); flushList(); flushTable(); out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`); continue; }
if (/^\|.*\|$/.test(t)) {
flushPara(); flushList();
const cells = t.slice(1, -1).split('|').map(c => c.trim());
if (!cells.every(c => /^-{3,}$/.test(c))) (table ||= []).push(cells);
continue;
}
const li = t.match(/^(?:[-*]|\d+\.) (.+)$/);
if (li) {
flushPara(); flushTable();
const want = /^\d+\./.test(t) ? 'ol' : 'ul';
if (list !== want) { flushList(); out.push(`<${want}>`); list = want; }
out.push(`<li>${inline(li[1])}</li>`);
continue;
}
if (list && /^\s+\S/.test(raw)) { // wrapped list-item line
out[out.length - 1] = out[out.length - 1].replace(/<\/li>$/, ` ${inline(t)}</li>`);
continue;
}
flushList(); flushTable();
para.push(t);
}
flushPara(); flushList(); flushTable();
return out.join('\n');
}
const guides = readdirSync('docs/guides').filter(f => f.endsWith('.md')).sort().map(f => {
const raw = readFileSync(`docs/guides/${f}`, 'utf8');
// Optional `<!-- audience: client -->` marker (default advisor) sets the
// printable page's bar label so a client-facing handout doesn't read
// "Advisor guide". Stripped before mdToHtml so it never renders as text.
const audience = (raw.match(/^<!--\s*audience:\s*(\w+)\s*-->\s*$/im) || [])[1] || 'advisor';
const md = raw.replace(/^<!--\s*audience:\s*\w+\s*-->\r?\n?/im, '');
const title = ((md.match(/^# (.+)$/m) || [])[1] || f.replace(/\.md$/, '')).trim();
return { slug: f.replace(/\.md$/, ''), title, audience, md, html: mdToHtml(md) };
});
// No <script> on guide pages on purpose: inline handlers are CSP-blocked and a
// hashed print button isn't worth the moving part - the page tells the reader
// to use the browser's own Print for the PDF.
const renderGuidePage = (g) => `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>${g.title.replace(/</g, '<')} | Prism Guide</title>
<style>
body { font: 15px/1.65 Georgia, 'Times New Roman', serif; color: #1d2a3a; max-width: 760px; margin: 40px auto 80px; padding: 0 20px; }
h1 { font-size: 28px; line-height: 1.25; }
h2 { font-size: 19px; margin-top: 34px; border-bottom: 1px solid #d8dee6; padding-bottom: 6px; }
table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
th, td { text-align: left; border: 1px solid #d8dee6; padding: 6px 10px; }
code { font-family: Consolas, monospace; font-size: .9em; background: #f0f2f5; padding: 1px 5px; border-radius: 4px; }
.pxg-bar { display: flex; justify-content: space-between; align-items: center; font: 12px/1.4 system-ui, sans-serif; color: #5b6b7e; border-bottom: 2px solid #1d2a3a; padding-bottom: 10px; margin-bottom: 8px; }
@media print { .pxg-hint { display: none; } }
</style></head>
<body>
<div class="pxg-bar"><span>Prism | ${g.audience === 'client' ? 'Client' : 'Advisor'} guide</span><span class="pxg-hint">Use your browser's Print to save this as a searchable PDF</span></div>
${g.html}
</body></html>`;
const guidesJs = `// Generated by build.mjs from docs/guides/*.md - advisor bundle only.\nwindow.__pxGuides = ${JSON.stringify(guides)};`;
// Two entries share one source pool (concatenated, not module-bundled): the
// advisor/admin app and the slim client portal. Each gets its own temp entry.
const entries = [
{ files: sourceFiles, tmp: 'src/_entry.jsx', out: 'dist/bundle.js' },
{ files: portalFiles, tmp: 'src/_entry-portal.jsx', out: 'dist/portal.js' },
];
for (const e of entries) {
// Advisor bundle additionally embeds the help guides (Help drawer source).
const prefix = e.out === 'dist/bundle.js' ? guidesJs + '\n\n' : '';
writeFileSync(e.tmp, prefix + e.files.map(f => readFileSync(f, 'utf8')).join('\n\n'));
}
try {
mkdirSync('dist', { recursive: true });
for (const e of entries) {
await esbuild.build({
entryPoints: [e.tmp],
bundle: false,
outfile: e.out,
jsxFactory: 'React.createElement',
jsxFragment: 'React.Fragment',
minify: true,
});
console.log(`✓ ${e.out} built`);
}
// ── Assemble a clean deploy directory (_site) ──────────────────────
// Hosts like Cloudflare upload the *entire* output dir, so we copy ONLY
// the runtime files here — never node_modules, migrations, or .jsx sources.
rmSync('_site', { recursive: true, force: true });
mkdirSync('_site/dist', { recursive: true });
mkdirSync('_site/src', { recursive: true });
// Minify the hand-authored CSS (esbuild, same engine as the JS) → the served
// stylesheet is the minified output, never the source. Hashing the minified
// bytes (below) keeps the cache-bust correct even if only the minifier changes.
const minifyCss = async (file) =>
(await esbuild.transform(readFileSync(file, 'utf8'), { loader: 'css', minify: true })).code;
const stylesCssMin = await minifyCss('src/styles.css');
const printCssMin = await minifyCss('src/print.css');
// Content hash over all cache-busted assets → any change to any of them
// refreshes the lot (CSS-only edits bust too, not just JS).
const hash = createHash('sha256')
.update(readFileSync('dist/bundle.js'))
.update(readFileSync('dist/portal.js'))
.update(stylesCssMin)
.update(printCssMin)
.update(readFileSync('src/supabase-client.js'))
.update(readFileSync('src/brand-boot.js'))
.digest('hex').slice(0, 8);
const bust = (html) => readFileSync(html, 'utf8')
.replace(/dist\/bundle\.js(\?v=[^"']*)?/g, `dist/bundle.js?v=${hash}`)
.replace(/dist\/portal\.js(\?v=[^"']*)?/g, `dist/portal.js?v=${hash}`)
.replace(/src\/styles\.css(\?v=[^"']*)?/g, `src/styles.css?v=${hash}`)
.replace(/src\/supabase-client\.js(\?v=[^"']*)?/g, `src/supabase-client.js?v=${hash}`)
.replace(/src\/brand-boot\.js(\?v=[^"']*)?/g, `src/brand-boot.js?v=${hash}`);
// Routing: marketing (landing.html) is served at / ; the app (index.html) lives at /app ;
// the slim client portal (portal.html → dist/portal.js) lives at /portal.
// login/signup stay at the root. Asset refs are absolute (/dist, /src, /vendor)
// so they resolve correctly from any path.
mkdirSync('_site/app', { recursive: true });
mkdirSync('_site/portal', { recursive: true });
writeFileSync('_site/index.html', bust('landing.html'));
writeFileSync('_site/app/index.html', bust('index.html'));
writeFileSync('_site/portal/index.html', bust('portal.html'));
writeFileSync('_site/login.html', bust('login.html'));
writeFileSync('_site/signup.html', bust('signup.html'));
// OAuth callback page — one source file served at both provider redirect
// URIs (the page reads the provider from its own path). Registered in
// Google Cloud / Azure as https://prismaw.com/oauth/{google|microsoft}/callback.
for (const prov of ['google', 'microsoft']) {
mkdirSync(`_site/oauth/${prov}/callback`, { recursive: true });
writeFileSync(`_site/oauth/${prov}/callback/index.html`, bust('oauth-callback.html'));
}
// Static legal + security pages (no bundle refs — plain copy).
for (const p of ['privacy.html', 'terms.html', 'dpa.html', 'security.html']) {
copyFileSync(p, `_site/${p}`);
}
copyFileSync('dist/bundle.js', '_site/dist/bundle.js');
copyFileSync('dist/portal.js', '_site/dist/portal.js');
writeFileSync('_site/src/styles.css', stylesCssMin);
writeFileSync('_site/src/print.css', printCssMin);
copyFileSync('src/supabase-client.js', '_site/src/supabase-client.js');
copyFileSync('src/brand-boot.js', '_site/src/brand-boot.js');
// PWA (client portal): service worker at the root (its scope must cover
// /portal/), manifest under /portal, icons under /icons. The SW URL is
// deliberately NOT cache-busted — browsers byte-compare the registered URL
// on each visit, and a ?v= would orphan old registrations.
mkdirSync('_site/icons', { recursive: true });
copyFileSync('src/portal-sw.js', '_site/portal-sw.js');
copyFileSync('portal-manifest.webmanifest', '_site/portal/manifest.webmanifest');
copyFileSync('icons/portal-192.png', '_site/icons/portal-192.png');
copyFileSync('icons/portal-512.png', '_site/icons/portal-512.png');
// Self-hosted libs (no runtime CDN dependency except Plaid, which requires its CDN)
mkdirSync('_site/vendor', { recursive: true });
for (const v of ['react.production.min.js', 'react-dom.production.min.js', 'supabase.js']) {
copyFileSync(`vendor/${v}`, `_site/vendor/${v}`);
}
// Security headers (Cloudflare/Netlify read _headers from the deploy root).
//
// CSP script-src: NO 'unsafe-inline'. React + supabase-js are self-hosted ('self');
// every executable inline <script> (landing/login/signup + the app's theme-init)
// is allow-listed by its SHA-256 hash, computed here over the exact served bytes.
// Plaid's CDN stays host-allow-listed (it auto-updates its "stable" URL, so SRI
// would break Link on their releases — host-allow-list is the correct control).
// style-src: NO 'unsafe-inline' (C5). Every served page that carries an inline
// <style> block is allow-listed by the SHA-256 of its exact bytes — the same
// mechanism as scripts. Inline style="" ATTRIBUTES were all migrated to classes
// (none remain in any served page), so style-src-attr needs no allowance. React's
// style={{}} props set properties via the CSSOM, which CSP does NOT gate, so the
// app's dynamic inline styles keep working. The print report (store.jsx) links a
// same-origin /src/print.css, which 'self' covers.
const inlineHashes = new Set();
for (const html of [bust('landing.html'), bust('index.html'), bust('portal.html'), bust('login.html'), bust('signup.html'), bust('oauth-callback.html')]) {
const re = /<script>([\s\S]*?)<\/script>/g; // bare <script> only — skips src= and application/ld+json
let m;
while ((m = re.exec(html)) !== null) {
// The HTML parser normalizes CRLF/CR → LF before the browser hashes the text,
// so hash the LF-normalized bytes (no-op on LF checkouts, correct on CRLF ones).
inlineHashes.add(`'sha256-${createHash('sha256').update(m[1].replace(/\r\n?/g, '\n'), 'utf8').digest('base64')}'`);
}
}
// Cloudflare auto-injects its Web Analytics beacon (static.cloudflareinsights.com)
// when the zone has Web Analytics enabled. Allow-list the beacon host (and its
// RUM collection endpoint in connect-src below) so it isn't blocked by our
// host-locked script-src. The beacon is host-allow-listed, not hashed — Cloudflare
// controls and versions that script, so a pinned hash would break on their updates.
const scriptSrc = `'self' ${[...inlineHashes].join(' ')} https://cdn.plaid.com https://static.cloudflareinsights.com`.replace(/\s+/g, ' ');
// ── B2B content/intent pages (static, crawlable) — rendered below, hashed here ──
const livePages = publishedPages();
// Inline <style> hashes over every served page that has a <style> block.
const styleHashes = new Set();
const styleHostHtml = [
bust('landing.html'), bust('login.html'), bust('signup.html'), bust('oauth-callback.html'),
readFileSync('privacy.html', 'utf8'), readFileSync('terms.html', 'utf8'),
readFileSync('dpa.html', 'utf8'), readFileSync('security.html', 'utf8'),
...livePages.map(renderPage),
...guides.map(renderGuidePage), // printable advisor guides carry an inline <style>
];
for (const html of styleHostHtml) {
const re = /<style>([\s\S]*?)<\/style>/g; // bare <style> only
let m;
while ((m = re.exec(html)) !== null) {
styleHashes.add(`'sha256-${createHash('sha256').update(m[1].replace(/\r\n?/g, '\n'), 'utf8').digest('base64')}'`);
}
}
const styleSrc = `'self' ${[...styleHashes].join(' ')} https://fonts.googleapis.com`.replace(/\s+/g, ' ');
const SB = 'https://phabxcijbbphfxvjedfj.supabase.co';
writeFileSync('_site/_headers', `/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Permissions-Policy: geolocation=(), microphone=(), camera=()
Content-Security-Policy: default-src 'self'; script-src ${scriptSrc}; style-src ${styleSrc}; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self' ${SB} wss://phabxcijbbphfxvjedfj.supabase.co https://cloudflareinsights.com; frame-src https://cdn.plaid.com https://*.plaid.com; base-uri 'self'; frame-ancestors 'none'; form-action 'self'; object-src 'none'
`);
// ── SEO: robots, sitemap, share image ──────────────────────────────
for (const p of livePages) {
mkdirSync(`_site/${p.slug}`, { recursive: true });
writeFileSync(`_site/${p.slug}/index.html`, renderPage(p));
}
console.log(`✓ ${livePages.length} content pages rendered (live by publishAt date)`);
// Advisor guides - printable, searchable-PDF artifacts of docs/guides/*.md
// (the same source embedded in the advisor bundle for the Help drawer).
for (const g of guides) {
mkdirSync(`_site/guides/${g.slug}`, { recursive: true });
writeFileSync(`_site/guides/${g.slug}/index.html`, renderGuidePage(g));
}
console.log(`✓ ${guides.length} advisor guide page(s) rendered`);
// ── SEO: robots, sitemap, share image ──────────────────────────────
// The app at /app carries a noindex meta tag, so it's kept crawlable here (a Disallow
// would prevent Google from reading the noindex, risking a URL-only index entry).
writeFileSync('_site/robots.txt', `User-agent: *
Allow: /
Sitemap: https://prismaw.com/sitemap.xml
`);
const today = new Date().toISOString().slice(0, 10);
const urls = [
{ loc: 'https://prismaw.com/', priority: '1.0', freq: 'weekly' },
{ loc: 'https://prismaw.com/signup.html', priority: '0.7', freq: 'monthly' },
...livePages.map(p => ({ loc: `https://prismaw.com/${p.slug}/`, priority: '0.8', freq: 'monthly' })),
{ loc: 'https://prismaw.com/security.html', priority: '0.5', freq: 'monthly' },
{ loc: 'https://prismaw.com/privacy.html', priority: '0.3', freq: 'yearly' },
{ loc: 'https://prismaw.com/terms.html', priority: '0.3', freq: 'yearly' },
{ loc: 'https://prismaw.com/dpa.html', priority: '0.3', freq: 'yearly' },
];
writeFileSync('_site/sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map(u => ` <url><loc>${u.loc}</loc><lastmod>${today}</lastmod><changefreq>${u.freq}</changefreq><priority>${u.priority}</priority></url>`).join('\n')}
</urlset>
`);
try { copyFileSync('og-image.png', '_site/og-image.png'); }
catch { console.warn('! og-image.png missing - run the OG image generator'); }
console.log('✓ _site/ assembled for static hosting');
} finally {
for (const e of entries) { try { unlinkSync(e.tmp); } catch {} }
}