Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
795 lines (761 loc) · 34.3 KB
/
Copy pathvite.config.ts
File metadata and controls
795 lines (761 loc) · 34.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import { defineConfig, loadEnv, parseAstAsync } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
import { oxcReactCompiler } from './oxcReactCompilerPlugin';
import webfontDownload from 'vite-plugin-webfont-dl';
import prismjs from 'vite-plugin-prismjs';
import { prismjsOptimizeDeps, prismjsOptions } from './prismDeps';
import wasm from 'vite-plugin-wasm';
import { wuchale } from 'wuchale/vite';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
import { execSync } from 'node:child_process';
import { buildWebsiteRuntime } from './scripts/build-website-runtime.mjs';
// TAURI=1 produces a Tauri-compatible bundle: no CSP nonces (Tauri serves
// HTML verbatim, so the server's runtime ATOMICSERVER_NONCE substitution
// doesn't happen), no PWA service worker (tauri:// isn't HTTP), separate
// outDir so the server build keeps its own nonce'd dist.
const isTauri = process.env.TAURI === '1';
// The packaged and dev desktop app is the atomic.place product, so it is a
// hosted distribution unless a build says otherwise. A plain web build from
// source stays the neutral, self-hostable AtomicServer.
if (isTauri) process.env.VITE_ATOMIC_HOSTED_DISTRIBUTION ??= 'true';
const isVitest = process.env.VITEST === 'true';
// Source maps are 28MB of the 48MB dist -- and that dist is compiled into the
// atomic-server binary by build.rs, so every user downloads ~60% debugging
// artifacts they will never open. `vite dev` serves maps regardless of this
// setting, so day-to-day debugging is unaffected; set SOURCEMAP=1 to put them
// back into a production build when you need to read a minified stack trace.
const wantSourcemaps = process.env.SOURCEMAP === '1';
// Readable stack traces in Sentry without shipping the maps. With a token, the
// build writes hidden source maps (no `sourceMappingURL` comment), uploads them
// under the release the SDK reports, and deletes them, so the dist stays as
// small as above. Without a token, nothing changes. Add `SENTRY_AUTH_TOKEN`
// to the environment of every build that is served to users.
const uploadSourcemaps = Boolean(process.env.SENTRY_AUTH_TOKEN) && !isVitest;
const repoLibDefaults = path.resolve(__dirname, '../../lib/defaults');
const ciLibDefaults = path.resolve(__dirname, '../lib-defaults');
const libDefaultsDir = fs.existsSync(
path.join(repoLibDefaults, 'default_base_models.json'),
)
? repoLibDefaults
: ciLibDefaults;
// Build/version info surfaced on the About page. Computed at build time and
// injected via `define`. Falls back gracefully outside a git checkout.
const appVersion = (
JSON.parse(
fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf-8'),
) as { version: string }
).version;
let gitCommit = 'unknown';
try {
gitCommit = execSync('git rev-parse --short HEAD', { cwd: __dirname })
.toString()
.trim();
} catch {
// Not a git checkout (e.g. published tarball) — leave as 'unknown'.
}
const buildTime = new Date().toISOString();
// A content hash of the atomic-wasm pair, appended to their URLs as `?v=`.
//
// These two files are the only ones the app loads from a STABLE url: they're
// copied into `public/wasm/` by `build:wasm` instead of going through Rollup,
// so unlike every hashed chunk their url stays identical across builds. That is
// what let a page span a service-worker update in 2026-08 and run the NEW app
// chunks against the PREVIOUS generation's precached glue, whose namespace has
// no `argon2idDeriveKey` — recovery-code generation died on a stale module the
// server had already replaced. Hashing the content into the url means the two
// generations no longer collide, so a mixed-generation page misses and refetches
// instead of silently resolving to the old body.
function wasmVersion(): string {
const dir = path.resolve(__dirname, 'public/wasm');
const hash = crypto.createHash('sha256');
let hashedAny = false;
for (const file of ['atomic_wasm.js', 'atomic_wasm_bg.wasm']) {
const full = path.join(dir, file);
if (!fs.existsSync(full)) continue;
hash.update(fs.readFileSync(full));
hashedAny = true;
}
// Absent under SKIP_WASM_BUILD=1 (and before the first `build:wasm`). A
// constant beats a hash of nothing, which would read as a real version.
return hashedAny ? hash.digest('hex').slice(0, 12) : 'dev';
}
// Computed once: hashing the pair reads ~6MB off disk.
const wasmVersionHash = wasmVersion();
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), 'VITE_');
// The desktop app's account service is atomic.place unless a local .env
// names another (a dev control plane). Without this a portal remembered from
// some server it once asked (staging) wins over the product's own.
if (
isTauri &&
!process.env.VITE_MANAGED_PORTAL_URL &&
!env.VITE_MANAGED_PORTAL_URL
) {
process.env.VITE_MANAGED_PORTAL_URL = 'https://atomic.place';
}
// Feedback needs a Sentry DSN, and the desktop app is not served by a node
// that could inject one, so "Send feedback" would be greyed out. The DSN is
// public (it only allows sending). A dev app reports as its own environment,
// apart from released builds.
if (isTauri && !process.env.VITE_SENTRY_DSN && !env.VITE_SENTRY_DSN) {
process.env.VITE_SENTRY_DSN =
'https://b08842f7f4ac1d5bea3415049eb226c0@o1378995.ingest.us.sentry.io/4512015907291136';
if (!process.env.VITE_SENTRY_ENVIRONMENT && !env.VITE_SENTRY_ENVIRONMENT) {
process.env.VITE_SENTRY_ENVIRONMENT =
mode === 'development' ? 'desktop-dev' : 'production';
}
}
const atomicServerUrl =
process.env.VITE_ATOMIC_SERVER_URL ??
env.VITE_ATOMIC_SERVER_URL ??
'http://localhost:9883';
// The hosted distribution (atomic.place) carries its own name. A build from
// source is the self-hostable server and keeps a neutral one.
const hostedFlag =
process.env.VITE_ATOMIC_HOSTED_DISTRIBUTION ??
env.VITE_ATOMIC_HOSTED_DISTRIBUTION;
const hosted = hostedFlag === '1' || hostedFlag === 'true';
const appName = hosted ? 'atomic.place' : 'AtomicServer';
const appDescription = hosted
? 'Your own place for documents, tables, meetings and chat. Local-first and open source, with optional cloud backup and sync.'
: 'The easiest way to create, share and model Linked Atomic Data.';
return {
define: {
__APP_VERSION__: JSON.stringify(appVersion),
__GIT_COMMIT__: JSON.stringify(gitCommit),
__BUILD_TIME__: JSON.stringify(buildTime),
__WASM_VERSION__: JSON.stringify(wasmVersionHash),
},
resolve: {
// `loro-prosemirror` is excluded from dep-optimization (see
// optimizeDeps.exclude — it pulls in the WASM `loro-crdt`), so its
// `import "prosemirror-view"` is served raw from node_modules. Meanwhile
// tiptap's ProseMirror is prebundled into an optimized chunk. Without
// deduping, that yields TWO copies of the `prosemirror-view` module at
// runtime: a `DecorationSet` produced by loro's cursor plugin then fails
// `instanceof DecorationSet` inside tiptap's `DecorationGroup.from`, which
// reads `.members` off the foreign set (undefined) and pushes it as a null
// group member — crashing `DecorationGroup.locals` ("Cannot read
// properties of undefined (reading 'localsInner')") on the next view
// update (e.g. opening the slash menu next to a collaborator cursor).
// Deduping forces a single shared instance so the `instanceof` holds.
// Shared sources receive localization imports from the host compiler.
// Resolve that injected runtime through the host's dependency.
dedupe: [
'prosemirror-view',
'prosemirror-state',
'prosemirror-model',
'@wuchale/jsx',
],
alias: [
{
find: '@tomic/resource-ui/locale-runtime',
replacement: path.resolve(
__dirname,
'../resource-ui/src/locales/main.loader.js',
),
},
{
find: '@tomic/resource-ui/locale-message',
replacement: path.resolve(
__dirname,
'../resource-ui/src/locales/message.js',
),
},
{
find: '@tomic/resource-ui',
replacement: path.resolve(__dirname, '../resource-ui/src'),
},
{
find: '@tomic/table-page',
replacement: path.resolve(__dirname, '../table-page/src'),
},
{
find: '@tomic/table',
replacement: path.resolve(__dirname, '../table/src/index.ts'),
},
{
find: '@tomic/ui',
replacement: path.resolve(__dirname, '../ui/src'),
},
// Force EVERY `loro-crdt` import (our `enableLoro`, plus
// `loro-prosemirror` used by the editor) onto the `web` build.
// The default entry resolves via the `module` field to the
// `bundler` build, whose WASM↔JS circular import + top-level
// -await glue hangs under `vite-plugin-wasm` (loro-crdt ≥ 1.12).
// Aliasing to one build also guarantees a SINGLE Loro module
// instance — otherwise a web-build `LoroDoc` handed to a
// bundler-build `loro-prosemirror` fails `instanceof` checks and
// the two WASM memories diverge. Exact-match regex so the
// `loro-crdt/web` subpath import in `LoroLoader` is left alone.
{
find: '@integration-host/import-records',
replacement: path.resolve(__dirname, '../lib/src/import-records.ts'),
},
{
find: '@integration-host/plugin-connection',
replacement: path.resolve(
__dirname,
'../lib/src/plugin-connection.ts',
),
},
{
find: '@integration-host/plugin-reconcile',
replacement: path.resolve(
__dirname,
'../lib/src/plugin-reconcile.ts',
),
},
{
find: '@integration-host/navigation',
replacement: path.resolve(__dirname, 'src/helpers/navigation.tsx'),
},
{
find: '@integration-host/runScript',
replacement: path.resolve(
__dirname,
'src/chunks/PluginRuns/runScript.ts',
),
},
{
find: '@integration-host/RunPluginDialog',
replacement: path.resolve(
__dirname,
'src/chunks/PluginRuns/RunPluginDialog.tsx',
),
},
{
find: '@integration-host/table/createTableFromSpec',
replacement: path.resolve(
__dirname,
'../table-page/src/TablePage/createTableFromSpec.ts',
),
},
{
find: '@integration-host/table/tableTemplates',
replacement: path.resolve(
__dirname,
'../table-page/src/TablePage/tableTemplates.ts',
),
},
{ find: /^loro-crdt$/, replacement: 'loro-crdt/web' },
{
find: '@components',
replacement: path.resolve(__dirname, 'src/components'),
},
{ find: '@views', replacement: path.resolve(__dirname, 'src/views') },
{ find: '@hooks', replacement: path.resolve(__dirname, 'src/hooks') },
{
find: '@helpers',
replacement: path.resolve(__dirname, 'src/helpers'),
},
{ find: '@chunks', replacement: path.resolve(__dirname, 'src/chunks') },
{ find: '@repo-lib-defaults', replacement: libDefaultsDir },
],
},
plugins: [
wasm(),
{
// `src/chunks/Website/runtime/{search-view.html,website-runtime.min.js}`
// are gitignored bundles of the runtime's `.ts` sources. `config` runs
// for dev, build and vitest alike, so every consumer finds them fresh.
name: 'website-runtime',
async config() {
await buildWebsiteRuntime();
},
async handleHotUpdate({ file }) {
if (/Website\/runtime\/[^/]+\.ts$/.test(file)) {
await buildWebsiteRuntime();
}
},
},
{
// mdast-util-gfm-autolink-literal finds emails with a lookbehind,
// which Safari before 16.4 rejects (see the check below). Its
// `findEmail` checks the previous character itself, so the
// lookbehind can go. A transform, not a pnpm patch: pnpm applies a
// new patch to a fresh install only, and an existing node_modules
// keeps the unpatched file in the patched package's folder.
name: 'autolink-email-without-lookbehind',
enforce: 'pre',
transform(code, id) {
if (!id.includes('mdast-util-gfm-autolink-literal')) return;
const lookbehind = '/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@';
if (!code.includes(lookbehind)) return;
return code.replace(lookbehind, '/([-.\\w+]+)@');
},
},
{
// Safari before 16.4 (iOS 16.3 and older) throws a SyntaxError on a
// regex literal with a lookbehind, `(?<=` or `(?<!`, and then loads
// none of the bundle: a blank page that never reaches Sentry. The
// build target doesn't lower regexes, so fail the build instead.
name: 'no-lookbehind-regex-literals',
apply: 'build',
async generateBundle(_options, bundle) {
const found: string[] = [];
const walk = (node: unknown, file: string) => {
if (!node || typeof node !== 'object') return;
const regex = (node as { regex?: { pattern: string } }).regex;
if (regex && /\(\?<[=!]/.test(regex.pattern)) {
found.push(`${file}: /${regex.pattern.slice(0, 80)}/`);
}
for (const child of Object.values(node)) walk(child, file);
};
for (const item of Object.values(bundle)) {
if (item.type === 'chunk') {
walk(await parseAstAsync(item.code), item.fileName);
}
}
if (found.length > 0) {
this.error(
`Lookbehind regex literals break Safari < 16.4; rewrite them ` +
`(or patch the dependency):\n${found.join('\n')}`,
);
}
},
},
{
// `prefetch.json`: what a first visit downloads before the app can
// start, for another page to warm the HTTP cache with ahead of time.
// atomic.place's homepage reads it while a visitor looks at the "Try
// Atomic" button, so the click no longer waits on ~3 MB of
// WebAssembly (measured: 4.0 s to 2.4 s from click to workspace).
// Hashed names change every build, which is why this is generated
// rather than written down anywhere.
name: 'atomic-prefetch-manifest',
apply: 'build',
generateBundle(_options, bundle) {
const files = new Set<string>();
const add = (name: string) => files.add(`/${name}`);
const entry = Object.values(bundle).find(
item => item.type === 'chunk' && item.isEntry,
);
if (entry?.type === 'chunk') {
add(entry.fileName);
entry.imports.forEach(add);
entry.viteMetadata?.importedCss.forEach(add);
}
for (const item of Object.values(bundle)) {
if (
item.type === 'asset' &&
/loro_wasm_bg.*\.wasm$/.test(item.fileName)
)
add(item.fileName);
}
files.add(`/wasm/atomic_wasm_bg.wasm?v=${wasmVersionHash}`);
this.emitFile({
type: 'asset',
fileName: 'prefetch.json',
source: JSON.stringify({ files: [...files] }, null, 2),
});
},
},
{
// index.html preloads the wasm pair to warm the worker's fetch, so those
// hrefs have to carry the same `?v=` the app requests — a preload for a
// url nobody asks for is a wasted download plus a console warning.
name: 'atomic-wasm-version-html',
transformIndexHtml: (html: string) =>
html.replaceAll('__WASM_VERSION__', wasmVersionHash),
},
{
// The tab title, description and splash caption before the bundle runs.
name: 'atomic-app-name-html',
transformIndexHtml: (html: string) =>
html
.replaceAll('__APP_NAME__', appName)
.replaceAll('__APP_DESCRIPTION__', appDescription),
},
!isVitest && webfontDownload(),
!isVitest &&
wuchale({
configPath: path.resolve(
__dirname,
'../resource-ui/wuchale.config.js',
),
}),
// Native React Compiler (oxc-transform-react). Must run before JSX
// transforms; this plugin does compiler + TS + JSX + Fast Refresh in one
// pass. Replace with `react({ compiler: true })` once plugin-react 6.1.0
// is released (vitejs/vite-plugin-react#1419). The compiler transform is
// skipped under Vitest — unit tests call `transformSync` directly — but
// the oxc styled-components options still apply so displayName works.
// The app compiles `@tomic/react` too: it is linked from outside
// `node_modules`, so the compiler sees its hooks. Tests compile just
// that package, so a hook the compiler would cache wrongly fails here.
...oxcReactCompiler(
isVitest ? { only: /\/browser\/react\/src\// } : { compile: true },
),
react(),
!isVitest &&
!isTauri &&
VitePWA({
registerType: 'autoUpdate',
injectRegister: 'auto',
manifest: {
name: appName,
short_name: hosted ? 'atomic.place' : 'Atomic',
description: appDescription,
theme_color: '#ffffff',
icons: [
{
src: 'app_data/images/android-chrome-192x192.png',
sizes: '192x192',
type: 'image/png',
purpose: 'any',
},
{
src: 'app_data/images/android-chrome-512x512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'any',
},
{
src: 'app_data/images/maskable_icon.png',
sizes: '1024x1024',
type: 'image/png',
purpose: 'maskable',
},
{
src: 'app_data/images/maskable_icon_x512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'maskable',
},
{
src: 'app_data/images/maskable_icon_x384.png',
sizes: '384x384',
type: 'image/png',
purpose: 'maskable',
},
{
src: 'app_data/images/maskable_icon_x192.png',
sizes: '192x192',
type: 'image/png',
purpose: 'maskable',
},
{
src: 'app_data/images/maskable_icon_x128.png',
sizes: '128x128',
type: 'image/png',
purpose: 'maskable',
},
],
},
workbox: {
// The Sentry upload deletes the build's source maps, but workbox
// writes its own (`sw.js.map`, `workbox-*.js.map`) afterwards,
// which would then be served publicly. Never emit them.
sourcemap: false,
// See https://github.com/atomicdata-dev/atomic-data-browser/issues/294
// index.html is excluded from precaching because atomic-server injects
// CSP nonces dynamically. Instead we use runtime caching with NetworkFirst
// so the SW caches whatever HTML the server serves (with nonce), and falls
// back to it offline.
// `/wasm/` is excluded because the app now requests those files with
// a `?v=<hash>` query (see `wasmVersion` above), which no precache
// entry keyed on the bare path can serve — precaching them would
// just park ~6MB per generation that nothing ever reads. The
// runtimeCaching rule below still caches them (keyed by the full
// versioned url), so offline use is unaffected after first load.
globIgnores: ['**/index.html', '**/wasm/**'],
// Purge precache entries from prior builds on SW activation, so a
// stale worker/wasm can never linger after the hashed names change.
cleanupOutdatedCaches: true,
// Increased for WASM binaries (loro-crdt + atomic-wasm)
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
// index.html is NOT precached because atomic-server injects CSP nonces.
// Disable the default navigateFallback (which requires precached index.html).
// Instead we cache navigation responses at runtime with NetworkFirst.
navigateFallback: null,
runtimeCaching: [
{
// Cache ALL navigation requests (SPA — same HTML shell for all routes).
// NetworkFirst: use server when online, fall back to cache offline.
urlPattern: ({ request }) => request.mode === 'navigate',
handler: 'NetworkFirst',
options: {
cacheName: 'html-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 7, // 7 days
},
cacheableResponse: {
statuses: [200],
},
},
},
{
// Cache WASM and worker files
urlPattern: /\/wasm\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'wasm-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 30, // 30 days
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 365, // <== 365 days
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
{
urlPattern:
/^https?:\/\/.*\.(?:png|jpg|jpeg|gif|bmp|svg|webp|ico)/i,
handler: 'CacheFirst',
options: {
cacheName: 'images-cache',
expiration: {
maxEntries: 100,
maxAgeSeconds: 60 * 60 * 24 * 30, // <== 30 days
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
{
urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'gstatic-fonts-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 365, // <== 365 days
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
},
}),
!isVitest && prismjs(prismjsOptions),
uploadSourcemaps &&
sentryVitePlugin({
org: 'ontola',
project: 'atomic-browser',
url: 'https://us.sentry.io',
authToken: process.env.SENTRY_AUTH_TOKEN,
telemetry: false,
// Must equal the `release` that `initSentry` passes to the SDK.
release: {
name: `atomic-data-browser@${appVersion}+${gitCommit}`,
inject: false,
setCommits: false,
},
sourcemaps: {
filesToDeleteAfterUpload: wantSourcemaps
? undefined
: [`${isTauri ? 'dist-tauri' : 'dist'}/**/*.map`],
},
// A Sentry outage must not fail a deploy.
errorHandler: err => {
console.warn(`[sentry] source map upload failed: ${err.message}`);
},
}),
],
optimizeDeps: {
// React Compiler emits `import { c as _c } from "react/compiler-runtime"`
// in every memoised component. Without this hint, Vite only discovers
// the dep the first time a compiled module loads — it prebundles
// mid-session and serves a half-written file to the next request,
// surfacing as `NS_ERROR_CORRUPTED_CONTENT` + empty MIME type on the
// browser. Listing it up front makes the optimization happen at boot.
//
// The AI SDK graph (`ai`, `@ai-sdk/react`, the provider packages and the
// MCP SDK) is only reachable behind the `React.lazy` AI sidebar chunk, so
// Vite's boot-time scan (which follows static imports from index.html)
// never sees it. The first time the sidebar opens, Vite discovers the
// whole graph, re-optimizes, and HARD-RELOADS the page — surfacing as a
// ~20s "Loading AI" stall (the lazy chunk's Suspense fallback). Listing
// them here prebundles them at boot so first-open is warm. Dev-only:
// production builds prebundle everything at build time. Keep in sync with
// the AI-only deps in `src/chunks/AI/`.
include: [
'react/compiler-runtime',
'@emotion/is-prop-valid',
'ai',
'@ai-sdk/react',
'zod',
'ollama-ai-provider-v2',
'@openrouter/ai-sdk-provider',
'@modelcontextprotocol/sdk/client/index.js',
'@modelcontextprotocol/sdk/client/sse.js',
'@modelcontextprotocol/sdk/client/streamableHttp.js',
'fast-json-patch',
// Prebundle the collaborative editor's CRDT-ProseMirror bridge into the
// same optimize graph as tiptap so they share ONE `prosemirror-view`
// instance (see the exclude note below re: the DecorationGroup crash).
// `loro-crdt` stays external, so the WASM is unaffected.
'loro-prosemirror',
// Lazy-loaded only when a leftover Yjs-era DocumentV2 is opened. Listed
// so the first `import('yjs')` does not trigger a mid-session re-optimize
// that 504s the dynamic import.
'yjs',
// The JSON value editor (`src/chunks/CodeEditor/AsyncJSONEditor.tsx`).
// `entries` below lets a fresh scan find these, but Vite leaves
// `entries` out of its dep-cache hash, so an older `.vite/deps`
// without them is reused as is and the first click on a JSON value
// re-optimized and reloaded the page (#1793). Listing them here also
// changes that hash, which retires such a cache.
'@uiw/react-codemirror',
'@uiw/codemirror-theme-github',
'@codemirror/lang-json',
'@codemirror/lint',
'codemirror-json-schema',
// Injected by `vite-plugin-prismjs` at transform time, after the scan;
// see `prismDeps.ts`. The first rendered JSON value reloaded the page.
...prismjsOptimizeDeps,
],
// `loro-crdt` ships a WASM module that `vite-plugin-wasm` (see the
// `wasm()` plugin above) handles. esbuild's dep-optimizer CANNOT —
// if Vite prebundles loro-crdt, the WASM init in the optimized
// chunk hangs forever: `import('loro-crdt')` in `enableLoro()`
// never resolves OR rejects, so `LoroLoader.isLoaded()` stays
// false, every `getLoroDoc()` returns undefined, and documents are
// stuck (now surfaced as the "editor failed to load" error in
// `DocumentV2FullPage`). Excluding it from optimization lets
// `vite-plugin-wasm` serve the module untouched. This is the
// documented requirement for WASM deps under vite-plugin-wasm.
//
// It also explains the *intermittent* original failure: with
// loro-crdt neither included nor excluded, Vite auto-discovered it
// on the first lazy import and tried to optimize it mid-session —
// sometimes racing cleanly, sometimes hanging. Excluding makes it
// deterministic.
// Both must skip esbuild prebundling: the `web` build loads its
// `.wasm` via `fetch(new URL('loro_wasm_bg.wasm', import.meta.url))`.
// If esbuild inlines either into an optimized chunk, `import.meta.url`
// points at `.vite/deps/…` where the `.wasm` doesn't exist → 404.
// Excluding keeps it served from `node_modules` so the relative
// `.wasm` URL resolves.
//
// NOTE: `loro-prosemirror` is deliberately NOT excluded (it's `include`d
// above). It only imports `loro-crdt` as a peer, which stays external
// here, so optimizing it doesn't drag the WASM into a chunk. Crucially,
// optimizing it puts its `prosemirror-view`/`-state`/`-model` imports in
// the SAME prebundled graph as tiptap's. If loro were excluded (served
// raw) while tiptap's ProseMirror was prebundled, there would be TWO
// runtime copies of `prosemirror-view`: a `DecorationSet` from loro's
// cursor plugin then fails `instanceof DecorationSet` inside tiptap's
// `DecorationGroup.from`, which reads `.members` off the foreign set
// (undefined) and stores it as a null group member — crashing
// `DecorationGroup.locals` ("Cannot read properties of undefined (reading
// 'localsInner')") on the next view update (e.g. opening the slash menu
// next to a collaborator's caret). One optimize graph + `resolve.dedupe`
// above keeps it a single instance. (Prod is unaffected: rollup bundles
// once.)
// `@tomic/lib` / `@tomic/react` are workspace packages built in watch mode
// (tsup) alongside this dev server. If Vite PRE-BUNDLES them into
// `.vite/deps`, that cache is keyed on the lockfile/config hash — NOT on the
// packages' `dist` content — so a rebuilt `dist` is invisible until a
// `--force` re-optimize. Excluding them makes Vite serve their `dist`
// directly, so every watch rebuild shows up on a plain reload (the documented
// workspace-link workaround). They don't drag in WASM/ProseMirror, so there's
// no single-instance concern like `loro-crdt` below.
exclude: ['loro-crdt', '@tomic/lib', '@tomic/react'],
//
// Vite's boot-time dep scan only follows static imports from index.html, so
// it never sees the deps behind `React.lazy` chunks (RTE/tiptap, AI SDK,
// code/table/PDF editors). The first time such a chunk loads, Vite
// discovers its deps mid-session, re-optimizes, and 504s the in-flight
// dynamic import ("Outdated Optimize Dep" → "Failed to fetch dynamically
// imported module: CollaborativeEditor.tsx"). Crawling the chunk roots at
// boot pre-optimizes everything, so first-open is warm and e2e is stable.
entries: [
'./index.html',
'./src/chunks/**/*.{ts,tsx}',
'../resource-ui/src/chunks/**/*.{ts,tsx}',
'../table-page/src/**/*.{ts,tsx}',
],
},
test: {
setupFiles: ['./src/test-setup.ts'],
// The suite runs on a CI host that is also busy with other jobs. A test
// that dynamically imports a large module spends more than the default
// five seconds on the import alone, and fails without anything being
// wrong. A real hang still fails, just later.
testTimeout: 30_000,
},
build: {
target: 'baseline-widely-available',
outDir: isTauri ? 'dist-tauri' : 'dist',
sourcemap: wantSourcemaps ? true : uploadSourcemaps ? 'hidden' : false,
// Don't inline worker scripts as `data:` URLs — the production CSP is
// `worker-src 'self'` and would block them, killing the ClientDb. Below
// the default 4096-byte limit, Vite would otherwise inline our 1.7KB
// ClientDb worker and break in prod (works in dev because dev has no CSP).
assetsInlineLimit: (filePath: string) =>
filePath.endsWith('.worker.js') ? false : undefined,
rollupOptions: {
output: {
entryFileNames: `assets/[name]-[hash].js`,
chunkFileNames: `assets/chunk_[name]-[hash].js`,
// Content-hash ALL assets — including the `?url`-imported ClientDb
// worker and the loro-crdt `.wasm`. With stable names these were
// precached by Workbox with `revision: null` (it assumes an unhashed
// name is immutable), so a content change kept the same URL+revision
// and the SW served the OLD worker/wasm to NEW hashed chunks forever:
// a soft (cmd+r) reload hit a stale worker (missing newer message
// handlers → empty resources) and the stale loro bundler glue
// (`./loro_wasm_bg.js` import error). Hashing makes every change a new
// URL Workbox correctly re-fetches. atomic-wasm is unaffected: it's
// served from the stable `/wasm/` public path, not via this pipeline.
assetFileNames: `assets/[name]-[hash].[ext]`,
},
},
},
html: {
cspNonce: isTauri ? undefined : 'ATOMICSERVER_NONCE',
},
server: {
// Fixed, uncommon port so the atomicbrowser dev server never collides with
// vite's default 5173 (used by other local apps).
// strictPort makes a collision fail loudly instead of silently shifting.
port: 6747,
strictPort: true,
host: true,
allowedHosts: ['.tunn.dev', 't-1sk9qbdw.tunn.dev'],
// Pre-transform the lazy AI chunk's source graph in the background at
// boot, so the first time the sidebar opens its modules are already
// through the React Compiler pass instead of being transformed on-demand
// while the user waits behind "Loading AI". Complements the
// `optimizeDeps.include` AI entries above (those cover the npm deps;
// this covers our own source modules).
warmup: {
clientFiles: [
'./src/chunks/AI/AISidebar.tsx',
'./src/chunks/RTE/AIChatInput/AsyncAIChatInput.tsx',
],
},
// Kept in step with VITE_ATOMIC_SERVER_URL in .env.development — these
// proxy to the same server the app talks to.
proxy: {
'/server': atomicServerUrl,
'/iroh-sync': atomicServerUrl,
},
},
};
});