Unverified Commit 29bbdfbd authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Output service workers to `/_next/static/` (#95554)

This should fix deployment tests because this now re-uses Vercel's
support for static JS files
parent fb55cfb0
...@@ -1614,6 +1614,7 @@ impl Project { ...@@ -1614,6 +1614,7 @@ impl Project {
.owned() .owned()
.await?, .await?,
asset_prefix: self.next_config().computed_asset_prefix(), asset_prefix: self.next_config().computed_asset_prefix(),
service_worker_scope_base_path: self.next_config().base_path(),
environment: self.client_compile_time_info().environment(), environment: self.client_compile_time_info().environment(),
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
......
...@@ -27,9 +27,9 @@ use crate::project::Project; ...@@ -27,9 +27,9 @@ use crate::project::Project;
/// reachable from `module_graph` — via the [`ServiceWorkerEntryModule`] markers the analyzer leaves /// reachable from `module_graph` — via the [`ServiceWorkerEntryModule`] markers the analyzer leaves
/// in the graph — and compiles each registered worker into a single self-contained bundle. /// in the graph — and compiles each registered worker into a single self-contained bundle.
/// ///
/// Each is emitted under `node_root/service-worker/<scope-derived name>` (e.g. /// Each is emitted under `node_root/static/service-worker/<scope-derived name>` (e.g.
/// `service-worker/sw.js`, `service-worker/sw-offline-mode.js`) and served at the matching /// `static/service-worker/sw.js`) and served at the matching `/_next/static/service-worker/` URL
/// origin-root URL (`/sw.js`, `/sw-offline-mode.js`). /// via the existing static pipeline (with a `Service-Worker-Allowed` header so it keeps its scope).
/// ///
/// Only one service worker is supported per scope. /// Only one service worker is supported per scope.
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -87,7 +87,7 @@ pub async fn service_worker_output_assets( ...@@ -87,7 +87,7 @@ pub async fn service_worker_output_assets(
} }
/// Compiles a single service worker `source_path` (registered at `scope`) into one self-contained /// Compiles a single service worker `source_path` (registered at `scope`) into one self-contained
/// chunk emitted at `node_root/service-worker/<scope-derived name>`. /// chunk emitted at `node_root/static/service-worker/<scope-derived name>`.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn service_worker_chunk( async fn service_worker_chunk(
project: Vc<Project>, project: Vc<Project>,
...@@ -122,7 +122,10 @@ async fn service_worker_chunk( ...@@ -122,7 +122,10 @@ async fn service_worker_chunk(
let EntryChunkGroupResult { asset, .. } = *chunking_context let EntryChunkGroupResult { asset, .. } = *chunking_context
.entry_chunk_group( .entry_chunk_group(
node_root.join("service-worker")?.join(&filename)?, node_root
.join("static")?
.join("service-worker")?
.join(&filename)?,
ChunkGroup::Entry(vec![module]), ChunkGroup::Entry(vec![module]),
own_graph, own_graph,
/* extra_chunks */ OutputAssets::empty(), /* extra_chunks */ OutputAssets::empty(),
......
...@@ -464,6 +464,7 @@ pub struct ClientChunkingContextOptions { ...@@ -464,6 +464,7 @@ pub struct ClientChunkingContextOptions {
pub client_root_to_root_path: RcStr, pub client_root_to_root_path: RcStr,
pub client_static_folder_name: RcStr, pub client_static_folder_name: RcStr,
pub asset_prefix: Vc<RcStr>, pub asset_prefix: Vc<RcStr>,
pub service_worker_scope_base_path: Vc<Option<RcStr>>,
pub environment: Vc<Environment>, pub environment: Vc<Environment>,
pub module_id_strategy: Vc<ModuleIdStrategy>, pub module_id_strategy: Vc<ModuleIdStrategy>,
pub export_usage: Vc<OptionBindingUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
...@@ -505,6 +506,7 @@ pub async fn get_client_chunking_context( ...@@ -505,6 +506,7 @@ pub async fn get_client_chunking_context(
client_root_to_root_path, client_root_to_root_path,
client_static_folder_name, client_static_folder_name,
asset_prefix, asset_prefix,
service_worker_scope_base_path,
environment, environment,
module_id_strategy, module_id_strategy,
export_usage, export_usage,
...@@ -529,6 +531,7 @@ pub async fn get_client_chunking_context( ...@@ -529,6 +531,7 @@ pub async fn get_client_chunking_context(
let next_mode = mode.await?; let next_mode = mode.await?;
let asset_prefix = asset_prefix.owned().await?; let asset_prefix = asset_prefix.owned().await?;
let service_worker_scope_base_path = service_worker_scope_base_path.owned().await?;
let cross_origin_loading = *cross_origin.await?; let cross_origin_loading = *cross_origin.await?;
let mut builder = BrowserChunkingContext::builder( let mut builder = BrowserChunkingContext::builder(
root_path, root_path,
...@@ -545,6 +548,7 @@ pub async fn get_client_chunking_context( ...@@ -545,6 +548,7 @@ pub async fn get_client_chunking_context(
next_mode.runtime_type(), next_mode.runtime_type(),
) )
.chunk_base_path(Some(asset_prefix.clone())) .chunk_base_path(Some(asset_prefix.clone()))
.service_worker_scope_base_path(service_worker_scope_base_path)
.asset_suffix(AssetSuffix::Inferred.resolved_cell()) .asset_suffix(AssetSuffix::Inferred.resolved_cell())
.minify_type(if *minify.await? { .minify_type(if *minify.await? {
MinifyType::Minify { MinifyType::Minify {
......
...@@ -231,6 +231,7 @@ import { ...@@ -231,6 +231,7 @@ import {
type PrefetchSegmentDataRoute, type PrefetchSegmentDataRoute,
} from '../server/lib/router-utils/build-prefetch-segment-data-route' } from '../server/lib/router-utils/build-prefetch-segment-data-route'
import { generateRoutesManifest } from './generate-routes-manifest' import { generateRoutesManifest } from './generate-routes-manifest'
import { buildCustomRoute } from '../lib/build-custom-route'
import { validateAppPaths } from './validate-app-paths' import { validateAppPaths } from './validate-app-paths'
type Fallback = null | boolean | string type Fallback = null | boolean | string
...@@ -2727,6 +2728,26 @@ export default async function build( ...@@ -2727,6 +2728,26 @@ export default async function build(
}) })
} }
// Service workers are compiled into `distDir/static/service-worker/` and register at a broader
// scope than their own directory (e.g. `/`), so their script response needs a
// `Service-Worker-Allowed` header.
const serviceWorkerDir = path.join(distDir, 'static', 'service-worker')
if (
existsSync(serviceWorkerDir) &&
(await fs.readdir(serviceWorkerDir)).length > 0
) {
routesManifest.headers.push(
buildCustomRoute('header', {
source: `${config.basePath || ''}/_next/static/service-worker/:path*`,
headers: [
{ key: 'Service-Worker-Allowed', value: config.basePath || '/' },
],
locale: false,
internal: true,
})
)
}
// We need to write the manifest with rewrites before build // We need to write the manifest with rewrites before build
await nextBuildSpan await nextBuildSpan
.traceChild('write-routes-manifest') .traceChild('write-routes-manifest')
......
...@@ -535,7 +535,10 @@ export async function initialize(opts: { ...@@ -535,7 +535,10 @@ export async function initialize(opts: {
!res.getHeader('cache-control') && !res.getHeader('cache-control') &&
matchedOutput.type === 'nextStaticFolder' matchedOutput.type === 'nextStaticFolder'
) { ) {
if (opts.dev && !isNextFont(parsedUrl.pathname)) { if (matchedOutput.itemPath.startsWith('/service-worker/')) {
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')
res.setHeader('Service-Worker-Allowed', config.basePath || '/')
} else if (opts.dev && !isNextFont(parsedUrl.pathname)) {
res.setHeader('Cache-Control', 'no-cache, must-revalidate') res.setHeader('Cache-Control', 'no-cache, must-revalidate')
} else { } else {
res.setHeader( res.setHeader(
......
...@@ -55,7 +55,6 @@ export type FsOutput = { ...@@ -55,7 +55,6 @@ export type FsOutput = {
| 'publicFolder' | 'publicFolder'
| 'nextStaticFolder' | 'nextStaticFolder'
| 'legacyStaticFolder' | 'legacyStaticFolder'
| 'serviceWorker'
| 'devVirtualFsItem' | 'devVirtualFsItem'
itemPath: string itemPath: string
...@@ -132,7 +131,6 @@ export async function setupFsCheck(opts: { ...@@ -132,7 +131,6 @@ export async function setupFsCheck(opts: {
const publicFolderItems = new Set<string>() const publicFolderItems = new Set<string>()
const nextStaticFolderItems = new Set<string>() const nextStaticFolderItems = new Set<string>()
const legacyStaticFolderItems = new Set<string>() const legacyStaticFolderItems = new Set<string>()
const serviceWorkerItems = new Set<string>()
const appFiles = new Set<string>() const appFiles = new Set<string>()
const pageFiles = new Set<string>() const pageFiles = new Set<string>()
...@@ -155,7 +153,6 @@ export async function setupFsCheck(opts: { ...@@ -155,7 +153,6 @@ export async function setupFsCheck(opts: {
const publicFolderPath = path.join(opts.dir, 'public') const publicFolderPath = path.join(opts.dir, 'public')
const nextStaticFolderPath = path.join(distDir, 'static') const nextStaticFolderPath = path.join(distDir, 'static')
const legacyStaticFolderPath = path.join(opts.dir, 'static') const legacyStaticFolderPath = path.join(opts.dir, 'static')
const serviceWorkerFolderPath = path.join(distDir, 'service-worker')
let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = { let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = {
redirects: [], redirects: [],
rewrites: { rewrites: {
...@@ -219,16 +216,6 @@ export async function setupFsCheck(opts: { ...@@ -219,16 +216,6 @@ export async function setupFsCheck(opts: {
if (opts.config.output !== 'standalone') throw err if (opts.config.output !== 'standalone') throw err
} }
try {
for (const file of await recursiveReadDir(serviceWorkerFolderPath)) {
serviceWorkerItems.add(encodeURIPath(normalizePathSep(file)))
}
} catch (err: any) {
if (err.code !== 'ENOENT') {
throw err
}
}
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST) const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST)
const middlewareManifestPath = path.join( const middlewareManifestPath = path.join(
...@@ -438,7 +425,6 @@ export async function setupFsCheck(opts: { ...@@ -438,7 +425,6 @@ export async function setupFsCheck(opts: {
debug('customRoutes', customRoutes) debug('customRoutes', customRoutes)
debug('publicFolderItems', publicFolderItems) debug('publicFolderItems', publicFolderItems)
debug('nextStaticFolderItems', nextStaticFolderItems) debug('nextStaticFolderItems', nextStaticFolderItems)
debug('serviceWorkerItems', serviceWorkerItems)
debug('pageFiles', pageFiles) debug('pageFiles', pageFiles)
debug('appFiles', appFiles) debug('appFiles', appFiles)
...@@ -540,7 +526,6 @@ export async function setupFsCheck(opts: { ...@@ -540,7 +526,6 @@ export async function setupFsCheck(opts: {
const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [ const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [
[this.devVirtualFsItems, 'devVirtualFsItem'], [this.devVirtualFsItems, 'devVirtualFsItem'],
[serviceWorkerItems, 'serviceWorker'],
[nextStaticFolderItems, 'nextStaticFolder'], [nextStaticFolderItems, 'nextStaticFolder'],
[legacyStaticFolderItems, 'legacyStaticFolder'], [legacyStaticFolderItems, 'legacyStaticFolder'],
[publicFolderItems, 'publicFolder'], [publicFolderItems, 'publicFolder'],
...@@ -664,10 +649,6 @@ export async function setupFsCheck(opts: { ...@@ -664,10 +649,6 @@ export async function setupFsCheck(opts: {
itemsRoot = publicFolderPath itemsRoot = publicFolderPath
break break
} }
case 'serviceWorker': {
itemsRoot = serviceWorkerFolderPath
break
}
case 'appFile': case 'appFile':
case 'pageFile': case 'pageFile':
case 'nextImage': case 'nextImage':
...@@ -691,7 +672,6 @@ export async function setupFsCheck(opts: { ...@@ -691,7 +672,6 @@ export async function setupFsCheck(opts: {
'nextStaticFolder', 'nextStaticFolder',
'publicFolder', 'publicFolder',
'legacyStaticFolder', 'legacyStaticFolder',
'serviceWorker',
] as (typeof type)[] ] as (typeof type)[]
).includes(type) ).includes(type)
......
...@@ -524,9 +524,14 @@ export function getResolveRoutes( ...@@ -524,9 +524,14 @@ export function getResolveRoutes(
let isImmutableFile = let isImmutableFile =
config.experimental.supportsImmutableAssets && config.experimental.supportsImmutableAssets &&
clientHashes![`static${decodeURI(output.itemPath)}`] clientHashes![`static${decodeURI(output.itemPath)}`]
const expectedToken = isImmutableFile // Service workers are served at a fixed, stable URL (so the browser can keep the
? undefined // same registration across builds), so they don't carry a `?dpl` token.
: config.deploymentId const isServiceWorker =
output.itemPath.startsWith('/service-worker/')
const expectedToken =
isImmutableFile || isServiceWorker
? undefined
: config.deploymentId
if (parsedUrl.query.dpl !== expectedToken) { if (parsedUrl.query.dpl !== expectedToken) {
console.error( console.error(
`Invalid dpl query param: ${req.url}, expected: ${expectedToken}` `Invalid dpl query param: ${req.url}, expected: ${expectedToken}`
......
...@@ -5,14 +5,10 @@ import { retry } from 'next-test-utils' ...@@ -5,14 +5,10 @@ import { retry } from 'next-test-utils'
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'app dir - service worker (one worker per scope)', 'app dir - service worker (one worker per scope)',
() => { () => {
const { next, skipped } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
// TODO(sampoder) output sw.js into static/ instead of special handling in next-server
skipDeployment: true,
}) })
if (skipped) return
it('serves one worker per scope at scope-derived file names', async () => { it('serves one worker per scope at scope-derived file names', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
...@@ -25,9 +21,9 @@ import { retry } from 'next-test-utils' ...@@ -25,9 +21,9 @@ import { retry } from 'next-test-utils'
) )
}) })
// The root scope "/" is served unhashed at /sw.js. Both workers are served // The root scope "/" is served unhashed at /_next/static/service-worker/sw.js. Both workers
// as mutable, always-revalidated assets (never immutable). // are served as mutable, always-revalidated assets (never immutable).
const root = await next.fetch('/sw.js') const root = await next.fetch('/_next/static/service-worker/sw.js')
expect(root.status).toBe(200) expect(root.status).toBe(200)
expect(root.headers.get('cache-control')).toContain('max-age=0') expect(root.headers.get('cache-control')).toContain('max-age=0')
expect(root.headers.get('cache-control')).not.toContain('immutable') expect(root.headers.get('cache-control')).not.toContain('immutable')
...@@ -37,7 +33,9 @@ import { retry } from 'next-test-utils' ...@@ -37,7 +33,9 @@ import { retry } from 'next-test-utils'
let offlineScript = '' let offlineScript = ''
await retry(async () => { await retry(async () => {
offlineScript = await browser.elementByCss('#offline-script').text() offlineScript = await browser.elementByCss('#offline-script').text()
expect(offlineScript).toMatch(/^\/sw-offline-mode-[0-9a-f]+\.js$/) expect(offlineScript).toMatch(
/^\/_next\/static\/service-worker\/sw-offline-mode-[0-9a-f]+\.js$/
)
}) })
const offline = await next.fetch(offlineScript) const offline = await next.fetch(offlineScript)
......
...@@ -6,6 +6,7 @@ export default function Page() { ...@@ -6,6 +6,7 @@ export default function Page() {
const [controller, setController] = useState('default') const [controller, setController] = useState('default')
const [script, setScript] = useState('default') const [script, setScript] = useState('default')
const [fetchResult, setFetchResult] = useState('default') const [fetchResult, setFetchResult] = useState('default')
const [interceptPath, setInterceptPath] = useState('/sw-intercepted')
useEffect(() => { useEffect(() => {
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
...@@ -15,10 +16,16 @@ export default function Page() { ...@@ -15,10 +16,16 @@ export default function Page() {
async function register() { async function register() {
const registration = await navigator.serviceWorker.register( const registration = await navigator.serviceWorker.register(
new URL('../lib/pwa', import.meta.url) new URL('../lib/pwa', import.meta.url),
{ updateViaCache: 'none' }
) )
setScope(registration.scope) setScope(registration.scope)
// Fetch a sentinel URL that lives inside the registration scope (e.g. `/sw-intercepted` or
// `/base/sw-intercepted`), so the service worker actually controls the request.
const scopePath = new URL(registration.scope).pathname.replace(/\/$/, '')
setInterceptPath(`${scopePath}/sw-intercepted`)
await navigator.serviceWorker.ready await navigator.serviceWorker.ready
const updateController = () => { const updateController = () => {
...@@ -47,7 +54,7 @@ export default function Page() { ...@@ -47,7 +54,7 @@ export default function Page() {
<p id="sw-script">{script}</p> <p id="sw-script">{script}</p>
<button <button
onClick={async () => { onClick={async () => {
const res = await fetch('/sw-intercepted') const res = await fetch(interceptPath)
setFetchResult(await res.text()) setFetchResult(await res.text())
}} }}
> >
......
...@@ -14,7 +14,8 @@ self.addEventListener('activate', (event) => { ...@@ -14,7 +14,8 @@ self.addEventListener('activate', (event) => {
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url) const url = new URL(event.request.url)
if (url.pathname === '/sw-intercepted') { // Match within any registration scope (e.g. `/sw-intercepted` or `/base/sw-intercepted`).
if (url.pathname.endsWith('/sw-intercepted')) {
event.respondWith( event.respondWith(
new Response('intercepted-by-sw', { new Response('intercepted-by-sw', {
headers: { 'content-type': 'text/plain' }, headers: { 'content-type': 'text/plain' },
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup, type NextInstance } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
// Compiling `navigator.serviceWorker.register(new URL(...))` is a Turbopack-only feature. // Compiling `navigator.serviceWorker.register(new URL(...))` is a Turbopack-only feature.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( const describeTurbopack = process.env.IS_TURBOPACK_TEST
'app dir - service worker register', ? describe
() => { : describe.skip
const { next, skipped } = nextTestSetup({
files: __dirname,
// TODO(sampoder) output sw.js into static/ instead of special handling in next-server
skipDeployment: true,
})
if (skipped) return // The same behavior is exercised with and without a `basePath`: the worker is served under the
// base path and both its script URL and registration scope are prefixed with it.
function runTests(next: NextInstance, basePath: string) {
const home = basePath || '/'
const swUrl = `${basePath}/_next/static/service-worker/sw.js`
it('registers the service worker and controls the page at scope "/"', async () => { it('registers the service worker and controls the page', async () => {
const browser = await next.browser('/') const browser = await next.browser(home)
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('#sw-controller').text()).toBe( expect(await browser.elementByCss('#sw-controller').text()).toBe(
'controlled' 'controlled'
) )
}) })
// Served from the origin root, so the registration scope is the whole origin // The worker is served under `/_next/static/service-worker/` but registers at a broader scope:
// with no Service-Worker-Allowed header needed. // the codegen pins `{ scope }` and the response carries `Service-Worker-Allowed`.
const scope = await browser.elementByCss('#sw-scope').text() const scope = await browser.elementByCss('#sw-scope').text()
expect(new URL(scope).pathname).toBe('/') expect(new URL(scope).pathname).toBe(home)
// A single service worker per app is served at the fixed, root-scoped /sw.js. // A single service worker per scope is served at a fixed URL under the static folder.
const script = await browser.elementByCss('#sw-script').text() const script = await browser.elementByCss('#sw-script').text()
expect(script).toBe('/sw.js') expect(script).toBe(swUrl)
})
it('serves the worker chunk as a revalidated, mutable asset', async () => {
const browser = await next.browser(home)
await retry(async () => {
expect(await browser.elementByCss('#sw-script').text()).toBe(swUrl)
}) })
it('serves the worker chunk at the root as a revalidated, mutable asset', async () => { const res = await next.fetch(swUrl)
const browser = await next.browser('/') expect(res.status).toBe(200)
await retry(async () => { // Stable URL across builds: it must be served as a mutable asset (never
expect(await browser.elementByCss('#sw-script').text()).toBe('/sw.js') // immutable) that is revalidated on every use, so a new worker ships
}) // immediately rather than being pinned by a long-lived cache entry.
const cacheControl = res.headers.get('cache-control')
const res = await next.fetch('/sw.js') expect(cacheControl).not.toContain('immutable')
expect(res.status).toBe(200) expect(cacheControl).toContain('max-age=0')
// Stable URL across builds: it must be served as a mutable asset (never
// immutable) that is revalidated on every use, so a new worker ships // It registers at a broader scope than its own directory, so the response must
// immediately rather than being pinned by a long-lived cache entry. // carry `Service-Worker-Allowed` or the browser rejects the registration.
const cacheControl = res.headers.get('cache-control') expect(res.headers.get('service-worker-allowed')).toBe(home)
expect(cacheControl).not.toContain('immutable')
expect(cacheControl).toContain('max-age=0') // Revalidated on every use, so it must ship an ETag to turn those
// revalidations into cheap 304s instead of re-downloading the worker body.
// Revalidated on every use, so it must ship an ETag to turn those const etag = res.headers.get('etag')
// revalidations into cheap 304s instead of re-downloading the worker body. expect(etag).toBeTruthy()
const etag = res.headers.get('etag')
expect(etag).toBeTruthy() // A conditional re-fetch with the ETag returns 304 Not Modified (no body),
// confirming we don't over-fetch an unchanged worker.
// A conditional re-fetch with the ETag returns 304 Not Modified (no body), const conditional = await next.fetch(swUrl, {
// confirming we don't over-fetch an unchanged worker. headers: { 'If-None-Match': etag },
const conditional = await next.fetch('/sw.js', {
headers: { 'If-None-Match': etag },
})
expect(conditional.status).toBe(304)
}) })
expect(conditional.status).toBe(304)
})
it('intercepts fetches within scope', async () => { it('preserves the options object passed to register()', async () => {
const browser = await next.browser('/') // The codegen pins `{ scope }` but must merge it into the user's options rather than
// replacing them, or options like `updateViaCache` / `type: 'module'` are silently dropped.
const browser = await next.browser(home)
await retry(async () => {
expect(await browser.elementByCss('#sw-controller').text()).toBe(
'controlled'
)
})
await retry(async () => { const scripts: string[] = await browser.eval(`
expect(await browser.elementByCss('#sw-controller').text()).toBe( Array.from(
'controlled' new Set(
performance
.getEntriesByType('resource')
.map((r) => r.name)
.filter((n) => n.includes('/_next/static/') && n.endsWith('.js'))
) )
}) )
`)
expect(scripts.length).toBeGreaterThan(0)
await browser.elementByCss('button').click() let preserved = false
for (const src of scripts) {
const res = await next.fetch(new URL(src).pathname)
if (res.status !== 200) continue
const text = await res.text()
if (/updateViaCache\s*:\s*["']none["']/.test(text)) {
preserved = true
break
}
}
expect(preserved).toBe(true)
})
await retry(async () => { it('intercepts fetches within scope', async () => {
expect(await browser.elementByCss('#fetch-result').text()).toBe( const browser = await next.browser(home)
'intercepted-by-sw'
) await retry(async () => {
}) expect(await browser.elementByCss('#sw-controller').text()).toBe(
'controlled'
)
})
await browser.elementByCss('button').click()
await retry(async () => {
expect(await browser.elementByCss('#fetch-result').text()).toBe(
'intercepted-by-sw'
)
}) })
} })
) }
describeTurbopack('app dir - service worker register', () => {
const { next } = nextTestSetup({
files: __dirname,
})
runTests(next, '')
})
describeTurbopack('app dir - service worker register (basePath)', () => {
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath: '/base',
},
})
runTests(next, '/base')
})
...@@ -101,6 +101,14 @@ impl BrowserChunkingContextBuilder { ...@@ -101,6 +101,14 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn service_worker_scope_base_path(
mut self,
service_worker_scope_base_path: Option<RcStr>,
) -> Self {
self.chunking_context.service_worker_scope_base_path = service_worker_scope_base_path;
self
}
pub fn chunk_base_path(mut self, chunk_base_path: Option<RcStr>) -> Self { pub fn chunk_base_path(mut self, chunk_base_path: Option<RcStr>) -> Self {
self.chunking_context.chunk_base_path = chunk_base_path; self.chunking_context.chunk_base_path = chunk_base_path;
self self
...@@ -315,6 +323,9 @@ pub struct BrowserChunkingContext { ...@@ -315,6 +323,9 @@ pub struct BrowserChunkingContext {
/// them. /// them.
#[bincode(with = "turbo_bincode::indexmap")] #[bincode(with = "turbo_bincode::indexmap")]
asset_base_paths: FxIndexMap<RcStr, RcStr>, asset_base_paths: FxIndexMap<RcStr, RcStr>,
/// This is the base path used to generate the service worker scope, it is
/// not used for output subdirectory logic
service_worker_scope_base_path: Option<RcStr>,
/// URL behavior overrides for different tags. /// URL behavior overrides for different tags.
#[bincode(with = "turbo_bincode::indexmap")] #[bincode(with = "turbo_bincode::indexmap")]
url_behaviors: FxIndexMap<RcStr, UrlBehavior>, url_behaviors: FxIndexMap<RcStr, UrlBehavior>,
...@@ -400,6 +411,7 @@ impl BrowserChunkingContext { ...@@ -400,6 +411,7 @@ impl BrowserChunkingContext {
asset_suffix: None, asset_suffix: None,
asset_base_path: None, asset_base_path: None,
asset_base_paths: Default::default(), asset_base_paths: Default::default(),
service_worker_scope_base_path: None,
url_behaviors: Default::default(), url_behaviors: Default::default(),
default_url_behavior: None, default_url_behavior: None,
enable_hot_module_replacement: false, enable_hot_module_replacement: false,
...@@ -678,6 +690,15 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -678,6 +690,15 @@ impl ChunkingContext for BrowserChunkingContext {
)) ))
} }
#[turbo_tasks::function]
fn service_worker_scope_base_path(&self) -> Vc<RcStr> {
Vc::cell(
self.service_worker_scope_base_path
.clone()
.unwrap_or_default(),
)
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn reference_chunk_source_maps(&self, _chunk: Vc<Box<dyn OutputAsset>>) -> Vc<bool> { fn reference_chunk_source_maps(&self, _chunk: Vc<Box<dyn OutputAsset>>) -> Vc<bool> {
Vc::cell(match self.source_maps_type { Vc::cell(match self.source_maps_type {
......
...@@ -365,6 +365,11 @@ pub trait ChunkingContext { ...@@ -365,6 +365,11 @@ pub trait ChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn asset_url(self: Vc<Self>, ident: FileSystemPath, tag: Option<RcStr>) -> Result<Vc<RcStr>>; fn asset_url(self: Vc<Self>, ident: FileSystemPath, tag: Option<RcStr>) -> Result<Vc<RcStr>>;
#[turbo_tasks::function]
fn service_worker_scope_base_path(self: Vc<Self>) -> Vc<RcStr> {
Vc::cell(RcStr::default())
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn asset_path( fn asset_path(
self: Vc<Self>, self: Vc<Self>,
......
...@@ -3053,7 +3053,27 @@ where ...@@ -3053,7 +3053,27 @@ where
// No `scope` key: register at the default scope. // No `scope` key: register at the default scope.
None => rcstr!("/"), None => rcstr!("/"),
Some(JsValue::Constant(JsConstantValue::Str(value))) => { Some(JsValue::Constant(JsConstantValue::Str(value))) => {
value.as_str().into() let scope = value.as_str();
// The scope must be an absolute path (starting with `/`) so
// it can be prefixed with the host's base path and served
// from a stable, root-relative URL. Reject relative scopes
// rather than silently registering at the wrong scope.
if !scope.starts_with('/') {
let (args, hints) = explain_args(args);
handler.span_warn_with_code(
span,
&format!(
"navigator.serviceWorker.register({args}) has a \
`scope` that does not start with `/`{hints}",
),
DiagnosticId::Error(
errors::failed_to_analyze::ecmascript::NEW_WORKER
.to_string(),
),
);
return Ok(());
}
scope.into()
} }
// A `scope` was provided but can't be analyzed statically; // A `scope` was provided but can't be analyzed statically;
// don't silently register at the wrong scope. // don't silently register at the wrong scope.
......
...@@ -247,20 +247,54 @@ pub struct ServiceWorkerAssetReferenceCodeGen { ...@@ -247,20 +247,54 @@ pub struct ServiceWorkerAssetReferenceCodeGen {
impl ServiceWorkerAssetReferenceCodeGen { impl ServiceWorkerAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
_chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
// The worker is served at a fixed, root-scoped URL derived from its `scope`. Rewrite the // Rewrite `register(...)`'s script argument to the served URL and pin the `{ scope }` the
// `new URL(...)` script argument to that URL string. // analyzer resolved, preserving any other options the user passed (such as `type` or
let url = format!("/{}", service_worker_chunk_filename(&self.scope)); // `updateViaCache`). Both are prefixed with the context's base path (e.g. a framework's
// `basePath`, provided by the host) so the worker is fetched and scoped under it.
//
// register(new URL("./sw", import.meta.url)) // base path ""
// -> register("/_next/static/service-worker/sw.js", { scope: "/" })
// register(new URL("./sw", import.meta.url)) // base path "/base"
// -> register("/base/_next/static/service-worker/sw.js", { scope: "/base" })
let base_path = chunking_context.service_worker_scope_base_path().await?;
let base_path = base_path.trim_end_matches('/');
let url = format!(
"{base_path}/_next/static/service-worker/{}",
service_worker_chunk_filename(&self.scope)
);
let scope = match self.scope.as_str() {
"/" if base_path.is_empty() => "/".to_string(),
"/" => base_path.to_string(),
s => format!("{base_path}{s}"),
};
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
let message = if let Expr::Call(call_expr) = expr { let message = if let Expr::Call(call_expr) = expr {
match call_expr.args.first_mut() { match call_expr.args.first() {
Some(ExprOrSpread { Some(ExprOrSpread { spread: None, .. }) => {
spread: None, let scope_expr = Expr::Lit(Lit::Str(scope.as_str().into()));
expr: url_expr, let options = match call_expr.args.get(1) {
}) => { Some(ExprOrSpread { spread: None, expr }) => quote_expr!(
**url_expr = Expr::Lit(Lit::Str(url.as_str().into())); "({ ...$user, scope: $scope })",
user: Expr = (**expr).clone(),
scope: Expr = scope_expr
),
_ => quote_expr!(
"({ scope: $scope })",
scope: Expr = scope_expr
),
};
call_expr.args.truncate(1);
call_expr.args[0] = ExprOrSpread {
spread: None,
expr: Box::new(Expr::Lit(Lit::Str(url.as_str().into()))),
};
call_expr.args.push(ExprOrSpread {
spread: None,
expr: options,
});
return; return;
} }
Some(ExprOrSpread { Some(ExprOrSpread {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment