diff --git a/import-meta.d.ts b/import-meta.d.ts index 0e851a1c1..76569f8ce 100644 --- a/import-meta.d.ts +++ b/import-meta.d.ts @@ -12,7 +12,7 @@ declare global { readonly content: { /** Resolved `content.compatibilityVersion`. With `3`, v3 query/search composables are enabled and sql-query + FTS plugins are injected into the Content instance. */ readonly compatibilityVersion: 3 | 4 - /** Names of the content instances, defined for `app/content.ts` in the app build. */ + /** Names of the content instances, defined for `app/content.ts` and `app/content.worker.ts` in the app build. */ readonly sources: string[] /** Resolved `content.build.markdown.highlight` options, `false` when highlighting is disabled. */ readonly highlight: false | { themes: { light?: string, dark?: string }, langs: string[] } diff --git a/package.json b/package.json index d2688c8d5..3f82d97d4 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "./v3": "./dist/runtime/v3/index.js", "./content": "./dist/runtime/server/content.js", "./app": "./dist/runtime/client-content/app.js", + "./worker": "./dist/runtime/client-content/worker.js", "./utils": "./dist/runtime/utils/index.js", "./server": "./dist/runtime/v3/composables.server.js" }, @@ -56,7 +57,7 @@ "@nuxt/kit": "^4.7.0", "@sqlite.org/sqlite-wasm": "3.54.1-build1", "comark": "https://pkg.pr.new/comark@0b5d53f", - "comark-content": "^0.6.2", + "comark-content": "https://pkg.pr.new/comark-content@cf8a861", "defu": "^6.1.7", "forges": "^0.3.2", "jiti": "^2.7.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c5b8566a4..40afbf405 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -185,6 +185,7 @@ overrides: '@nuxt/content': link:. postcss-merge-rules@9>cssnano-utils: ^8.2.0 comark: https://pkg.pr.new/comark@0b5d53f + comark-content: https://pkg.pr.new/comark-content@cf8a861 importers: @@ -203,8 +204,8 @@ importers: specifier: https://pkg.pr.new/comark@0b5d53f version: https://pkg.pr.new/comark@0b5d53f(shiki@4.6.0) comark-content: - specifier: ^0.6.2 - version: 0.6.2(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) + specifier: https://pkg.pr.new/comark-content@cf8a861 + version: https://pkg.pr.new/comark-content@cf8a861(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) defu: specifier: ^6.1.7 version: 6.1.7 @@ -297,8 +298,8 @@ importers: specifier: link:../.. version: link:../.. comark-content: - specifier: ^0.6.2 - version: 0.6.2(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) + specifier: https://pkg.pr.new/comark-content@cf8a861 + version: https://pkg.pr.new/comark-content@cf8a861(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) nuxt: specifier: ^4.7.0 version: 4.7.0(58168c37520f52aa720a3fd946e5719d) @@ -3703,8 +3704,9 @@ packages: colortranslator@5.0.0: resolution: {integrity: sha512-Z3UPUKasUVDFCDYAjP2fmlVRf1jFHJv1izAmPjiOa0OCIw1W7iC8PZ2GsoDa8uZv+mKyWopxxStT9q05+27h7w==} - comark-content@0.6.2: - resolution: {integrity: sha512-LqWmTQYHCHwlWolCVad0ErzBWNiJxQdWRC8m5+z/htOB6YrVpuIScCicoMh3Yk9tPnNWQyVQd5JL+sm9acqUFA==} + comark-content@https://pkg.pr.new/comark-content@cf8a861: + resolution: {integrity: sha512-E+7Vm1t8zKYeRo8pYZJHDbQLa0fFUHHt4MXBLEJ8WdB80uI/3OtoY4HZlJrXxyLicepLY/G4OrB1BVSkhr6Lhg==, tarball: https://pkg.pr.new/comark-content@cf8a861} + version: 0.6.3 hasBin: true peerDependencies: forges: ^0.3.0 @@ -11045,7 +11047,7 @@ snapshots: colortranslator@5.0.0: {} - comark-content@0.6.2(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))): + comark-content@https://pkg.pr.new/comark-content@cf8a861(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))): dependencies: comark: https://pkg.pr.new/comark@0b5d53f(shiki@4.6.0) hookable: 6.1.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index e47dc07e3..caff8d5e8 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -11,8 +11,10 @@ overrides: "postcss-merge-rules@9>cssnano-utils": ^8.2.0 # `external-links` plugin from comarkdown/comark#599, until it's released. One copy for every dependent. comark: https://pkg.pr.new/comark@0b5d53f + # `comark-content/worker` and `buildSearchIndex()` from comarkdown/comark-content#172, until it's released. + comark-content: https://pkg.pr.new/comark-content@cf8a861 -# The `comark` override above is a URL, which pnpm blocks below the top level. Remove both once comark is released. +# The `comark` and `comark-content` overrides above are URLs, which pnpm blocks below the top level. Remove this once both are released. blockExoticSubdeps: false allowBuilds: diff --git a/src/module.ts b/src/module.ts index cb7763cf0..ce3713982 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,12 +1,11 @@ import { comarkContent, contentHub, generateSourceTypes, isParsedSource, readArtifact } from 'comark-content' import defu from 'defu' import type { CacheArtifact, ContentSource, Manifest, AnyComarkContent, ContentHub, ParsedSnapshot, TypegenFieldContext } from 'comark-content' -import { defineNuxtModule, createResolver, addServerImports, addServerHandler, addImports, addComponent, addPlugin, addTemplate, addPrerenderRoutes, addDevServerHandler, addTypeTemplate, addServerTemplate, useLogger } from '@nuxt/kit' -import { existsSync } from 'node:fs' +import { defineNuxtModule, createResolver, addServerImports, addServerHandler, addImports, addComponent, addPlugin, addTemplate, addPrerenderRoutes, addDevServerHandler, addTypeTemplate, addServerTemplate, resolvePath, useLogger } from '@nuxt/kit' import { mkdir, writeFile } from 'node:fs/promises' import type { Nuxt } from 'nuxt/schema' import type { MediaMethods } from 'comark-content/plugins/media' -import { importContent, resolveContentEntry } from './utils/config' +import { importContent, resolveContentEntry, resolveLayerAppFile } from './utils/config' import { highlightTypesTemplate, importMetaTypesTemplate } from './utils/templates' import { highlightStylesTemplate, highlightTemplate, resolveHighlightOptions, type ResolvedHighlightOptions } from './utils/highlight' import { resolveTocOptions, type ResolvedTocOptions } from './utils/toc' @@ -17,7 +16,6 @@ import { v3ServerPlugins } from './runtime/v3/content-plugins.server' import { resolveContentConfigCollections, type ResolvedContentCollections } from './runtime/v3/content-config' import { HMR_REMOVE_EVENT, HMR_UPDATE_EVENT, type ContentHmrRemove, type ContentHmrUpdate } from './runtime/utils/hmr' import { fileURLToPath } from 'node:url' -import { join } from 'node:path' // `ContentHub`: its `query` is invariant in T, so a hub over a mutable array isn't a `ContentHub`. type ContentSurface = AnyComarkContent | ContentHub @@ -50,7 +48,7 @@ export default defineNuxtModule({ } /** - * Entry files + * Entry files, from the app then its layers */ const entry = resolveContentEntry(nuxt, options.compatibilityVersion!) const serverContentPath = entry.type === 'server' @@ -59,12 +57,13 @@ export default defineNuxtModule({ ? resolve('./runtime/server/internal/content-config') : resolve('./runtime/server/internal/fallback-content') // `app/content.ts` configures the browser instance, as `server/content.ts` does the server one. - let appContentPath: string | undefined = join(nuxt.options.srcDir, 'content') - if (!existsSync(`${appContentPath}.ts`)) appContentPath = undefined + let appContentPath = resolveLayerAppFile(nuxt, 'content.ts')?.slice(0, -'.ts'.length) if (appContentPath && (options.mode !== 'hybrid' || options.compatibilityVersion !== 4)) { - logger.warn('`app/content.ts` is only used with `mode: \'hybrid\'` and `compatibilityVersion: 4`, ignoring it.') + logger.warn('`app/content.ts` is only used with `mode: \'hybrid\'` and `compatibilityVersion: 4`, ignoring it. Use `app/content.worker.ts` for content in the browser in server-only mode.') appContentPath = undefined } + // `app/content.worker.ts` runs instances in a web worker, hydrated from the public snapshots. + const workerPath = resolveLayerAppFile(nuxt, 'content.worker.ts') /** * Build config @@ -87,6 +86,7 @@ export default defineNuxtModule({ '@nuxt/content/content': resolve('./runtime/server/content'), }) nuxt.options.alias['@nuxt/content/app'] = resolve('./runtime/client-content/app') + nuxt.options.alias['@nuxt/content/worker'] = resolve('./runtime/client-content/worker') nuxt.options.nitro.replace = defu(nuxt.options.nitro.replace, { 'import.meta.rootDir': JSON.stringify(nuxt.options.rootDir), @@ -109,7 +109,7 @@ export default defineNuxtModule({ /** * Server */ - const content = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks) + const content = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks, !!workerPath) // A build reads every document once, shared by the types and components templates. const readContent = content && !nuxt.options.dev && !nuxt.options._prepare ? createContentReader(content) : undefined @@ -119,7 +119,7 @@ export default defineNuxtModule({ /** * Browser */ - if (appContentPath) { + if (appContentPath || workerPath) { // `createNuxtContent()` is synchronous, so it can't fetch the manifest to know the instances. nuxt.options.vite.define = defu(nuxt.options.vite.define, { 'import.meta.content.sources': JSON.stringify(content ? resolveInstanceNames(content) : []), @@ -129,6 +129,9 @@ export default defineNuxtModule({ addImports({ name: 'content', from: clientContentPath }) // A dynamic import deadlocks the client's top-level `await` on Nuxt 4.7; the stub keeps sqlite out of v4 bundles. nuxt.options.alias['#content-wasm-plugins'] = resolve(`./runtime/v3/content-plugins.${options.compatibilityVersion === 3 ? 'wasm' : 'stub'}`) + if (workerPath) { + await setupWorker(workerPath, content ? resolveInstanceNames(content) : [], nuxt) + } /** * Components @@ -222,6 +225,66 @@ export default defineNuxtModule({ }, }) +/** + * Bundle `app/content.worker.ts` into a web worker, which Vite builds from a generated entry as its own chunk. + * Only the worker imports the file, so its plugins never reach the app's bundle. + */ +async function setupWorker(workerPath: string, names: string[], nuxt: Nuxt) { + const { resolve } = createResolver(import.meta.url) + const runtime = await resolvePath(resolve('./runtime/client-content/worker')) + // Written to disk: Vite bundles workers without Nuxt's plugins, which serve the other templates from memory. + const entry = addTemplate({ + // Names the worker's chunk, `content-worker-.js`. + filename: 'content/content-worker.mjs', + write: true, + getContents: () => [ + `import definition from ${JSON.stringify(workerPath)}`, + `import { startNuxtContentWorker } from ${JSON.stringify(runtime)}`, + // The `app.baseURL` of the build: a base set at runtime with `NUXT_APP_BASE_URL` isn't supported. + `startNuxtContentWorker(definition, ${JSON.stringify(names)}, ${JSON.stringify(nuxt.options.app.baseURL)})`, + ].join('\n') + '\n', + }) + nuxt.options.alias['@nuxt/content/worker-entry'] = entry.dst + // Vite lists the worker as an asset of the app's entry, which Nuxt would preload on every page. + nuxt.hook('build:manifest', (manifest) => { + for (const chunk of Object.values(manifest)) { + if (/^(?:.*\/)?content-worker-[\w-]+\.js$/.test(chunk.file)) { + chunk.preload = false + chunk.prefetch = false + } + } + }) + addImports({ name: 'useNuxtContentWorker', from: resolve('./runtime/client-content/worker-client') }) + + nuxt.options.vite.optimizeDeps = defu(nuxt.options.vite.optimizeDeps, { + // Pre-bundled, it can't find its `sqlite3.wasm` next to it. + exclude: ['@sqlite.org/sqlite-wasm'], + }) + const workerPlugins = nuxt.options.vite.worker?.plugins + nuxt.options.vite.worker = { + ...nuxt.options.vite.worker, + // Vite flattens nested and pending plugin lists, so the app's are kept as one entry. + plugins: () => [workerPlugins?.(), sqliteWorkerFilesPlugin()], + } +} + +/** + * sqlite-wasm references its Worker1 API and OPFS helper with `new URL(…, import.meta.url)`, so Vite emits both. + * An in-memory database loads neither, so they throw instead; sqlite-wasm catches the failed OPFS install. + * TODO: use the plugin from comark-content once it ships there. + */ +function sqliteWorkerFilesPlugin() { + const files = /new URL\("(sqlite3-worker1\.mjs|sqlite3-opfs-async-proxy\.js)", import\.meta\.url\)/ + return { + name: 'nuxt-content:sqlite-worker-files', + enforce: 'pre' as const, + transform: { + filter: { id: /[\\/]@sqlite\.org[\\/]sqlite-wasm[\\/]/, code: files }, + handler: (code: string) => code.replace(new RegExp(files, 'g'), (_, file: string) => `(() => { throw new Error(${JSON.stringify(`\`${file}\` isn't bundled with the Nuxt Content worker.`)}) })()`), + }, + } +} + function setupHighlight(highlight: ResolvedHighlightOptions | false, nuxt: Nuxt) { const { resolve } = createResolver(import.meta.url) @@ -445,7 +508,7 @@ async function cloneSurface( }) } -async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[]): Promise { +async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[], publicSnapshots: boolean): Promise { const { resolve } = createResolver(import.meta.url) const imported = await importContent(nuxt.options.rootDir, contentPath, { @@ -479,8 +542,8 @@ async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOpti nitro.options.serverAssets.push({ baseName: 'content', dir }) nitro.hooks.hook('prerender:generate', async (route) => { if (!route.route.startsWith('/__nuxt_content')) return - // Server-only mode keeps them private. - if (options.mode === 'server-only') { + // Server-only mode keeps them private, except the snapshots `app/content.worker.ts` hydrates from. + if (options.mode === 'server-only' && !(publicSnapshots && route.route.startsWith('/__nuxt_content/snapshot/'))) { route.skip = true } diff --git a/src/runtime/client-content/worker-client.ts b/src/runtime/client-content/worker-client.ts new file mode 100644 index 000000000..ed959b43e --- /dev/null +++ b/src/runtime/client-content/worker-client.ts @@ -0,0 +1,137 @@ +import { readonly, shallowRef, toValue, watch, type MaybeRefOrGetter, type Ref } from 'vue' +import type { SearchOptions, SearchResult } from 'comark-content' +import { createContentClient, type ContentClient, type ContentFetch } from 'comark-content/client' +import searchClient from 'comark-content/plugins/sqlite-full-text-search/client' +import { connectContentWorker, type ContentWorker } from 'comark-content/worker' +import { HMR_REMOVE_EVENT, HMR_UPDATE_EVENT } from '../utils/hmr' + +/** Matches the `searchStatus` prop of Nuxt UI's ``. */ +export type NuxtContentWorkerStatus = 'idle' | 'loading' | 'ready' | 'error' + +export interface NuxtContentWorkerSearchOptions extends SearchOptions { + /** Instances to search. Defaults to the instances of `useNuxtContentWorker()`. */ + instances?: string[] +} + +export interface UseNuxtContentWorkerOptions { + /** + * Instances to load and read, such as the current locale's. Only their snapshots are downloaded. + * When it changes after `warmup()`, the new instances are loaded. Every instance by default. + */ + instances?: MaybeRefOrGetter +} + +export interface NuxtContentWorker { + /** `ready` once the snapshots of the instances are loaded and their search index is built. */ + status: Readonly> + /** Start the worker and load the instances in the background, such as from `onNuxtReady()`. Safe to call again. */ + warmup: () => Promise + /** Full-text search in the worker. Takes the `search` prop of ``. */ + search: (query: string, opts?: NuxtContentWorkerSearchOptions) => Promise + /** A document of the instances, by public path. */ + get: ContentClient['get'] + /** The documents of the given instances, the composable's by default, without their bodies. */ + list: ContentClient['list'] +} + +/** Instances loaded or loading in the worker, shared by every `useNuxtContentWorker()`. */ +const warmed = new Map>() +let worker: ContentWorker | undefined + +// The worker answers `handler()` requests, so the client is the one `server-only.ts` uses over HTTP. +const clientOptions = { + basePath: '/__nuxt_content', + fetch: ((url, opts) => worker!.fetch(url, opts)) as ContentFetch, + plugins: [searchClient()], +} +const hub = createContentClient(clientOptions) +const bound = new Map() +// Sends `?instance=`, so a read only loads that instance. +const client = (name: string) => bound.get(name) ?? bound.set(name, createContentClient(name, clientOptions)).get(name)! + +/** Created on the first call, so a page that never reads it doesn't download the worker. */ +function start() { + if (worker) return + worker = connectContentWorker( + // Vite bundles the generated entry as its own chunk. A `#` alias would be read as a URL hash. + new Worker(new URL('@nuxt/content/worker-entry', import.meta.url), { type: 'module', name: 'nuxt-content' }), + ) + + if (import.meta.hot) { + import.meta.hot.on(HMR_UPDATE_EVENT, payload => worker!.update(payload)) + import.meta.hot.on(HMR_REMOVE_EVENT, payload => worker!.remove(payload)) + } +} + +function warmOne(name: string) { + let warming = warmed.get(name) + if (!warming) { + // The next call tries again. + warming = hub.buildSearchIndex({ instances: [name] }).catch((error) => { + warmed.delete(name) + throw error + }) + warmed.set(name, warming) + } + return warming +} + +/** + * The content instances of `app/content.worker.ts`, running in a web worker. + * Reads and search there don't need a server, so they work on a static host. + */ +export function useNuxtContentWorker(options: UseNuxtContentWorkerOptions = {}): NuxtContentWorker { + const status = shallowRef('idle') + // A plain copy: `postMessage()` can't clone a reactive array. + const names = () => [...(toValue(options.instances) ?? import.meta.content.sources)] + let started = false + let current: Promise | undefined + + function warmup() { + if (import.meta.server) return Promise.resolve() + start() + started = true + const loading = Promise.all(names().map(warmOne)).then(() => {}) + current = loading + status.value = 'loading' + // Only the latest instances decide the status: a locale switch makes the previous load stale. + loading.then( + () => current === loading && (status.value = 'ready'), + () => current === loading && (status.value = 'error'), + ) + return loading + } + + if (import.meta.client) { + watch(names, () => started && warmup().catch(() => {})) + } + + function ready() { + if (import.meta.server) throw new Error('`useNuxtContentWorker()` reads in the browser only.') + // Keeps `status` accurate; the worker loads the instances on the first read anyway. + warmup().catch(() => {}) + } + + return { + status: readonly(status), + warmup, + search: async (query, opts = {}) => { + if (import.meta.server) return [] + ready() + return hub.search(query, { ...opts, instances: opts.instances ?? names() }) + }, + // A hub `get` would load every instance to find the path. + get: (async (path: string) => { + ready() + for (const name of names()) { + const doc = await client(name).get(path) + if (doc) return doc + } + return null + }) as ContentClient['get'], + list: ((list?: string[]) => { + ready() + return hub.list(list ?? names()) + }) as ContentClient['list'], + } +} diff --git a/src/runtime/client-content/worker.ts b/src/runtime/client-content/worker.ts new file mode 100644 index 000000000..fa3058f1f --- /dev/null +++ b/src/runtime/client-content/worker.ts @@ -0,0 +1,35 @@ +import { comarkContent, contentHub } from 'comark-content/runtime' +import snapshot from 'comark-content/sources/snapshot' +import { serveContentWorker } from 'comark-content/worker' +import type { ContentPlugin } from 'comark-content' + +export { default as sqliteFullTextSearch } from 'comark-content/plugins/sqlite-full-text-search' +export { default as sqliteWasm } from 'comark-content/database/sqlite-wasm' + +export interface NuxtContentWorkerOptions { + /** Plugins of every instance in the worker, hydrated from the prerendered snapshots. Pass one database to rank a hub as one index. */ + plugins?: ContentPlugin[] +} + +/** + * Declare the content instances that run in a web worker, in `app/content.worker.ts`. + * The file is only evaluated in the worker, so its plugins (and sqlite-wasm) stay out of the app's bundle. + */ +export function createNuxtContentWorker(options: T): T { + return options +} + +/** + * Serve the instances of `app/content.worker.ts` to `useNuxtContentWorker()`, from the generated worker entry. + * Each instance loads its prerendered snapshot on its first read, so only the instances read are downloaded. + * @internal + */ +export function startNuxtContentWorker(options: NuxtContentWorkerOptions, names: string[], baseURL: string) { + serveContentWorker(() => contentHub( + names.map(name => comarkContent(name, { + source: snapshot(`${baseURL.replace(/\/?$/, '/')}__nuxt_content/snapshot/${name}.json`), + plugins: options.plugins, + })), + { basePath: '/__nuxt_content' }, + )) +} diff --git a/src/runtime/v3/composables.ts b/src/runtime/v3/composables.ts index 7421adcda..4a5170d85 100644 --- a/src/runtime/v3/composables.ts +++ b/src/runtime/v3/composables.ts @@ -25,6 +25,7 @@ import type { SourceQueryBuilder, } from 'comark-content/database/utils/query' import type { SqlQueryMethods } from 'comark-content/plugins/sql-query' +import type { SqliteFullTextSearchHubMethods } from 'comark-content/plugins/sqlite-full-text-search' import { content } from '#imports' type QueryableContent = (ComarkContent | ContentHub) & { @@ -131,7 +132,7 @@ export function useSearchCollection( } // Hub search takes (query, { instances }). if ('from' in searchable && typeof (searchable as ContentHub).from === 'function') { - return (searchable as ContentHub).search(query, { ...searchOpts, instances: collections }) + return (searchable as unknown as SqliteFullTextSearchHubMethods).search(query, { ...searchOpts, instances: collections }) } // Single-instance search takes (query, opts) only. return searchable.search(query, searchOpts) diff --git a/src/utils/config.ts b/src/utils/config.ts index 2cb8e38e8..101b4e896 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -74,6 +74,11 @@ export type ContentEntry = { type: 'fallback' } +/** The first `app/`, from the project then its layers by priority. */ +export function resolveLayerAppFile(nuxt: Nuxt, file: string): string | undefined { + return getLayerDirectories(nuxt).map(dirs => join(dirs.app, file)).find(path => existsSync(path)) +} + /** * The first `server/content.ts`, from the project then its layers by priority. * Without one, the v3 `content.config.ts` of every layer, which `compatibilityVersion: 4` ignores. diff --git a/src/utils/templates.ts b/src/utils/templates.ts index 1f1e9bcff..70a93f08a 100644 --- a/src/utils/templates.ts +++ b/src/utils/templates.ts @@ -13,7 +13,7 @@ readonly rootDir: string readonly content: { /** Resolved \`content.compatibilityVersion\`. With \`3\`, v3 query/search composables are enabled and sql-query + FTS plugins are injected into the Content instance. */ readonly compatibilityVersion: 3 | 4 -/** Names of the content instances, defined for \`app/content.ts\` in the app build. */ +/** Names of the content instances, defined for \`app/content.ts\` and \`app/content.worker.ts\` in the app build. */ readonly sources: string[] /** Collections resolved at build time from the v3 \`content.config.ts\` of every layer. */ readonly collections: import('@nuxt/content/v3').ResolvedContentCollections diff --git a/test/app-content.test.ts b/test/app-content.test.ts index b9d61ee0c..dc18917d3 100644 --- a/test/app-content.test.ts +++ b/test/app-content.test.ts @@ -10,7 +10,7 @@ describe('app/content.ts', async () => { expect(html).toContain('The intro page.') }) - it('adds its plugins to every instance of the browser hub that `content` reads', async () => { + it('adds its plugins to every instance of the browser hub that `content` reads, over a layer\'s file', async () => { const page = await createPage('/') expect(JSON.parse(await page.locator('#probes').textContent() ?? '')).toEqual({ docs: ['project'], blog: ['project'] }) await page.close() diff --git a/test/fixtures/app-content/base-layer/app/content.ts b/test/fixtures/app-content/base-layer/app/content.ts new file mode 100644 index 000000000..6b24027e4 --- /dev/null +++ b/test/fixtures/app-content/base-layer/app/content.ts @@ -0,0 +1,13 @@ +import { createNuxtContent } from '@nuxt/content/app' +import type { ContentPlugin } from 'comark-content' + +// Shadowed by the project's `app/content.ts`. +const layer: ContentPlugin = { + name: 'probe-layer', + setup(content) { + const target = content as unknown as { probes?: string[] } + target.probes = [...(target.probes ?? []), 'layer'] + }, +} + +export const content = createNuxtContent({ plugins: [layer] }) diff --git a/test/fixtures/app-content/base-layer/nuxt.config.ts b/test/fixtures/app-content/base-layer/nuxt.config.ts new file mode 100644 index 000000000..268da7f8c --- /dev/null +++ b/test/fixtures/app-content/base-layer/nuxt.config.ts @@ -0,0 +1 @@ +export default defineNuxtConfig({}) diff --git a/test/fixtures/app-content/nuxt.config.ts b/test/fixtures/app-content/nuxt.config.ts index 7f2d139f7..552e39773 100644 --- a/test/fixtures/app-content/nuxt.config.ts +++ b/test/fixtures/app-content/nuxt.config.ts @@ -1,6 +1,8 @@ import MyModule from '../../../src/module' export default defineNuxtConfig({ + // Its own `app/content.ts` is shadowed by the project's. + extends: ['./base-layer'], modules: [ MyModule, ], diff --git a/test/fixtures/worker-search/app/app.vue b/test/fixtures/worker-search/app/app.vue new file mode 100644 index 000000000..1a3a63b72 --- /dev/null +++ b/test/fixtures/worker-search/app/app.vue @@ -0,0 +1,22 @@ + + + diff --git a/test/fixtures/worker-search/content/blog/hello.md b/test/fixtures/worker-search/content/blog/hello.md new file mode 100644 index 000000000..e4f221f09 --- /dev/null +++ b/test/fixtures/worker-search/content/blog/hello.md @@ -0,0 +1,3 @@ +# Hello + +A wombat wrote this post. diff --git a/test/fixtures/worker-search/content/docs/en/install.md b/test/fixtures/worker-search/content/docs/en/install.md new file mode 100644 index 000000000..5bae916b0 --- /dev/null +++ b/test/fixtures/worker-search/content/docs/en/install.md @@ -0,0 +1,7 @@ +# Install + +Add the module to your app. + +## Configure the worker + +The wombat runs the search in a web worker. diff --git a/test/fixtures/worker-search/content/docs/fr/install.md b/test/fixtures/worker-search/content/docs/fr/install.md new file mode 100644 index 000000000..ee6afc9c0 --- /dev/null +++ b/test/fixtures/worker-search/content/docs/fr/install.md @@ -0,0 +1,7 @@ +# Installation + +Ajoutez le module. + +## Configurer le worker + +Le wombat lance la recherche dans un web worker. diff --git a/test/fixtures/worker-search/nuxt.config.ts b/test/fixtures/worker-search/nuxt.config.ts new file mode 100644 index 000000000..e967cc6f8 --- /dev/null +++ b/test/fixtures/worker-search/nuxt.config.ts @@ -0,0 +1,20 @@ +import MyModule from '../../../src/module' + +export default defineNuxtConfig({ + // Ships `app/content.worker.ts`, as Docus would. + extends: ['./search-layer'], + modules: [ + MyModule, + ], + // As for an installed module: Nuxt doesn't auto-import in files under `node_modules`. + imports: { transform: { exclude: [/[\\/]src[\\/]runtime[\\/]/] } }, + content: { + compatibilityVersion: 4, + mode: 'server-only', + }, + nitro: { + // Only `.output/public`, served without a server. + preset: 'static', + imports: { exclude: [/\/src\/runtime\//] }, + }, +}) diff --git a/test/fixtures/worker-search/package.json b/test/fixtures/worker-search/package.json new file mode 100644 index 000000000..3e87fd082 --- /dev/null +++ b/test/fixtures/worker-search/package.json @@ -0,0 +1,5 @@ +{ + "private": true, + "name": "worker-search", + "type": "module" +} diff --git a/test/fixtures/worker-search/search-layer/app/content.worker.ts b/test/fixtures/worker-search/search-layer/app/content.worker.ts new file mode 100644 index 000000000..5bf693653 --- /dev/null +++ b/test/fixtures/worker-search/search-layer/app/content.worker.ts @@ -0,0 +1,6 @@ +import { createNuxtContentWorker, sqliteFullTextSearch, sqliteWasm } from '@nuxt/content/worker' + +// One database for every instance, so a search across them is ranked as one index. +export default createNuxtContentWorker({ + plugins: [sqliteFullTextSearch({ database: sqliteWasm() })], +}) diff --git a/test/fixtures/worker-search/search-layer/nuxt.config.ts b/test/fixtures/worker-search/search-layer/nuxt.config.ts new file mode 100644 index 000000000..268da7f8c --- /dev/null +++ b/test/fixtures/worker-search/search-layer/nuxt.config.ts @@ -0,0 +1 @@ +export default defineNuxtConfig({}) diff --git a/test/fixtures/worker-search/server/content.ts b/test/fixtures/worker-search/server/content.ts new file mode 100644 index 000000000..806c701a6 --- /dev/null +++ b/test/fixtures/worker-search/server/content.ts @@ -0,0 +1,10 @@ +import { createNuxtContent } from '@nuxt/content/content' +import fs from 'comark-content/sources/fs' + +export const content = createNuxtContent({ + mode: 'server-only', + sources: { + docs: fs('content/docs', { cwd: import.meta.rootDir, prefix: '/docs' }), + blog: fs('content/blog', { cwd: import.meta.rootDir, prefix: '/blog' }), + }, +}) diff --git a/test/layer-sources.test.ts b/test/layer-sources.test.ts index 06f8834aa..6e412c33d 100644 --- a/test/layer-sources.test.ts +++ b/test/layer-sources.test.ts @@ -1,5 +1,5 @@ import { spawn, type ChildProcess } from 'node:child_process' -import { cpSync, readFileSync, rmSync } from 'node:fs' +import { cpSync, existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, it, expect } from 'vitest' @@ -65,6 +65,11 @@ describe('sources provided by a layer', async () => { expect(page('fr/guide')).toContain('Page en français.') }) + // Only `app/content.worker.ts` reads them in the browser. + it('keeps the snapshots out of the public files without a content worker', () => { + expect(existsSync(join(useTestContext().nuxt!.options.nitro.output!.dir!, 'static/__nuxt_content'))).toBe(false) + }) + it('types the layer\'s source with its declared schema', () => { const types = readFileSync(join(useTestContext().nuxt!.options.buildDir, 'content/types.d.ts'), 'utf8') // `target` only comes from the schema: no document sets it. diff --git a/test/worker-search.test.ts b/test/worker-search.test.ts new file mode 100644 index 000000000..3f91263f2 --- /dev/null +++ b/test/worker-search.test.ts @@ -0,0 +1,136 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { createServer, type Server } from 'node:http' +import { extname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { chromium, type Browser } from 'playwright-core' +import { setup, useTestContext } from '@nuxt/test-utils/e2e' + +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.mjs': 'text/javascript', + '.css': 'text/css', + '.json': 'application/json', + '.wasm': 'application/wasm', +} + +/** A static host: files from `dir`, `index.html` for directories, 404 for anything else. */ +function serveStatic(dir: string) { + return createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url!, 'http://localhost').pathname) + for (const file of [join(dir, pathname), join(dir, pathname, 'index.html')]) { + try { + const body = await readFile(file) + res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' }) + return res.end(body) + } + catch { + // Not this candidate. + } + } + res.writeHead(404).end() + }) +} + +type SearchResult = { id: string, source: string, title: string, content: string } + +describe('search in a web worker, on a static host', async () => { + await setup({ + rootDir: fileURLToPath(new URL('./fixtures/worker-search', import.meta.url)), + // Served below from `.output/public`, without Nitro. + server: false, + }) + + let publicDir: string + let server: Server + let url: string + let browser: Browser + + beforeAll(async () => { + publicDir = join(useTestContext().nuxt!.options.nitro.output!.dir!, 'public') + server = serveStatic(publicDir) + await new Promise(resolve => server.listen(0, resolve)) + url = `http://localhost:${(server.address() as { port: number }).port}` + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + server?.close() + }) + + it('publishes the snapshots the worker hydrates from', () => { + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/docs.json'))).toBe(true) + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/blog.json'))).toBe(true) + }) + + // sqlite-wasm references its own worker API and OPFS helper, which an in-memory database never loads. + it('only emits the sqlite files the worker loads', () => { + const files = readdirSync(join(publicDir, '_nuxt')) + expect(files.filter(file => file.startsWith('sqlite3'))).toEqual([expect.stringMatching(/^sqlite3\..+\.wasm$/)]) + }) + + it('doesn\'t preload the worker with the page', () => { + const html = readFileSync(join(publicDir, 'index.html'), 'utf8') + expect(html).toContain('/_nuxt/') + expect(html).not.toContain('content-worker') + }) + + it('warms up after the page is ready and searches the prerendered content in the worker', { timeout: 60_000 }, async () => { + const page = await browser.newPage() + const errors: string[] = [] + page.on('pageerror', error => errors.push(error.message)) + await page.goto(url) + await page.getByText('The wombat runs the search in a web worker.').waitFor() + // Nobody searched yet: `onNuxtReady()` started the hydration. + await page.locator('#status', { hasText: 'ready' }).waitFor({ timeout: 30_000 }) + + type Worker = { search: (q: string, o?: object) => Promise, get: (key: string) => Promise<{ meta: { title: string } } | null>, instances: { value: string[] } } + const search = (query: string, opts?: object) => page.evaluate( + ([query, opts]) => (window as unknown as { __worker: Worker }).__worker.search(query as string, opts as object), + [query, opts] as const, + ) + const [worker] = page.workers() + const snapshots = () => worker!.evaluate(() => performance.getEntriesByType('resource').map(entry => new URL(entry.name).pathname).filter(path => path.startsWith('/__nuxt_content/'))) + + // Only the selected instance, as Docus selects the current locale's source. + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json']) + const docs = await search('wombat') + expect(docs.map(result => result.id).sort()).toEqual(['/docs/en/install#configure-the-worker', '/docs/fr/install#configurer-le-worker']) + expect(docs.find(result => result.id === '/docs/en/install#configure-the-worker')).toMatchObject({ + source: 'docs', + title: 'Configure the worker', + content: 'The wombat runs the search in a web worker.', + }) + expect(await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.get('/docs/fr/install').then(doc => doc?.meta.title))).toBe('Installation') + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json']) + + // Selecting more instances loads them, and one shared database ranks them in a single query. + await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.instances.value = ['docs', 'blog']) + await page.locator('#status', { hasText: 'ready' }).waitFor() + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json', '/__nuxt_content/snapshot/blog.json']) + const all = await search('wombat') + expect(all.map(result => result.id).sort()).toEqual(['/blog/hello#hello', '/docs/en/install#configure-the-worker', '/docs/fr/install#configurer-le-worker']) + + // sqlite and the snapshots only ever load in the worker. + const mainResources = await page.evaluate(() => performance.getEntriesByType('resource').map(entry => entry.name)) + expect(mainResources.filter(name => /\.wasm|__nuxt_content/.test(name))).toEqual([]) + expect(await page.evaluate(() => 'sqlite3ApiConfig' in globalThis)).toBe(false) + const workerResources = await worker!.evaluate(() => performance.getEntriesByType('resource').map(entry => entry.name)) + expect(workerResources.some(path => path.endsWith('.wasm'))).toBe(true) + + // Nor in the scripts the page itself runs: only the worker's own script has it. + const scripts = mainResources.filter(name => name.endsWith('.js') && name !== worker!.url()) + expect(scripts.length).toBeGreaterThan(0) + const withSqlite = [] + for (const script of scripts) { + if ((await fetch(script).then(response => response.text())).includes('sqlite3')) withSqlite.push(script) + } + expect(withSqlite).toEqual([]) + + expect(errors).toEqual([]) + await page.close() + }) +})