[READ-ONLY] Mirror of https://github.com/danielroe/cross-origin-storage. Load shared dependencies from Cross-Origin Storage (COS).
cross-origin-storage experimental nuxt vite vite-plugin
0

Configure Feed

Select the types of activity you want to include in your feed.

1import { createHash } from 'node:crypto' 2import { fileURLToPath } from 'node:url' 3import { rolldown } from 'rolldown' 4import type { Plugin } from 'vite' 5import type { CosManifest } from './runtime/loader' 6 7export type { CosManifest } 8 9const MANIFEST_PLACEHOLDER = '__COS_MANIFEST__' 10 11/** 12 * Recipe version embedded in every content-addressed specifier. Bump this 13 * whenever the build recipe (bundler version, options, define replacements) 14 * changes in a way that alters emitted bytes, so chunks built under different 15 * recipes cannot silently collide on the same SHA-256. 16 */ 17const RECIPE = 'cos1' 18 19const DEFAULT_LOADER_ENTRY = fileURLToPath(new URL('./runtime/loader.entry.js', import.meta.url)) 20 21export interface CosPluginOptions { 22 /** 23 * Packages to extract into standalone Cross-Origin Storage chunks. Each entry 24 * is matched against the imported module specifier; a plain string is treated 25 * as an exact match. 26 */ 27 packages: Array<string | RegExp> 28 /** 29 * Public base path the managed chunks are served from. Defaults to Vite's 30 * resolved `base` joined with `build.assetsDir`. 31 */ 32 base?: string 33 /** 34 * Path to the runtime loader entry to bundle into the injected `<script>`. 35 * Defaults to the bundled loader. Override only to swap the loader runtime. 36 */ 37 loaderEntry?: string 38 /** 39 * Called once the managed chunks are emitted, with the loader `<script>` body 40 * (loader IIFE + inlined manifest). SSR frameworks should inject this into 41 * their rendered HTML themselves. When omitted, the plugin injects it into 42 * `index.html` via `transformIndexHtml` for plain client builds. 43 */ 44 onGenerated?: (scriptContent: string) => void 45} 46 47function contentSpecifier(hash: string): string { 48 return `${RECIPE}:${hash}` 49} 50 51function toMatchers(packages: Array<string | RegExp>): RegExp[] { 52 return packages.map(p => typeof p === 'string' ? new RegExp(`^${p}$`) : p) 53} 54 55/** 56 * Bundle the runtime loader into a self-contained IIFE with rolldown, leaving 57 * `__COS_MANIFEST__` as a literal token for the caller to substitute. Bundling 58 * from source keeps the loader correct regardless of how the host build loaded 59 * this plugin. 60 */ 61async function bundleLoader(entry: string): Promise<string> { 62 const builder = await rolldown({ input: entry, platform: 'browser', treeshake: true }) 63 const { output } = await builder.generate({ format: 'iife', minify: true }) 64 await builder.close() 65 return output[0].code 66} 67 68function rewriteSpecifier(code: string, from: string, to: string): string { 69 const escaped = from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') 70 const fromImport = new RegExp(`((?:import|export)\\b[^;'"\\n]*?from\\s*|import\\s*|export\\s*\\*\\s*from\\s*)(["'])${escaped}\\2`, 'g') 71 const bareImport = new RegExp(`(\\bimport\\s*)(["'])${escaped}\\2`, 'g') 72 const dynamic = new RegExp(`(\\bimport\\s*\\(\\s*)(["'])${escaped}\\2(\\s*\\))`, 'g') 73 return code 74 .replace(dynamic, `$1$2${to}$2$3`) 75 .replace(fromImport, `$1$2${to}$2`) 76 .replace(bareImport, `$1$2${to}$2`) 77} 78 79function joinBase(base: string, assetsDir: string): string { 80 const prefix = base.endsWith('/') ? base : `${base}/` 81 const dir = assetsDir.replace(/^\/+|\/+$/g, '') 82 return dir ? `${prefix}${dir}/` : prefix 83} 84 85export function cosPlugin(options: CosPluginOptions): Plugin { 86 const packages = toMatchers(options.packages) 87 const loaderEntry = options.loaderEntry ?? DEFAULT_LOADER_ENTRY 88 89 const collected = new Set<string>() 90 let assetsDir = 'assets' 91 let resolvedBase = '/' 92 let loaderTemplate: Promise<string> | undefined 93 let scriptContent = '' 94 95 return { 96 name: 'vite-plugin-cos', 97 enforce: 'pre', 98 apply: 'build', 99 configResolved(config) { 100 assetsDir = config.build.assetsDir 101 resolvedBase = config.base 102 }, 103 resolveId: { 104 order: 'pre', 105 filter: { id: packages }, 106 async handler(id, importer, resolveOptions) { 107 const resolved = await this.resolve(id, importer, { ...resolveOptions, skipSelf: true }) 108 if (!resolved) { 109 return 110 } 111 112 collected.add(resolved.id) 113 114 // Externalise under a synthetic specifier so it never clashes with the 115 // real module id elsewhere in the app graph. It is rewritten to a 116 // content-addressed specifier in `generateBundle`, once every managed 117 // chunk has been hashed bottom-up. 118 return { id: `cos-ext:${resolved.id}`, external: true } 119 }, 120 }, 121 async generateBundle(_outputOptions, bundle) { 122 if (!collected.size) { 123 return 124 } 125 const base = options.base ?? joinBase(resolvedBase, assetsDir) 126 const assetPrefix = assetsDir ? `${assetsDir.replace(/^\/+|\/+$/g, '')}/` : '' 127 128 // Build each managed package standalone, externalising every dependency 129 // by its resolved absolute id. Transitive dependencies are discovered and 130 // queued here, so managing a package implicitly manages its whole import 131 // subgraph (e.g. `vue` pulls in `@vue/*`) without the app having to list 132 // them. The externalised ids double as the edges between managed chunks. 133 const raw = new Map<string, { code: string, deps: string[] }>() 134 const queue = [...collected] 135 while (queue.length) { 136 const input = queue.shift()! 137 if (raw.has(input)) { 138 continue 139 } 140 141 const deps = new Set<string>() 142 let code: string 143 try { 144 const builder = await rolldown({ 145 input, 146 platform: 'browser', 147 treeshake: false, 148 plugins: [{ 149 name: 'cos-externalise-deps', 150 async resolveId(id, importer) { 151 if (!importer) { 152 return null 153 } 154 const dep = await this.resolve(id, importer, { skipSelf: true }) 155 if (!dep) { 156 return null 157 } 158 deps.add(dep.id) 159 // Externalise under a synthetic specifier keyed by the resolved 160 // id, so the emitted import is a literal token we rewrite later. 161 // Source specifiers may be relative (`./shared/x.mjs`); the 162 // token makes the rewrite independent of how they were written. 163 return { id: `cos-dep:${dep.id}`, external: true } 164 }, 165 }], 166 }) 167 // `minify` is part of the pinned recipe (see RECIPE): it both shrinks 168 // the chunk and strips rolldown's `//#region <path>` debug comments, 169 // which embed cwd-relative paths and would otherwise make the hash 170 // depend on the build location. 171 const { output } = await builder.generate({ file: 'chunk.js', codeSplitting: false, minify: true }) 172 await builder.close() 173 code = output[0].code 174 } 175 catch (error) { 176 throw new Error( 177 `[cos] cannot bundle managed package as a standalone chunk:\n ${input}\n` 178 + `It likely imports build-time virtuals (e.g. \`#build/*\`, \`#imports\`) that only ` 179 + `resolve inside the host build, so it is not a self-contained, shareable artifact. ` 180 + `Only depend on packages whose source resolves from disk on its own.\n\n` 181 + `Underlying error: ${(error as Error).message}`, 182 { cause: error }, 183 ) 184 } 185 186 raw.set(input, { code, deps: [...deps] }) 187 queue.push(...deps) 188 } 189 190 // Hash bottom-up: a chunk's specifier for a dependency is that 191 // dependency's content hash, so a chunk can only be hashed once all of 192 // its dependencies have been. The npm graph for these packages is a DAG. 193 const hashes = new Map<string, string>() 194 const managed: CosManifest['chunks'] = {} 195 196 const visit = (id: string, stack: string[]): string => { 197 const existing = hashes.get(id) 198 if (existing) { 199 return existing 200 } 201 if (stack.includes(id)) { 202 throw new Error(`[cos] dependency cycle between managed packages: ${[...stack, id].join(' -> ')}`) 203 } 204 205 const { code, deps } = raw.get(id)! 206 let resolved = code 207 for (const dep of deps) { 208 resolved = rewriteSpecifier(resolved, `cos-dep:${dep}`, contentSpecifier(visit(dep, [...stack, id]))) 209 } 210 211 const hash = createHash('sha256').update(resolved).digest('hex') 212 const fileName = `${assetPrefix}${hash}.js` 213 hashes.set(id, hash) 214 managed[contentSpecifier(hash)] = { file: `${hash}.js`, hash } 215 bundle[fileName] = { 216 type: 'asset', 217 fileName, 218 name: hash, 219 names: [hash], 220 originalFileName: null, 221 originalFileNames: [], 222 needsCodeReference: false, 223 source: resolved, 224 } 225 return hash 226 } 227 228 for (const id of raw.keys()) { 229 visit(id, []) 230 } 231 232 let entry: CosManifest['entry'] | undefined 233 for (const file of Object.values(bundle)) { 234 if (file.type !== 'chunk') { 235 continue 236 } 237 // App chunks only reference the packages the app imported directly, 238 // externalised as `cos-ext:<id>` by this plugin's `resolveId`. 239 for (const id of collected) { 240 file.code = rewriteSpecifier(file.code, `cos-ext:${id}`, contentSpecifier(hashes.get(id)!)) 241 } 242 if (file.isEntry) { 243 // The entry is app-specific and is re-rendered by Vite after this 244 // hook, so it cannot be content-addressed here; it loads from the 245 // network under a stable specifier instead. 246 entry = { specifier: `${RECIPE}:entry`, file: file.fileName.replace(new RegExp(`^${assetPrefix}`), '') } 247 } 248 } 249 250 if (!entry) { 251 return 252 } 253 254 const manifest: CosManifest = { base, entry, chunks: managed } 255 loaderTemplate ??= bundleLoader(loaderEntry) 256 scriptContent = (await loaderTemplate).replace(MANIFEST_PLACEHOLDER, JSON.stringify(manifest)) 257 options.onGenerated?.(scriptContent) 258 }, 259 transformIndexHtml: { 260 order: 'post', 261 handler(html) { 262 if (options.onGenerated || !scriptContent) { 263 return html 264 } 265 return html 266 .replace(/<script type="module"[^>]*src="[^"]*"[^>]*><\/script>/g, '') 267 .replace('</head>', `<script id="cos-loader">${scriptContent}</script></head>`) 268 }, 269 }, 270 } 271} 272 273export default cosPlugin