Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
466 lines (452 loc) · 21.4 KB
/
Copy pathvite.config.ts
File metadata and controls
466 lines (452 loc) · 21.4 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { writeFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { createCssVariablesTheme } from 'shiki'
import { defineConfig } from 'vite-plus'
import { voidPlugin } from 'void'
import { voidReact } from '@void/react/plugin'
import { voidMarkdown } from '@void/md/plugin'
import { changelogData } from './lib/changelog/plugin.ts'
import { shikiLightCssVars } from './lib/shiki-themes.ts'
import { convertFenceHighlightMeta } from './lib/md/fence-highlight.ts'
import { markCodeFilenames } from './lib/md/code-filename.ts'
import { transformPmTabs } from './lib/md/pm-tabs.ts'
import { sitemapPlugin } from './scripts/generate-sitemap.mjs'
import { ogImagePlugin } from './scripts/generate-og-images.mjs'
import { generateRss } from './scripts/generate-rss.mjs'
import { searchIndexPlugin } from './scripts/build-search-index.mjs'
import { lastmodPlugin } from './scripts/build-lastmod.mjs'
import { svgoInline } from './lib/svg/svgo-plugin.ts'
// Docs dark code theme. napi.rs / Nextra highlight code with Shiki's
// `css-variables` theme (signature: GREEN string literals #4bb74a), NOT
// github-dark (which renders strings BLUE). @void/md passes `shiki.themes`
// straight to createHighlighter/codeToHtml, both of which accept a theme
// OBJECT, so this css-variables theme becomes the dark half of the dual-theme
// output: every token emits `--shiki-dark:var(--shiki-token-…)`, and code.css's
// dark swap (`color:var(--shiki-dark)`) resolves them against the --shiki-token-*
// hexes defined in pages/theme.css. The LIGHT half is a matching css-variables
// theme (shikiLightCssVars, --shiki-light- prefix, lib/shiki-themes.ts) so light
// mode keeps napi.rs's GREEN strings too instead of github-light's blue. Mirrors
// the landing demo panel (scripts/build-demo-code.mjs + components/landing/live-demo.css).
const shikiDarkCssVars = createCssVariablesTheme({
name: 'css-variables',
variablePrefix: '--shiki-',
fontStyle: true,
})
// Project root, used to wire the `@/*` -> `./*` path alias (mirrors tsconfig
// compilerOptions.paths) so runtime imports like `@/lib/utils` /
// `@/components/ui/*` resolve under Vite the same way TypeScript resolves them.
const projectRoot = fileURLToPath(new URL('.', import.meta.url))
// Self-contained branded 404 page (inline styles, the only external asset is
// the favicon) emitted to dist/client/404.html by the napi-rs-404 plugin below.
// The worker's notFound handler serves it for unknown routes in EVERY locale,
// so it is English-only and `noindex`.
const NOT_FOUND_HTML = `<!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>404 — Page not found · NAPI-RS</title>
<link rel="icon" href="/img/favicon.png">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #111;
color: #e5e5e5;
font-family: Manrope, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
padding: 2rem;
}
main { max-width: 34rem; text-align: center; }
.wordmark {
font-weight: 800;
letter-spacing: 0.08em;
font-size: 0.9rem;
color: #4bb74a;
margin-bottom: 2.5rem;
}
.code {
font-size: 5rem;
font-weight: 800;
line-height: 1;
background: linear-gradient(135deg, #4bb74a, #2f80ed);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
h1 { font-size: 1.5rem; font-weight: 700; margin: 1rem 0 0.75rem; }
p { color: #a3a3a3; line-height: 1.6; margin-bottom: 2rem; }
.actions { display: flex; gap: 0.75rem; justify-content: center; flex-wrap: wrap; }
a.btn {
display: inline-block;
padding: 0.6rem 1.25rem;
border-radius: 0.5rem;
font-weight: 600;
font-size: 0.95rem;
text-decoration: none;
}
a.primary { background: #4bb74a; color: #0c0c0c; }
a.primary:hover { background: #5cc75b; }
a.ghost { border: 1px solid #333; color: #e5e5e5; }
a.ghost:hover { border-color: #4bb74a; color: #4bb74a; }
.hint { margin-top: 2.5rem; font-size: 0.85rem; color: #737373; }
.hint kbd {
border: 1px solid #333;
border-radius: 0.3rem;
padding: 0.1rem 0.4rem;
font-family: inherit;
background: #1a1a1a;
}
.hint a { color: #737373; }
</style>
</head>
<body>
<main>
<div class="wordmark">NAPI-RS</div>
<div class="code">404</div>
<h1>Page not found</h1>
<p>The page you are looking for does not exist or may have moved.
The documentation is the best place to start looking.</p>
<div class="actions">
<a class="btn primary" href="/docs/introduction/getting-started">Go to Docs</a>
<a class="btn ghost" href="/">Home</a>
<a class="btn ghost" href="https://github.com/napi-rs/napi-rs">GitHub</a>
</div>
<p class="hint">Tip: press <kbd>⌘K</kbd> anywhere on the site to search the docs.</p>
</main>
</body>
</html>
`
// Dev/preview cross-origin isolation. Three pages run the @napi-rs/image WASM
// transcoder, which needs SharedArrayBuffer + threads: the landing (`/`), the
// WebAssembly doc (`/docs/concepts/webassembly`), and the v3 announcement blog
// (`/blog/announce-v3`). `self.crossOriginIsolated` (the gate for SAB) is only
// true when the DOCUMENT carries BOTH Cross-Origin-Opener-Policy: same-origin
// AND Cross-Origin-Embedder-Policy: require-corp. The deployed worker sets these
// per-route via void.json `routing.headers`; `void dev` and `vite preview` do
// NOT replay those, so we stamp them here — but ONLY on those three document
// paths (the migration scoped COEP to the demo pages, not site-wide), so every
// other page stays non-isolated, matching production.
//
// CORP is set UNCONDITIONALLY (on every response, including non-demo pages). It
// is harmless on a non-isolated document, and it is REQUIRED on the demo pages'
// subresources: under COEP:require-corp the browser blocks every subresource the
// isolated page loads (the worker module, the nested wasi-worker, the .wasm, the
// sample image, the `.vite/deps` modules) unless each carries CORP. Those
// subresource requests have their own non-document URLs, so scoping COOP/COEP to
// document paths while keeping CORP everywhere is exactly what makes the demo run
// in dev/preview without leaking isolation onto unrelated pages.
const DUPLICATED_WASM_PKG =
'@napi-rs/image-wasm32-wasi/@napi-rs/image-wasm32-wasi/'
// Document paths whose response must be cross-origin isolated (COOP + COEP). The
// landing serves at `/` and `/en`; the two demo leaves serve at their canonical
// path AND every locale-prefixed variant that i18n fallback renders 200 (the
// `/en/*` variants 301-redirect to canonical, so they never serve a document and
// need no header). Matched on the pathname only (query/hash stripped). Mirrors
// the void.json `routing.headers` keys for the same paths.
function needsIsolation(url: string | undefined): boolean {
if (!url) return false
const pathname = url.split(/[?#]/, 1)[0]
if (pathname === '/' || pathname === '/en') return true
// Locale-tolerant match for the two demo leaves: `/`, `/en/`, `/cn/`, `/pt-BR/`
// prefixes all resolve to the same en document.
return (
/^\/(?:en\/|cn\/|pt-BR\/)?docs\/concepts\/webassembly\/?$/.test(pathname) ||
/^\/(?:en\/|cn\/|pt-BR\/)?blog\/announce-v3\/?$/.test(pathname)
)
}
function isolationMiddleware(
req: {
url?: string
headers?: Record<string, string | string[] | undefined>
},
res: { setHeader: (name: string, value: string) => void },
next: () => void,
) {
// CORP on every response (see note above): harmless on non-isolated pages,
// required on the demo pages' subresources.
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
// COOP + COEP ONLY on the demo document paths, so isolation is scoped and a
// non-demo page never becomes cross-origin isolated.
if (needsIsolation(req.url)) {
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
} else if (
// A dedicated/shared worker spawned BY a require-corp document is itself
// blocked unless ITS OWN top-level script response also carries
// COEP:require-corp (the worker must adopt a policy compatible with its
// owner). In production void.json stamps this via `/assets/*`; `void dev`
// (the worker is `components/transform-image/worker.ts?worker_file`) and
// `vite preview` (`/assets/worker-*.js`) replay neither, so the demo worker
// — and the nested @napi-rs `wasi-worker-browser` it spawns — load with an
// opaque ONERROR and the transcode silently hangs. `Sec-Fetch-Dest: worker`
// (or `sharedworker`) is the browser's signal for a worker top-level fetch
// and is the one discriminator that covers BOTH worker layers in BOTH dev
// and preview. COOP is intentionally NOT set: it is meaningless on a worker
// script and we must not broaden document isolation here.
req.headers?.['sec-fetch-dest'] === 'worker' ||
req.headers?.['sec-fetch-dest'] === 'sharedworker'
) {
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
}
// @napi-rs/image-wasm32-wasi spawns its own module worker via
// `new Worker(new URL('@napi-rs/image-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url))`.
// Under `vite dev` that bare-specifier resolves with the package dir doubled and 404s;
// collapse it. Production `vite build` bundles the worker, so this is serve-only.
if (req.url && req.url.includes(DUPLICATED_WASM_PKG)) {
req.url = req.url.replace(
DUPLICATED_WASM_PKG,
'@napi-rs/image-wasm32-wasi/',
)
}
next()
}
// Vitest drives this same config; the Void plugins register a custom "void_worker"
// Vite environment that the vite-plus test runner cannot introspect (ReferenceError:
// module is not defined). Our unit tests are pure-data and need none of the Void
// pipeline, so skip those plugins under Vitest.
const isVitest = !!process.env.VITEST
export default defineConfig({
// BOTH worker layers (our demo worker + the wasm package's nested wasi-worker) must be
// ES modules — the wasm browser build is a top-level-await ESM and the default 'iife'
// worker format cannot handle top-level await, which fails the build.
worker: { format: 'es' },
environments: { void_worker: { build: { sourcemap: false } } },
// Force the demo worker's deps into the optimizer's STARTUP pass. The worker
// (`components/transform-image/worker.ts`) statically imports `buffer` and
// dynamically imports `@napi-rs/image` (aliased below to the wasm build). The
// worker sits behind a `with { island: 'idle' }` boundary, so Vite's dep
// scanner never crawls into it at boot — both deps are otherwise discovered
// LATE, on the first transform click. That late discovery triggers a
// re-optimization which churns EVERY `.vite/deps/…?v=<hash>` URL; a
// worker-context dynamic import that 404s on the now-stale hash does NOT trip
// Vite's auto full-reload, so the transcode silently fails. Both must be
// listed — pinning only the codec still lets `buffer` leak in late and re-bump
// the codec's hash. Pre-including both pins their hashes from boot so the
// worker's imports always resolve. Dev/preview-only: `vite build` bundles the
// worker + wasm and never touches the optimizer.
optimizeDeps: {
include: ['@napi-rs/image', 'buffer'],
},
ssr: {
// `@waaark/luge` reads window/document/requestAnimationFrame at module load,
// so it crashes if it is evaluated during worker SSR. components/landing/luge.tsx
// only ever `import()`s it lazily inside a client effect, so it should never be
// pulled into the SSR graph — but bundle it (don't externalize) so that path is
// transformed through Vite and any stray CSS side-effects resolve correctly.
noExternal: ['@waaark/luge'],
},
resolve: {
// The browser build of @napi-rs/image is `@napi-rs/image-wasm32-wasi`. The public
// wrapper's `main` is the native loader that require()s a platform .node binary, which
// Vite/rolldown cannot parse. Alias straight to the wasm build everywhere Vite bundles.
// Array form so the `@/` alias is matched precisely (a bare `@` key would
// also swallow `@napi-rs/*` etc.). `@/` -> project root mirrors tsconfig
// `@/*`: `./*`, so runtime imports (`@/lib/utils`, `@/components/ui/*`)
// resolve under Vite exactly as TypeScript resolves them.
alias: [
{ find: '@napi-rs/image', replacement: '@napi-rs/image-wasm32-wasi' },
{ find: /^@\//, replacement: `${projectRoot.replace(/\/$/, '')}/` },
],
},
plugins: isVitest
? // ?svgo imports (build-time SVGO, lib/svg/svgo-plugin.ts) must still
// resolve if a component is ever pulled into a Vitest run.
[svgoInline()]
: [
// Build-time SVGO for `import … from './x.svg?svgo'` (inline SVG markup).
svgoInline(),
{
name: 'napi-rs-isolation-dev',
apply: 'serve',
configureServer(server) {
server.middlewares.use(isolationMiddleware)
},
configurePreviewServer(server) {
server.middlewares.use(isolationMiddleware)
},
},
voidPlugin(),
voidReact(),
// Build-time changelog data: resolves `virtual:changelog/<slug>` to one
// package's full release history rendered to HTML (fetched + Shiki'd once
// per build in Node). The changelog page islands import these, so they
// carry NO loader and auto-prerender to static, cookie-agnostic HTML.
changelogData(),
// Pre-process docs markdown to restore napi.rs code-block affordances
// BEFORE @void/md compiles it (must precede voidMarkdown so this `pre`
// transform runs first). Two rewrites:
// 1. `{n}` fence highlight meta → Shiki notation comments — @void/md's
// markdown-it-attrs eats `{…}` before transformerMetaHighlight reads
// it, so the meta is inert otherwise (lib/md/fence-highlight.ts).
// 2. `**filename**` captions → a `<div class="code-filename">` header
// bar element (lib/md/code-filename.ts).
// 3. package-manager install fences → tabbed markup (lib/md/pm-tabs.ts).
// transformPmTabs runs FIRST: it must see the ORIGINAL fences, and
// it preserves the inner fences verbatim, so the fence-line
// transforms after it still apply inside the tabs.
{
name: 'napi-rs-md-code-blocks',
enforce: 'pre',
transform(code: string, id: string) {
if (!id.endsWith('.md')) return
const out = markCodeFilenames(
convertFenceHighlightMeta(transformPmTabs(code)),
)
return out === code ? undefined : out
},
},
// enforce:'pre', auto-detects React → MUST come after voidReact()
voidMarkdown({
shiki: {
// Runtime accepts a theme OBJECT for either half; the @void/md type
// narrows `themes` to { light: string; dark: string }, so cast the
// css-variables object to satisfy the declared type (runtime is fine).
themes: {
light: shikiLightCssVars as unknown as string,
dark: shikiDarkCssVars as unknown as string,
},
langs: [
'rust',
'toml',
'bash',
'json',
'js',
'jsx',
'ts',
'tsx',
'diff',
'yaml',
],
},
}),
// Emit sitemap.xml + the raw `.md` assets into the client build output.
// Defined as a factory in scripts/generate-sitemap.mjs (co-located with
// the generator), mirroring lib/changelog/plugin.ts.
sitemapPlugin(),
// Emit a per-page Open Graph PNG (title on a branded 1200×630 card) for
// every docs + blog route into dist/client/og/<route>.png (satori →
// resvg). Same build-plugin rationale as the sitemap: `void deploy` runs
// `vp build`, so a plugin is what guarantees the images ship. Islands
// (home/changelog) keep the static /img/og-v2.png. Defined as a factory
// in scripts/generate-og-images.mjs (co-located with the generator).
ogImagePlugin(),
// Emit the blog RSS 2.0 feed (rss.xml) into the CLIENT build output, the
// same way (and for the same reasons) as the sitemap plugin above —
// `void deploy` runs `vp build`, not `npm run build`, so a build plugin
// is what guarantees the feed ships. napi.rs itself has no feed; this is
// net-new. The `<link rel="alternate">` in void.json points browsers /
// readers at it (scripts/generate-rss.mjs stays usable standalone too).
{
name: 'napi-rs-rss',
apply: 'build',
writeBundle(options) {
if (!options.dir || basename(options.dir) !== 'client') return
const { itemCount, skipped } = generateRss(options.dir)
console.log(
`napi-rs-rss: ${itemCount} blog posts -> ${options.dir}/rss.xml` +
(skipped.length ? ` (skipped: ${skipped.join(', ')})` : ''),
)
},
},
// Keep lib/docs/lastmod.gen.json (per-page lastmod + top contributors
// from git history) fresh at build (buildStart) and dev (server start)
// time. The write is idempotent, so dev watchers never loop on our own
// output. Factory in scripts/build-lastmod.mjs.
lastmodPlugin(),
// Emit /search-index.<locale>.json (the data behind the client-side
// Cmd+K search dialog) into the client build output. Factory in
// scripts/build-search-index.mjs, same rationale as the sitemap.
searchIndexPlugin(),
// Emit a branded, self-contained 404.html into the client output. The
// worker's notFound handler serves static /404.html from ASSETS when it
// exists (serveCustomErrorPage), turning bare 404s into branded ones.
// English-only on purpose: one file serves every locale.
{
name: 'napi-rs-404',
apply: 'build',
writeBundle(options) {
if (!options.dir || basename(options.dir) !== 'client') return
writeFileSync(join(options.dir, '404.html'), NOT_FOUND_HTML)
console.log(`napi-rs-404: wrote 404.html -> ${options.dir}`)
},
},
],
// --- Vitest: use Node pool/environment for lib/nav data-only tests ---
test: {
pool: 'forks',
environment: 'node',
server: {
deps: {
// Inline mermaid so the dompurify mock in pages/mermaid-syntax.test.ts
// reaches its internal imports (node_modules are external by default).
inline: ['mermaid'],
},
},
},
// --- Vite+ toolchain blocks (consumed by vp fmt / vp lint / vp check / vp staged) ---
// Mirror the project's previous Prettier config.
fmt: {
semi: false,
singleQuote: true,
trailingComma: 'all',
printWidth: 80,
ignorePatterns: [
'dist/**',
'.void/**',
'.wrangler/**',
'public/**',
'.yarn/**',
'content/**',
// @void/md island markdown pages MUST start with their `<script>` island
// block at byte 0 (the plugin's SCRIPT_RE is anchored, runs before
// gray-matter), so frontmatter follows the script. Oxfmt assumes
// frontmatter at byte 0 and rewrites the trailing `---` as a thematic
// break, corrupting the page. These pages are generated by
// scripts/convert-content.mjs (the sole formatter of record for them);
// exempt them from `vp fmt`. Append future inline-island .md pages here.
// All three locales share the identical byte-0 `<script>` island shape, so
// exempt every localized variant — not just en — for consistency and to
// stay safe against oxfmt version drift.
'pages/en/docs/concepts/webassembly.md',
'pages/cn/docs/concepts/webassembly.md',
'pages/pt-BR/docs/concepts/webassembly.md',
// Blog inline-island pages (byte-0 <script>). announce-v2 (en + cn) imports
// Diff + Contributors; announce-v3 (en) imports LinkPreview + the SVG-logo
// components + Sponsor. function-and-callbacks.md has NO island (it stays
// frontmatter-first) so it is intentionally NOT exempted.
'pages/en/blog/announce-v2.md',
'pages/cn/blog/announce-v2.md',
'pages/en/blog/announce-v3.md',
// Baked LinkPreview fixture — generated wholesale by
// scripts/fetch-link-previews.mjs (its formatter of record). Exempt so
// `vp fmt` doesn't reflow it out of sync with a future rebake.
'lib/docs/link-preview-data.json',
// Shiki HTML for the landing demo code panels — generated wholesale by
// scripts/build-demo-code.mjs. Exempt so `vp fmt` doesn't reflow the long
// pre-highlighted HTML strings out of sync with a regen.
'components/landing/live-demo-code.gen.ts',
],
},
// Oxlint — advisory for now (no type-aware path on this JS-heavy codebase yet).
lint: {
ignorePatterns: [
'dist/**',
'.void/**',
'.wrangler/**',
'.yarn/**',
'content/**',
'public/**',
],
},
// Replaces lint-staged. Format-only so it matches the old `prettier --write` behaviour
// (switch to `vp check --fix` once lint is green).
staged: {
'*.{js,jsx,ts,tsx,mjs,cjs}': 'vp fmt --write',
'*.{json,md,yml,yaml,css}': 'vp fmt --write',
},
})