diff --git a/README.md b/README.md index 463e6a8..b03b54f 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ export default { } ``` -The copied files keep the names PDF.js asks for, so an upgrade doesn't rename them. If your host caches the build's asset folder as `immutable`, as SvelteKit, Nuxt and Astro do, serve the data folders with a short cache, or use `assets-base` below. Otherwise browsers can keep the old files after an upgrade, and PDF.js can't use them. See the [Vite plugin](https://missing-elements.github.io/pdfjs-viewer/#vite-plugin) docs. [demo/vite-plugin](./demo/vite-plugin) is a minimal app that uses the plugin. +The plugin puts the viewer files and their data in a folder named after a hash of their content, such as `assets/pdfjs-viewer-84204294/`. An upgrade that changes any of them gets a new folder, so caching the build's asset folder as `immutable`, as SvelteKit, Nuxt and Astro do, is safe. See the [Vite plugin](https://missing-elements.github.io/pdfjs-viewer/#vite-plugin) docs. [demo/vite-plugin](./demo/vite-plugin) is a minimal app that uses the plugin. **webpack, Next.js and other bundlers:** copy the package's `dist` folder into your public files, for example in a `postinstall` script, and point [`assets-base`](https://missing-elements.github.io/pdfjs-viewer/#other-bundlers-and-assets-base) at it: diff --git a/plugins/vite.d.ts b/plugins/vite.d.ts index 3f347f0..eb50eaf 100644 --- a/plugins/vite.d.ts +++ b/plugins/vite.d.ts @@ -2,6 +2,7 @@ * A Vite plugin. It writes the PDF.js data the viewer loads on demand (`wasm/`, `cmaps/`, * `standard_fonts/`, `iccs/`, `images/` and `pdf.sandbox.mjs`) into the build output, next to the * viewer files Vite emits. The element finds the data there, with no `assets-base` or resource - * attribute. + * attribute. The viewer files and the data go into a folder named after a hash of their content, + * so an upgrade that changes them changes their URLs. */ export declare function pdfjsViewerData(): { name: string } diff --git a/plugins/vite.js b/plugins/vite.js index 901dbeb..56018c5 100644 --- a/plugins/vite.js +++ b/plugins/vite.js @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto' import { readdirSync, readFileSync, statSync } from 'node:fs' import { join, posix } from 'node:path' import { fileURLToPath } from 'node:url' @@ -19,28 +20,68 @@ const readFile = (file) => readFileSync(join(distDirectory, file)) const listFiles = (entry) => { const path = join(distDirectory, entry) if (!statSync(path).isDirectory()) return [entry] - return readdirSync(path).map((name) => posix.join(entry, name)) + return readdirSync(path).map((name) => posix.join(entry, name)).sort() +} + +let anchors +const getAnchors = () => { + anchors ??= Object.entries(dataByAnchor).map(([name, entries]) => ({ + file: readFile(name), + dataFiles: entries.flatMap(listFiles) + })) + return anchors +} + +// The data keeps the names PDF.js asks for, so on its own its URLs would stay the same across +// upgrades, and a host that caches the build's assets as `immutable` would keep serving an older +// PDF.js version's files to returning visitors. The runtime files and their data go into a folder +// named after a hash of all of them instead: an upgrade that changes any of them changes every URL +// in it, and one that changes none keeps them. +let folderName +const getFolderName = () => { + if (!folderName) { + const hash = createHash('sha256') + getAnchors().forEach(({ file, dataFiles }) => { + hash.update(file) + dataFiles.forEach((name) => hash.update(`\0${name}\0`).update(readFile(name))) + }) + folderName = `pdfjs-viewer-${hash.digest('hex').slice(0, 8)}` + } + return folderName } // The bundler copies a runtime file byte for byte and only renames it, so an emitted asset is // recognised by its content. That follows any `assetFileNames` setting, and it works in Vite and // Rollup versions that don't record which source file an asset came from. const isSameFile = (source, file) => - Buffer.byteLength(source) === file.length && file.equals(Buffer.from(source)) + source != null && Buffer.byteLength(source) === file.length && file.equals(Buffer.from(source)) + +const findAnchor = (source) => getAnchors().find(({ file }) => isSameFile(source, file)) export const pdfjsViewerData = () => ({ name: 'pdfjs-viewer-data', + // Keeps the app's own `assetFileNames` and adds the folder in front of the file name, so a + // runtime file stays in the directory the app gives it. + outputOptions(options) { + const assetFileNames = options.assetFileNames ?? 'assets/[name]-[hash][extname]' + return { + ...options, + assetFileNames: (asset) => { + const pattern = typeof assetFileNames === 'function' ? assetFileNames(asset) : assetFileNames + if (!findAnchor(asset.source)) return pattern + return posix.join(posix.dirname(pattern), getFolderName(), posix.basename(pattern)) + } + } + }, generateBundle(_options, bundle) { - const anchors = Object.entries(dataByAnchor).map(([name, entries]) => ({ file: readFile(name), entries })) - Object.values(bundle) .filter((output) => output.type === 'asset') .forEach((asset) => { - const anchor = anchors.find(({ file }) => isSameFile(asset.source, file)) + const anchor = findAnchor(asset.source) if (!anchor) return const outputDirectory = posix.dirname(asset.fileName) - anchor.entries.flatMap(listFiles).forEach((file) => { + anchor.dataFiles.forEach((file) => { this.emitFile({ type: 'asset', fileName: posix.join(outputDirectory, file), diff --git a/tests/plugin/vite.test.ts b/tests/plugin/vite.test.ts index 67b725c..bc00cef 100644 --- a/tests/plugin/vite.test.ts +++ b/tests/plugin/vite.test.ts @@ -1,9 +1,10 @@ -import { copyFileSync, createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs' +import { appendFileSync, copyFileSync, cpSync, createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs' import { createServer, type Server } from 'node:http' import { createRequire } from 'node:module' import type { AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import { dirname, extname, join, relative, resolve, sep } from 'node:path' +import { pathToFileURL } from 'node:url' import { firefox, type Browser } from 'playwright' import { build, type PluginOption } from 'vite' import { afterAll, beforeAll, describe, expect, it } from 'vitest' @@ -43,6 +44,10 @@ const findFile = (files: string[], pattern: RegExp) => { return file! } +// The folder the plugin moves the runtime files and their data into. +const dataFolder = /pdfjs-viewer-[0-9a-f]{8}/ +const getViewerDirectory = (directory: string) => dirname(findFile(listFiles(directory), /\/viewer-[\w-]+\.mjs$/)) + const contentTypes: Record = { '.html': 'text/html', '.js': 'text/javascript', @@ -137,6 +142,9 @@ describe('Vite plugin', () => { const files = listFiles(pluginOutput) const viewerDirectory = dirname(findFile(files, /\/viewer-[\w-]+\.mjs$/)) const libDirectory = dirname(findFile(files, /\/pdf-[\w-]+\.mjs$/)) + // Both runtime files move into one folder inside the app's `assets`. + expect(viewerDirectory).toMatch(new RegExp(`^assets/${dataFolder.source}$`)) + expect(libDirectory).eq(viewerDirectory) // Every folder in `dist` holds data the element resolves against viewer.mjs, so a folder that // scripts/copy-worker.mjs starts to ship has to reach the plugin's list too. @@ -162,11 +170,29 @@ describe('Vite plugin', () => { } const files = listFiles(await buildApp([pdfjsViewerData()], { assetFileNames })) - expect(files).toContain('static/viewer/wasm/jbig2.wasm') - expect(files).toContain('static/viewer/cmaps/Adobe-Japan1-UCS2.bcmap') - expect(files).toContain('static/lib/pdf.sandbox.mjs') - expect(files.filter((file) => file.endsWith('pdf.sandbox.mjs'))).toEqual(['static/lib/pdf.sandbox.mjs']) - expect(files.filter((file) => file.endsWith('jbig2.wasm'))).toEqual(['static/viewer/wasm/jbig2.wasm']) + // Each file keeps the directory and the name the app gives it, inside the data folder. + const viewerDirectory = dirname(findFile(files, new RegExp(`^static/viewer/${dataFolder.source}/v\\.[\\w-]+\\.mjs$`))) + const libDirectory = dirname(findFile(files, new RegExp(`^static/lib/${dataFolder.source}/p\\.[\\w-]+\\.mjs$`))) + expect(files).toContain(`${viewerDirectory}/cmaps/Adobe-Japan1-UCS2.bcmap`) + expect(files.filter((file) => file.endsWith('jbig2.wasm'))).toEqual([`${viewerDirectory}/wasm/jbig2.wasm`]) + expect(files.filter((file) => file.endsWith('pdf.sandbox.mjs'))).toEqual([`${libDirectory}/pdf.sandbox.mjs`]) + }) + + it('names the data folder after its content, so an upgrade that changes a data file changes its URLs', async () => { + // A copy of the package: its plugin reads the copy's `dist`, as an installed plugin reads its own. + const buildWithPackageCopy = async (changedFile?: string) => { + const packageDirectory = mkdtempSync(join(tmpdir(), 'pdfjs-viewer-package-')) + outputDirectories.push(packageDirectory) + cpSync(join(rootDirectory, 'plugins'), join(packageDirectory, 'plugins'), { recursive: true }) + cpSync(distDirectory, join(packageDirectory, 'dist'), { recursive: true }) + if (changedFile) appendFileSync(join(packageDirectory, 'dist', changedFile), '\0') + const plugin = await import(/* @vite-ignore */ pathToFileURL(join(packageDirectory, 'plugins/vite.js')).href) + return getViewerDirectory(await buildApp([plugin.pdfjsViewerData()])) + } + + const folder = getViewerDirectory(pluginOutput) + expect(await buildWithPackageCopy(), 'the same files keep their folder').eq(folder) + expect(await buildWithPackageCopy('wasm/openjpeg.wasm'), 'a changed decoder moves to a new folder').not.eq(folder) }) it('is exported from the package as ./vite, with types', () => {