Open History to see the last commit
1// @vitest-environment node
2/**
3 * Receiving witnesses for bundlers other than Vite. The README promises that
4 * an app loads the OPFS worker and the separate `wa-sqlite.wasm` file without
5 * asset configuration. Each case installs the built package in a consumer app,
6 * bundles it, opens and queries SQLite in Chromium, and checks four facts:
7 *
8 * - the query returns its row;
9 * - one worker starts, as a classic script;
10 * - the browser loads one `200 application/wasm` response;
11 * - the Vite dev-server lookup never runs, because no Vite client is present;
12 * - a production build ships none of that lookup's code, because the bundler
13 * removes it with `process.env.NODE_ENV`.
14 *
15 * Cases: webpack 5 production and development builds served as static files,
16 * and Next.js with Turbopack and with webpack, each under `next build` plus
17 * `next start` and under `next dev`. The apps live in the package's ignored
18 * `.cache` directory, inside the workspace, because Next.js infers its project
19 * root from the workspace lockfile. Each app installs the built workspace
20 * packages as published packages and has its own empty TypeScript or
21 * JavaScript config, as a real app does. Otherwise webpack and Turbopack apply
22 * the workspace tsconfig paths, which point at sources.
23 */
24import { spawn } from 'node:child_process'
25import {
26 copyFileSync,
27 cpSync,
28 createReadStream,
29 existsSync,
30 mkdirSync,
31 readFileSync,
32 readdirSync,
33 realpathSync,
34 rmSync,
35 statSync,
36 symlinkSync,
37 writeFileSync,
38} from 'node:fs'
39import { createServer as createHttpServer } from 'node:http'
40import { createRequire } from 'node:module'
41import { dirname, extname, join } from 'node:path'
42import { chromium } from '@playwright/test'
43import webpack from 'webpack'
44import { afterAll, beforeAll, expect, it } from 'vitest'
45import { packageDirectory, probeWorkers } from './packaged-consumer'
46import type { ChildProcess } from 'node:child_process'
47import type { AddressInfo } from 'node:net'
48import type { Browser } from '@playwright/test'
49import type { ProbeGlobal } from './packaged-consumer'
50
51const appsDirectory = join(packageDirectory, `.cache/bundler-consumers`)
52const require = createRequire(import.meta.url)
53const nextBin = require.resolve(`next/dist/bin/next`)
54
55type StartedApp = {
56 url: string
57 close: () => void
58 // The emitted client code, for a production build.
59 productionOutput?: string
60}
61
62// Whether any emitted script contains the Vite dev-server lookup.
63function shipsViteLookup(directory: string): boolean {
64 return (readdirSync(directory, { recursive: true }) as Array<string>).some(
65 (file) =>
66 /\.(c?js)$/.test(file) &&
67 readFileSync(join(directory, file), `utf8`).includes(`/@vite/client`),
68 )
69}
70
71type BundlerCase =
72 | { bundler: `webpack`; mode: `production` | `development` }
73 | {
74 bundler: `next`
75 compiler: `turbopack` | `webpack`
76 server: `build and start` | `dev`
77 }
78
79const cases: Array<BundlerCase> = [
80 { bundler: `webpack`, mode: `production` },
81 { bundler: `webpack`, mode: `development` },
82 ...([`turbopack`, `webpack`] as const).flatMap((compiler) =>
83 ([`build and start`, `dev`] as const).map((server) => ({
84 bundler: `next` as const,
85 compiler,
86 server,
87 })),
88 ),
89]
90
91let browser: Browser
92beforeAll(async () => {
93 rmSync(appsDirectory, { recursive: true, force: true })
94 browser = await chromium.launch({ headless: true })
95})
96afterAll(async () => {
97 await browser.close()
98 rmSync(appsDirectory, { recursive: true, force: true })
99})
100
101// The workspace packages that the app installs, by name.
102const workspacePackages: Record<string, string> = {
103 '@tanstack/browser-db-sqlite-persistence': packageDirectory,
104 '@tanstack/db-sqlite-persistence-core': join(
105 packageDirectory,
106 `../db-sqlite-persistence-core`,
107 ),
108 '@tanstack/db': join(packageDirectory, `../db`),
109 '@tanstack/db-ivm': join(packageDirectory, `../db-ivm`),
110}
111
112/**
113 * Installs the built workspace packages as published packages: their `dist`
114 * and `package.json`, without the workspace's tsconfig files, whose paths
115 * point at sources. Third-party dependencies link to their installed copies.
116 */
117function installAsPublished(appDirectory: string): void {
118 const modules = join(appDirectory, `node_modules`)
119 for (const [name, directory] of Object.entries(workspacePackages)) {
120 const installed = join(modules, name)
121 mkdirSync(installed, { recursive: true })
122 cpSync(join(directory, `dist`), join(installed, `dist`), {
123 recursive: true,
124 })
125 copyFileSync(
126 join(directory, `package.json`),
127 join(installed, `package.json`),
128 )
129 const { dependencies = {} } = JSON.parse(
130 readFileSync(join(directory, `package.json`), `utf8`),
131 ) as { dependencies?: Record<string, string> }
132 for (const dependency of Object.keys(dependencies)) {
133 const link = join(modules, dependency)
134 if (dependency in workspacePackages || existsSync(link)) continue
135 mkdirSync(dirname(link), { recursive: true })
136 symlinkSync(
137 realpathSync(join(directory, `node_modules`, dependency)),
138 link,
139 `dir`,
140 )
141 }
142 }
143}
144
145const openDatabaseModule = `import { openBrowserWASQLiteOPFSDatabase } from '@tanstack/browser-db-sqlite-persistence'
146globalThis.openDatabase = (options) =>
147 openBrowserWASQLiteOPFSDatabase({ databaseName: 'bundler.sqlite', ...options })
148`
149
150const contentTypes: Record<string, string> = {
151 '.html': `text/html`,
152 '.js': `text/javascript`,
153 '.wasm': `application/wasm`,
154 '.map': `application/json`,
155}
156
157async function serveStatic(directory: string): Promise<{
158 url: string
159 close: () => void
160}> {
161 const server = createHttpServer((request, response) => {
162 const pathname = new URL(request.url ?? `/`, `http://x`).pathname
163 const file = join(directory, pathname === `/` ? `index.html` : pathname)
164 if (!existsSync(file) || !statSync(file).isFile()) {
165 response.statusCode = 404
166 response.end()
167 return
168 }
169 response.setHeader(
170 `content-type`,
171 contentTypes[extname(file)] ?? `application/octet-stream`,
172 )
173 createReadStream(file).pipe(response)
174 })
175 await new Promise<void>((resolve) => server.listen(0, `127.0.0.1`, resolve))
176 const { port } = server.address() as AddressInfo
177 return { url: `http://127.0.0.1:${port}/`, close: () => server.close() }
178}
179
180async function startWebpackApp(
181 appDirectory: string,
182 mode: `production` | `development`,
183): Promise<StartedApp> {
184 writeFileSync(join(appDirectory, `tsconfig.json`), `{}`)
185 writeFileSync(join(appDirectory, `main.js`), openDatabaseModule)
186 const outputDirectory = join(appDirectory, `dist`)
187 await new Promise<void>((resolve, reject) => {
188 webpack(
189 {
190 mode,
191 context: appDirectory,
192 entry: `./main.js`,
193 devtool: false,
194 output: { path: outputDirectory, filename: `main.js` },
195 },
196 (error, stats) => {
197 if (error || stats?.hasErrors()) {
198 reject(error ?? new Error(stats!.toString(`errors-only`)))
199 } else {
200 resolve()
201 }
202 },
203 )
204 })
205 writeFileSync(
206 join(outputDirectory, `index.html`),
207 `<script src="/main.js"></script>`,
208 )
209 const app = await serveStatic(outputDirectory)
210 return mode === `production`
211 ? { ...app, productionOutput: outputDirectory }
212 : app
213}
214
215function runNext(
216 appDirectory: string,
217 args: Array<string>,
218): { child: ChildProcess; output: Array<string>; exited: Promise<number> } {
219 const output: Array<string> = []
220 const child = spawn(process.execPath, [nextBin, ...args], {
221 cwd: appDirectory,
222 env: { ...process.env, NEXT_TELEMETRY_DISABLED: `1`, NODE_ENV: undefined },
223 })
224 child.stdout.on(`data`, (chunk: Buffer) => output.push(String(chunk)))
225 child.stderr.on(`data`, (chunk: Buffer) => output.push(String(chunk)))
226 const exited = new Promise<number>((resolve) =>
227 child.on(`exit`, (code) => resolve(code ?? 1)),
228 )
229 return { child, output, exited }
230}
231
232async function freePort(): Promise<number> {
233 const server = createHttpServer()
234 await new Promise<void>((resolve) => server.listen(0, `127.0.0.1`, resolve))
235 const { port } = server.address() as AddressInfo
236 await new Promise<void>((resolve) => server.close(() => resolve()))
237 return port
238}
239
240// Readiness, not timing: the server is ready when its page answers. A server
241// error is final, and the bound only stops a server that never listens.
242async function waitForPage(url: string, server: ChildProcess): Promise<void> {
243 for (let attempt = 0; attempt < 480; attempt++) {
244 if (server.exitCode !== null) throw new Error(`Next.js exited`)
245 try {
246 const response = await fetch(url)
247 if (response.ok) return
248 throw new Error(`${response.status} ${await response.text()}`)
249 } catch (error) {
250 if (!(error instanceof TypeError)) throw error
251 // fetch rejects with a TypeError until the server listens.
252 }
253 await new Promise((resolve) => setTimeout(resolve, 250))
254 }
255 throw new Error(`Next.js did not listen`)
256}
257
258async function startNextApp(
259 appDirectory: string,
260 compiler: `turbopack` | `webpack`,
261 server: `build and start` | `dev`,
262): Promise<StartedApp> {
263 writeFileSync(join(appDirectory, `jsconfig.json`), `{}`)
264 mkdirSync(join(appDirectory, `app`))
265 writeFileSync(
266 join(appDirectory, `app/layout.jsx`),
267 `export default function Layout({ children }) {
268 return <html><body>{children}</body></html>
269}
270`,
271 )
272 writeFileSync(
273 join(appDirectory, `app/page.jsx`),
274 `'use client'
275import { useEffect } from 'react'
276
277export default function Page() {
278 useEffect(() => {
279 import('../open-database.js')
280 }, [])
281 return <p>bundler consumer</p>
282}
283`,
284 )
285 writeFileSync(join(appDirectory, `open-database.js`), openDatabaseModule)
286 const compilerFlag = compiler === `webpack` ? [`--webpack`] : []
287 if (server === `build and start`) {
288 const build = runNext(appDirectory, [`build`, ...compilerFlag])
289 if ((await build.exited) !== 0) {
290 throw new Error(`next build failed\n${build.output.join(``)}`)
291 }
292 }
293 const port = await freePort()
294 const started = runNext(appDirectory, [
295 server === `dev` ? `dev` : `start`,
296 ...(server === `dev` ? compilerFlag : []),
297 `--port`,
298 String(port),
299 `--hostname`,
300 `127.0.0.1`,
301 ])
302 const url = `http://127.0.0.1:${port}/`
303 try {
304 await waitForPage(url, started.child)
305 } catch (error) {
306 started.child.kill()
307 throw new Error(`${String(error)}\n${started.output.join(``)}`)
308 }
309 return {
310 url,
311 close: () => started.child.kill(),
312 ...(server === `build and start`
313 ? { productionOutput: join(appDirectory, `.next/static`) }
314 : {}),
315 }
316}
317
318function describeCase(bundlerCase: BundlerCase): string {
319 return bundlerCase.bundler === `webpack`
320 ? `webpack ${bundlerCase.mode} build`
321 : `Next.js ${bundlerCase.compiler} ${bundlerCase.server}`
322}
323
324it.each(cases.map((bundlerCase) => [describeCase(bundlerCase), bundlerCase]))(
325 `opens packaged SQLite from a %s without asset configuration`,
326 async (name, bundlerCase) => {
327 const appDirectory = join(appsDirectory, name.replaceAll(` `, `-`))
328 mkdirSync(appDirectory, { recursive: true })
329 writeFileSync(
330 join(appDirectory, `package.json`),
331 JSON.stringify({ name: `bundler-consumer`, private: true }),
332 )
333 installAsPublished(appDirectory)
334 const app =
335 bundlerCase.bundler === `webpack`
336 ? await startWebpackApp(appDirectory, bundlerCase.mode)
337 : await startNextApp(
338 appDirectory,
339 bundlerCase.compiler,
340 bundlerCase.server,
341 )
342 const context = await browser.newContext()
343 const page = await context.newPage()
344 const wasmResponses: Array<{ status: number; contentType?: string }> = []
345 const lookupRequests: Array<string> = []
346 const diagnostics: Array<string> = []
347 page.on(`request`, (request) => {
348 if (request.url().includes(`/@id/`)) lookupRequests.push(request.url())
349 })
350 page.on(`response`, (response) => {
351 if (new URL(response.url()).pathname.endsWith(`.wasm`)) {
352 wasmResponses.push({
353 status: response.status(),
354 contentType: response.headers()[`content-type`],
355 })
356 }
357 if (response.status() >= 400) {
358 diagnostics.push(`${response.status()} ${response.url()}`)
359 }
360 })
361 page.on(`pageerror`, (error) => diagnostics.push(error.message))
362 try {
363 await page.addInitScript(probeWorkers, { refuseWorkers: false })
364 await page.goto(app.url)
365 await page.waitForFunction(
366 () => typeof (globalThis as ProbeGlobal).openDatabase === `function`,
367 )
368 const opened = await page.evaluate(async () => {
369 const probe = globalThis as ProbeGlobal
370 const database = await probe.openDatabase({ timeoutMs: 0 })
371 try {
372 return {
373 rows: await database.execute(`SELECT 42 AS value`),
374 workerTypes: probe.workerTypes,
375 }
376 } finally {
377 await database.close?.()
378 }
379 })
380 expect({
381 ...opened,
382 wasmResponses: wasmResponses.map(({ status, contentType }) => ({
383 status,
384 wasm: contentType?.includes(`application/wasm`) ?? false,
385 })),
386 lookupRequests,
387 ...(app.productionOutput
388 ? { shipsViteLookup: shipsViteLookup(app.productionOutput) }
389 : {}),
390 }).toEqual({
391 rows: [{ value: 42 }],
392 workerTypes: [`classic`],
393 wasmResponses: [{ status: 200, wasm: true }],
394 lookupRequests: [],
395 ...(app.productionOutput ? { shipsViteLookup: false } : {}),
396 })
397 } catch (error) {
398 throw new Error(`${String(error)}\n${diagnostics.join(`\n`)}`, {
399 cause: error,
400 })
401 } finally {
402 await context.close()
403 app.close()
404 }
405 },
406 300_000,
407)