Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

install-layout-oracle.e2e.test.ts

487 lines16.5 KB

1// @vitest-environment node
2/**
3 * # Which installs open the packaged OPFS database without configuration?
4 *
5 * The built package finds its worker and WASM file through URLs relative to its
6 * own code. A Vite production build and a Vite dev server that serves the
7 * package in place both resolve those URLs. Vite's dependency optimizer moves
8 * pre-bundled code into its cache and leaves the assets behind, so a moved copy
9 * asks the dev server for the assets by package name, from the app root.
10 *
11 * The README promises this behavior:
12 *
13 * - Production builds open in every install layout.
14 * - In development, a copy served in place opens with its own assets. A copy is
15 * served in place when `optimizeDeps.exclude` names the specifier that its
16 * importer uses, which is the alias name for an npm alias.
17 * - A moved copy opens when the app root resolves the package name, and rejects
18 * with `PersistenceUnavailableError` when it does not. When the root resolves
19 * another installed copy, the moved copy loads that copy's assets. A worker
20 * from another version refuses the opener, so that open rejects with
21 * `PersistenceUnavailableError` after the worker starts.
22 *
23 * The model below states those rules over install layout, cache directory,
24 * exclusion, and server. It reads facts from each installed tree rather than
25 * from a table per layout: the specifier that the opened copy's importer uses,
26 * the copy that Node resolution finds for the package name from the app root,
27 * and the version of each of those copies. The driver installs the built package in each layout, opens and
28 * queries it in Chromium, and records the outcome, the number of workers, and
29 * which copy's worker started. The model does not predict which copy a
30 * production build emits; the copies are identical, so the driver does not
31 * observe it there.
32 */
33import {
34 cpSync,
35 existsSync,
36 mkdirSync,
37 mkdtempSync,
38 readFileSync,
39 readdirSync,
40 realpathSync,
41 rmSync,
42 symlinkSync,
43 writeFileSync,
44} from 'node:fs'
45import { tmpdir } from 'node:os'
46import { dirname, join } from 'node:path'
47import { fileURLToPath } from 'node:url'
48import { chromium } from '@playwright/test'
49import { afterAll, beforeAll, expect, it } from 'vitest'
50import { createServer, preview } from 'vite'
51import { declareOracle } from '../../db/tests/oracle-declaration'
52import { buildForProduction } from './packaged-consumer'
53import type { Browser } from '@playwright/test'
54import type { BrowserWASQLiteDatabase } from '../src'
55​
56const packageDirectory = fileURLToPath(new URL('../', import.meta.url))
57const packageName = `@tanstack/browser-db-sqlite-persistence`
58const aliasName = `sqlite-alias`
59​
60type Layout =
61 | `direct`
62 | `hoisted`
63 | `pnpm`
64 | `transitive`
65 | `alias`
66 | `two copies`
67 | `two versions`
68type Cache = `default` | `custom` | `dist`
69type Exclusion = `none` | `import name` | `package name`
70type Server = `development` | `production`
71type LayoutCase = {
72 layout: Layout
73 cache: Cache
74 exclusion: Exclusion
75 server: Server
77type LayoutOutcome =
78 | { opens: false; workers: 0 | 1 }
79 | { opens: true; workers: 1; worker?: `imported copy` | `other copy` }
80​
81/** Facts read from an installed tree; see `installLayout`. */
82type InstallFacts = {
83 appDirectory: string
84 // The real directory of the copy that the app opens.
85 importedCopy: string
86 // The specifier that the opened copy's importer uses.
87 importSpecifier: string
88 // The real directory that the package name resolves to from the app root.
89 rootResolvedCopy: string | undefined
90 // The package version that each of those copies was built as.
91 importedVersion: string
92 rootResolvedVersion: string | undefined
94​
95// Node resolution: the nearest node_modules/<name> from a directory upward.
96function resolveFrom(directory: string, stop: string): string | undefined {
97 for (let current = directory; ; current = dirname(current)) {
98 const candidate = join(current, `node_modules`, packageName)
99 if (existsSync(candidate)) return realpathSync(candidate)
100 if (current === stop) return undefined
101 }
103​
104function expectedOutcome(
105 layoutCase: LayoutCase,
106 install: InstallFacts,
107): LayoutOutcome {
108 if (layoutCase.server === `production`) return { opens: true, workers: 1 }
109 const excludedName =
110 layoutCase.exclusion === `import name`
111 ? install.importSpecifier
112 : layoutCase.exclusion === `package name`
113 ? packageName
114 : undefined
115 if (excludedName === install.importSpecifier) {
116 return { opens: true, workers: 1, worker: `imported copy` }
117 }
118 if (!install.rootResolvedCopy) return { opens: false, workers: 0 }
119 if (install.rootResolvedCopy === install.importedCopy) {
120 return { opens: true, workers: 1, worker: `imported copy` }
121 }
122 // The moved copy starts the root copy's worker, which refuses an opener
123 // built as another version.
124 return install.rootResolvedVersion === install.importedVersion
125 ? { opens: true, workers: 1, worker: `other copy` }
126 : { opens: false, workers: 1 }
128​
129/*
130 * Histories: every layout with each cache directory while pre-bundled in
131 * development, since only a moved copy depends on the cache path; every layout
132 * excluded by its import name; an alias excluded by the package name, which
133 * does not match its specifier; and every layout in a production build.
134 */
135const layouts: Array<Layout> = [
136 `direct`,
137 `hoisted`,
138 `pnpm`,
139 `transitive`,
140 `alias`,
141 `two copies`,
142 `two versions`,
144const layoutCases: Array<LayoutCase> = [
145 ...layouts.flatMap((layout) =>
146 ([`default`, `custom`, `dist`] as const).map((cache) => ({
147 layout,
148 cache,
149 exclusion: `none` as const,
150 server: `development` as const,
151 })),
152 ),
153 ...layouts.map((layout) => ({
154 layout,
155 cache: `default` as const,
156 exclusion: `import name` as const,
157 server: `development` as const,
158 })),
159 {
160 layout: `alias`,
161 cache: `default`,
162 exclusion: `package name`,
163 server: `development`,
164 },
165 ...layouts.map((layout) => ({
166 layout,
167 cache: `default` as const,
168 exclusion: `none` as const,
169 server: `production` as const,
170 })),
172​
173declareOracle({
174 check: [expectLayoutOutcome],
175 model: [expectedOutcome],
176 grammar: [layoutCases],
177})
178​
179// The check: the installed copy's observed outcome equals the layout model's
180// prediction for the same case and install facts.
181async function expectLayoutOutcome(
182 layoutCase: LayoutCase,
183 install: InstallFacts,
184): Promise<void> {
185 expect(await openInLayout(install, layoutCase)).toEqual(
186 expectedOutcome(layoutCase, install),
187 )
189​
190let browser: Browser
191const coveredOutcomes = new Set<string>()
192beforeAll(async () => {
193 browser = await chromium.launch({ headless: true })
194})
195afterAll(async () => {
196 await browser.close()
197})
198​
199it.each(layoutCases)(
200 `$server $layout install (cache $cache, excluded by $exclusion) matches the layout model`,
201 async (layoutCase) => {
202 const temporaryDirectory = realpathSync(
203 mkdtempSync(join(realpathSync(tmpdir()), `db-wasm-layout-`)),
204 )
205 try {
206 const install = installLayout(temporaryDirectory, layoutCase.layout)
207 const expected = expectedOutcome(layoutCase, install)
208 coveredOutcomes.add(JSON.stringify(expected))
209 await expectLayoutOutcome(layoutCase, install)
210 } finally {
211 rmSync(temporaryDirectory, { recursive: true, force: true })
212 }
213 },
214 120_000,
216​
217// Grammar coverage: the cases above must reach every outcome the model can
218// predict. Runs after them, because the predictions read installed trees.
219it(`covers every promised layout outcome`, () => {
220 expect([...coveredOutcomes].sort()).toEqual(
221 [
222 { opens: false, workers: 0 },
223 { opens: false, workers: 1 },
224 { opens: true, workers: 1 },
225 { opens: true, workers: 1, worker: `imported copy` },
226 { opens: true, workers: 1, worker: `other copy` },
227 ]
228 .map((outcome) => JSON.stringify(outcome))
229 .sort(),
230 )
231})
232​
233/**
234 * Copies the built package to a directory, as an install would. With
235 * `version`, the copy is a build of that version: its manifest and the
236 * version that its opener and worker carry both change.
237 */
238function copyPackage(destination: string, version?: string): void {
239 mkdirSync(destination, { recursive: true })
240 cpSync(join(packageDirectory, `dist`), join(destination, `dist`), {
241 recursive: true,
242 })
243 const manifest = JSON.parse(
244 readFileSync(join(packageDirectory, `package.json`), `utf8`),
245 ) as { version: string } & Record<string, unknown>
246 writeFileSync(
247 join(destination, `package.json`),
248 JSON.stringify(version ? { ...manifest, version } : manifest),
249 )
250 if (!version) return
251 const builtMarker = `${packageName}@${manifest.version}`
252 for (const file of readdirSync(join(destination, `dist`), {
253 recursive: true,
254 }) as Array<string>) {
255 if (!/\.(c?js)$/.test(file)) continue
256 const path = join(destination, `dist`, file)
257 const source = readFileSync(path, `utf8`)
258 if (source.includes(builtMarker)) {
259 writeFileSync(
260 path,
261 source.replaceAll(builtMarker, `${packageName}@${version}`),
262 )
263 }
264 }
266​
267function installedVersion(directory: string | undefined): string | undefined {
268 if (!directory) return undefined
269 return (
270 JSON.parse(readFileSync(join(directory, `package.json`), `utf8`)) as {
271 version: string
272 }
273 ).version
275​
276// Links the package's workspace dependencies into a node_modules scope.
277function linkDependencies(scopeDirectory: string): void {
278 mkdirSync(scopeDirectory, { recursive: true })
279 for (const name of [`db`, `db-sqlite-persistence-core`]) {
280 symlinkSync(
281 join(packageDirectory, `../${name}`),
282 join(scopeDirectory, name),
283 `dir`,
284 )
285 }
287​
288// A library that re-exports the package; only it depends on the package.
289function writeWrapper(appModules: string): string {
290 const wrapper = join(appModules, `wrapper`)
291 mkdirSync(wrapper, { recursive: true })
292 writeFileSync(
293 join(wrapper, `package.json`),
294 JSON.stringify({ name: `wrapper`, type: `module`, main: `index.js` }),
295 )
296 writeFileSync(
297 join(wrapper, `index.js`),
298 `export { openBrowserWASQLiteOPFSDatabase } from '${packageName}'\n`,
299 )
300 return wrapper
302​
303/** Installs the built package in one layout and reads its install facts. */
304function installLayout(root: string, layout: Layout): InstallFacts {
305 const appDirectory =
306 layout === `hoisted` ? join(root, `apps/web`) : join(root, `app`)
307 const appModules = join(appDirectory, `node_modules`)
308 mkdirSync(appModules, { recursive: true })
309 writeFileSync(
310 join(appDirectory, `package.json`),
311 JSON.stringify({ name: `web`, type: `module` }),
312 )
313 let importedCopy: string
314 let entry = packageName
315 switch (layout) {
316 case `direct`:
317 importedCopy = join(appModules, packageName)
318 copyPackage(importedCopy)
319 linkDependencies(join(appModules, `@tanstack`))
320 break
321 case `hoisted`:
322 writeFileSync(
323 join(root, `package.json`),
324 JSON.stringify({ private: true, workspaces: [`apps/*`] }),
325 )
326 importedCopy = join(root, `node_modules`, packageName)
327 copyPackage(importedCopy)
328 linkDependencies(join(root, `node_modules/@tanstack`))
329 break
330 case `pnpm`: {
331 // pnpm keeps real directories in .pnpm and links the direct dependency.
332 const storeModules = join(
333 appModules,
334 `.pnpm/@tanstack+browser-db-sqlite-persistence@1.0.0/node_modules`,
335 )
336 importedCopy = join(storeModules, packageName)
337 copyPackage(importedCopy)
338 linkDependencies(join(storeModules, `@tanstack`))
339 mkdirSync(join(appModules, `@tanstack`), { recursive: true })
340 symlinkSync(importedCopy, join(appModules, packageName), `dir`)
341 break
342 }
343 case `transitive`:
344 case `two copies`:
345 case `two versions`: {
346 const wrapper = writeWrapper(appModules)
347 importedCopy = join(wrapper, `node_modules`, packageName)
348 copyPackage(
349 importedCopy,
350 layout === `two versions` ? `0.0.0-nested` : undefined,
351 )
352 linkDependencies(join(appModules, `@tanstack`))
353 if (layout !== `transitive`) copyPackage(join(appModules, packageName))
354 entry = `wrapper`
355 break
356 }
357 case `alias`:
358 importedCopy = join(appModules, aliasName)
359 copyPackage(importedCopy)
360 linkDependencies(join(appModules, `@tanstack`))
361 entry = aliasName
362 break
363 }
364 writeFileSync(
365 join(appDirectory, `index.html`),
366 `<script type="module" src="./main.js"></script>`,
367 )
368 writeFileSync(
369 join(appDirectory, `main.js`),
370 `import { openBrowserWASQLiteOPFSDatabase } from '${entry}';
371globalThis.openDatabase = () => openBrowserWASQLiteOPFSDatabase({ databaseName: 'layout.sqlite', timeoutMs: 0 });`,
372 )
373 return {
374 appDirectory,
375 importedCopy: realpathSync(importedCopy),
376 importSpecifier: layout === `alias` ? aliasName : packageName,
377 rootResolvedCopy: resolveFrom(appDirectory, root),
378 importedVersion: installedVersion(importedCopy)!,
379 rootResolvedVersion: installedVersion(resolveFrom(appDirectory, root)),
380 }
382​
383async function openInLayout(
384 { appDirectory, importedCopy, importSpecifier }: InstallFacts,
385 layoutCase: LayoutCase,
386): Promise<LayoutOutcome> {
387 const config = {
388 configFile: false as const,
389 root: appDirectory,
390 base: `/nested/`,
391 logLevel: `error` as const,
392 cacheDir:
393 layoutCase.cache === `custom`
394 ? join(appDirectory, `node_modules/.cache/vite`)
395 : layoutCase.cache === `dist`
396 ? join(appDirectory, `node_modules/.cache/dist`)
397 : undefined,
398 optimizeDeps:
399 layoutCase.exclusion === `none`
400 ? undefined
401 : {
402 exclude: [
403 layoutCase.exclusion === `import name`
404 ? importSpecifier
405 : packageName,
406 ],
407 },
408 }
409 let developmentServer: Awaited<ReturnType<typeof createServer>> | undefined
410 let productionServer: Awaited<ReturnType<typeof preview>> | undefined
411 if (layoutCase.server === `production`) {
412 await buildForProduction({
413 ...config,
414 build: { outDir: join(appDirectory, `dist`) },
415 })
416 productionServer = await preview({
417 ...config,
418 preview: { host: `127.0.0.1`, port: 0 },
419 })
420 } else {
421 developmentServer = await createServer({
422 ...config,
423 // Files are written just before the server starts. A late watcher event
424 // would reload the page during the open, so these servers do not watch.
425 server: { host: `127.0.0.1`, port: 0, watch: null },
426 })
427 await developmentServer.listen()
428 }
429 const page = await browser.newPage()
430 const workerUrls: Array<string> = []
431 const diagnostics: Array<string> = []
432 page.on(`worker`, (worker) => workerUrls.push(worker.url()))
433 page.on(`pageerror`, (error) => diagnostics.push(error.message))
434 page.on(`response`, (response) => {
435 if (response.status() >= 400) {
436 diagnostics.push(`${response.status()} ${response.url()}`)
437 }
438 })
439 try {
440 const server = developmentServer ?? productionServer
441 await page.goto(server!.resolvedUrls!.local[0]!)
442 const opened = await page.evaluate(async () => {
443 const { openDatabase } = globalThis as typeof globalThis & {
444 openDatabase: () => Promise<BrowserWASQLiteDatabase>
445 }
446 try {
447 const database = await openDatabase()
448 try {
449 await database.execute(`SELECT 42 AS value`)
450 return { opens: true as const }
451 } finally {
452 await database.close?.()
453 }
454 } catch (error) {
455 return { opens: false as const, name: (error as Error).name }
456 }
457 })
458 if (!opened.opens) {
459 // Any rejection other than the promised one is reported in full.
460 if (opened.name !== `PersistenceUnavailableError`) {
461 throw new Error(`${opened.name}\n${diagnostics.join(`\n`)}`)
462 }
463 return { opens: false, workers: workerUrls.length } as LayoutOutcome
464 }
465 if (layoutCase.server === `production`) {
466 return { opens: true, workers: workerUrls.length } as LayoutOutcome
467 }
468 // Vite serves a file under the root by its root path and one outside the
469 // root under /@fs/ with its absolute path.
470 const importedPath = importedCopy.startsWith(`${appDirectory}/`)
471 ? importedCopy.slice(appDirectory.length)
472 : importedCopy
473 const fromImportedCopy = workerUrls.map((url) =>
474 decodeURIComponent(new URL(url).pathname).includes(`${importedPath}/`),
475 )
476 return {
477 opens: true,
478 workers: workerUrls.length,
479 // With other than one worker the count already differs from the model.
480 worker: fromImportedCopy.every(Boolean) ? `imported copy` : `other copy`,
481 } as LayoutOutcome
482 } finally {
483 await page.close()
484 await developmentServer?.close()
485 await productionServer?.close()
486 }