Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions test/engines.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ describe.each(NATIVE)('the %s declaration engine', (engine) => {
const dir = dirs[engine]!
const watcher = watch(dir, [tsdownBin, '--watch'])
try {
await waitFor(() => /Rebuilt in/.test(watcher.output()), 120_000)
await waitFor(() => watcher.builds() > 0, 120_000)
await writeFile(join(dir, 'src/extra/math.ts'), `export function twice(value: number) {\n return value * 2\n}\n\nexport const half = () => 'half' as const\n`)
await waitFor(async () => exists(dir, 'dist/extra/math.d.mts') && (await read(dir, 'dist/extra/math.d.mts')).includes('half: () => \'half\''), 60_000)
await waitFor(async () => exists(dir, 'dist/extra/math.d.mts') && (await read(dir, 'dist/extra/math.d.mts')).includes('half: () => \'half\''), watcher.timeout(), 50)
await writeFile(join(dir, 'src/utils.ts'), `export const myModuleUtils = () => {}\nexport const watched = 1 as const\n`)
await waitFor(async () => (await read(dir, 'dist/utils.d.mts')).includes('watched: 1'), 60_000)
await waitFor(async () => (await read(dir, 'dist/utils.d.mts')).includes('watched: 1'), watcher.timeout(), 50)
}
finally {
await watcher.stop()
Expand Down
51 changes: 48 additions & 3 deletions test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,29 @@ export async function unresolvedSpecifiers(dir: string) {
return failures
}

export function watch(cwd: string, args: string[], onFailed: typeof onTestFailed = onTestFailed) {
/** A running `tsdown --watch`, and the builds it reports. */
export interface Watched {
/** Everything the process has printed so far. */
output: () => string
/** The builds the process has reported as finished. */
builds: () => number
/**
* How long to wait for the watcher to report a change or a rebuild: three times the longest
* build it has reported so far, and at least ten seconds.
*/
timeout: () => number
/**
* Runs `change`, then waits for the watcher to report `changed` and for the build it starts
* after that report to finish.
*/
rebuild: (change: () => void | Promise<void>, changed: string) => Promise<void>
stop: () => Promise<void>
}

/** A watcher that reports nothing for this long has not seen the change at all. */
const MIN_TIMEOUT = 10_000

export function watch(cwd: string, args: string[], onFailed: typeof onTestFailed = onTestFailed): Watched {
const result = exec('node', args, { nodeOptions: { cwd, env: { ...process.env, ...buildEnv } } })
let output = ''
onFailed(() => {
Expand All @@ -213,22 +235,45 @@ export function watch(cwd: string, args: string[], onFailed: typeof onTestFailed
output += chunk
})
}
const durations = () => [...output.matchAll(/Rebuilt in (\d+)ms/g)].map(([, ms]) => Number(ms))
const builds = () => durations().length
const timeout = () => Math.max(MIN_TIMEOUT, 3 * Math.max(0, ...durations()))
return {
output: () => output,
builds,
timeout,
async rebuild(change, changed) {
const seen = output.length
const limit = timeout()
const normalised = () => output.replaceAll('\\', '/')
const within = async (check: () => boolean, what: string) => {
try {
await waitFor(check, limit, 50)
}
catch {
throw new Error(`Waited ${limit}ms for ${what}`)
}
}
await change()
const reported = `Watched change: ${changed.replaceAll('\\', '/')}`
await within(() => normalised().slice(seen).includes(reported), `the watcher to report ${changed}`)
const from = seen + normalised().slice(seen).indexOf(reported) + reported.length
await within(() => /Rebuilt in \d+ms/.test(normalised().slice(from)), `the rebuild after ${changed} to finish`)
},
async stop() {
result.kill()
await result.then(() => {}, () => {})
},
}
}

export async function waitFor(check: () => Promise<boolean> | boolean, timeout = 60_000) {
export async function waitFor(check: () => Promise<boolean> | boolean, timeout = 60_000, interval = 250) {
const end = Date.now() + timeout
while (!await check()) {
if (Date.now() > end) {
throw new Error('Timed out')
}
await delay(250)
await delay(interval)
}
}

Expand Down
87 changes: 49 additions & 38 deletions test/watch.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { createHash } from 'node:crypto'
import { writeFileSync } from 'node:fs'
import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { setTimeout as delay } from 'node:timers/promises'
import { pathToFileURL } from 'node:url'
import { join, relative } from 'pathe'
import { basename, dirname, join, relative } from 'pathe'
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
import type { TestContext } from 'vitest'

Expand All @@ -26,21 +26,31 @@ async function outputs(dir: string) {
})))
}

async function addDirectory(dir: string, target: string, files: Record<string, string>) {
const staging = join(dir, '.staging', basename(target))
await rm(staging, { recursive: true, force: true })
for (const [file, contents] of Object.entries(files)) {
await mkdir(dirname(join(staging, file)), { recursive: true })
await writeFile(join(staging, file), contents)
}
await rename(staging, join(dir, target))
}

describe.concurrent('tsdown --watch', () => {
describe('with a module whose entry imports runtime code', () => {
let dir: string
let watcher: ReturnType<typeof watch>
const dist = (file: string) => join(dir, 'dist', file)
const builds = (from = 0) => watcher.output().slice(from).split(BUILD_STARTED).slice(1)
const starts = (from = 0) => watcher.output().slice(from).split(BUILD_STARTED).slice(1)
const changed = (from: number) => [...new Set([...watcher.output().slice(from).matchAll(/Watched change: ([^\n]+)/g)].map(match => relative(dir, match[1]!.trim())))]
const settled = async () => {
let started = -1
await waitFor(() => {
const count = builds().length
const count = starts().length
const idle = count === started && count === (watcher.output().match(/Rebuilt in|Build failed with/g)?.length ?? 0)
started = count
return idle
})
}, watcher.timeout())
}
let previous = Promise.resolve()
const finished: Array<() => void> = []
Expand Down Expand Up @@ -85,54 +95,56 @@ describe.concurrent('tsdown --watch', () => {
})

it('should report the size of each entry and runtime directory once', inOrder(async () => {
expect(builds().map(build => sizeRows(build))).toEqual([['dist/module.mjs', 'dist/runtime/']])
expect(starts().map(build => sizeRows(build))).toEqual([['dist/module.mjs', 'dist/runtime/']])
expect(JSON.parse(await read(dist('module.json'))).name).toBe('from-runtime')
}))

it('should rewrite `module.json` when a file the module entry imports changes', inOrder(async () => {
writeFileSync(join(dir, 'src/runtime/name.ts'), `export const moduleName: string = 'changed-runtime'\n`)
await waitFor(async () => JSON.parse(await read(dist('module.json'))).name === 'changed-runtime')
await watcher.rebuild(() => writeFile(join(dir, 'src/runtime/name.ts'), `export const moduleName: string = 'changed-runtime'\n`), join(dir, 'src/runtime/name.ts'))
expect(JSON.parse(await read(dist('module.json'))).name).toBe('changed-runtime')
}))

it('should rebuild when a file is added to the runtime directory', inOrder(async () => {
await mkdir(join(dir, 'src/runtime/utils/nested'), { recursive: true })
writeFileSync(join(dir, 'src/runtime/utils/nested/added.ts'), `export const added: string = 'added'\n`)
await waitFor(() => exists(dist('runtime/utils/nested/added.js')) && exists(dist('runtime/utils/nested/added.d.ts')))
await watcher.rebuild(() => addDirectory(dir, 'src/runtime/utils', { 'nested/added.ts': `export const added: string = 'added'\n` }), join(dir, 'src/runtime/utils/nested/added.ts'))
expect(exists(dist('runtime/utils/nested/added.js'))).toBe(true)
expect(exists(dist('runtime/utils/nested/added.d.ts'))).toBe(true)
}))

it('should compile JSX in a server runtime file added', inOrder(async () => {
await mkdir(join(dir, 'src/runtime/server'), { recursive: true })
writeFileSync(join(dir, 'src/runtime/server/render.tsx'), `export const render = (): unknown => <p>hi</p>\n`)
await waitFor(() => exists(dist('runtime/server/render.js')) || exists(dist('runtime/server/render.jsx')))
await watcher.rebuild(() => addDirectory(dir, 'src/runtime/server', { 'render.tsx': `export const render = (): unknown => <p>hi</p>\n` }), join(dir, 'src/runtime/server/render.tsx'))
expect(exists(dist('runtime/server/render.js'))).toBe(true)
expect(exists(dist('runtime/server/render.jsx'))).toBe(false)
expect(await read(dist('runtime/server/render.js'))).toContain('vue/jsx-runtime')
}))

it('should rebuild when a file outside the runtime directory that a runtime file imports changes', inOrder(async () => {
await waitFor(async () => (await read(dist('shared.js'))).includes('first'))
writeFileSync(join(dir, 'src/shared.ts'), `export const shared: string = 'second'\n`)
await waitFor(async () => (await read(dist('shared.js'))).includes('second'))
expect(await read(dist('shared.js'))).toContain('first')
await watcher.rebuild(() => writeFile(join(dir, 'src/shared.ts'), `export const shared: string = 'second'\n`), join(dir, 'src/shared.ts'))
expect(await read(dist('shared.js'))).toContain('second')
}))

it('should remove the output of a deleted runtime file', inOrder(async () => {
expect(exists(dist('runtime/removed.js'))).toBe(true)
await rm(join(dir, 'src/runtime/removed.ts'))
await waitFor(() => !exists(dist('runtime/removed.js')) && !exists(dist('runtime/removed.d.ts')))
await watcher.rebuild(() => rm(join(dir, 'src/runtime/removed.ts')), join(dir, 'src/runtime/removed.ts'))
expect(exists(dist('runtime/removed.js'))).toBe(false)
expect(exists(dist('runtime/removed.d.ts'))).toBe(false)
expect(exists(dist('runtime/plugins/plugin.js'))).toBe(true)
}))

it('should rewrite `#app` in an added declaration file', inOrder(async () => {
writeFileSync(join(dir, 'src/runtime/composables/added.d.ts'), `import type { NuxtApp } from '#app'\nexport type Added = NuxtApp\n`)
await waitFor(async () => exists(dist('runtime/composables/added.d.ts')) && (await read(dist('runtime/composables/added.d.ts'))).includes(`from 'nuxt/app'`))
const added = join(dir, 'src/runtime/composables/added.d.ts')
await watcher.rebuild(() => writeFile(added, `import type { NuxtApp } from '#app'\nexport type Added = NuxtApp\n`), added)
expect(await read(dist('runtime/composables/added.d.ts'))).toContain(`from 'nuxt/app'`)
}))

it('should rewrite `types.d.mts` when the module entry changes, and report sizes once per rebuild', inOrder(async () => {
const seen = watcher.output().length
writeFileSync(join(dir, 'src/module.ts'), `${await read(dir, 'src/module.ts')}\nexport const rebuiltMarker: string = 'rebuilt'\n`)
await waitFor(async () => (await read(dist('types.d.mts'))).includes('rebuiltMarker'))
const source = await read(dir, 'src/module.ts')
await watcher.rebuild(() => writeFile(join(dir, 'src/module.ts'), `${source}\nexport const rebuiltMarker: string = 'rebuilt'\n`), join(dir, 'src/module.ts'))
await settled()
expect(await read(dist('types.d.mts'))).toContain('rebuiltMarker')
expect(changed(seen)).toEqual(['src/module.ts'])
const rebuilt = builds(seen).filter(build => /Rebuilt in/.test(build))
const rebuilt = starts(seen).filter(build => /Rebuilt in/.test(build))
expect(rebuilt.map(build => sizeRows(build))).toEqual(rebuilt.map(() => ['dist/module.mjs', 'dist/runtime/']))
expect(JSON.parse(await read(dist('module.json'))).name).toBe('changed-runtime')
}))
Expand All @@ -150,23 +162,22 @@ describe.concurrent('tsdown --watch', () => {
await waitFor(() => /error/i.test(watcher.output().slice(seen)))
await delay(1000)
expect(await Promise.all(files.map(output => read(output)))).toEqual(before)
writeFileSync(join(dir, file), `${source}\nexport const recoveredMarker: string = 'recovered'\n`)
await waitFor(async () => (await read(dist(recovered))).includes('recoveredMarker'))
await watcher.rebuild(() => writeFile(join(dir, file), `${source}\nexport const recoveredMarker: string = 'recovered'\n`), join(dir, file))
expect(await read(dist(recovered))).toContain('recoveredMarker')
}))
}

it('should keep the previous declarations when a rebuild of a component fails, and recover on the next good save', inOrder(async () => {
const file = join(dir, 'src/runtime/components/TestMeSetup.vue')
const source = await read(file)
const before = await read(dist('runtime/components/TestMeSetup.d.vue.ts'))
let seen = watcher.output().length
const seen = watcher.output().length
writeFileSync(file, source.replace('defineProps<{ count: number }>()', 'defineProps<{ count: number }>(\n'))
await waitFor(() => /error/i.test(watcher.output().slice(seen)))
await delay(1000)
expect(await read(dist('runtime/components/TestMeSetup.d.vue.ts'))).toBe(before)
seen = watcher.output().length
writeFileSync(file, source.replace('count: number', 'count: number, recovered?: boolean'))
await waitFor(async () => (await read(dist('runtime/components/TestMeSetup.d.vue.ts'))).includes('recovered') && /Rebuilt in/.test(watcher.output().slice(seen)))
await watcher.rebuild(() => writeFile(file, source.replace('count: number', 'count: number, recovered?: boolean')), file)
expect(await read(dist('runtime/components/TestMeSetup.d.vue.ts'))).toContain('recovered')
}))

it('should emit the same files as a one-off build of the same sources', inOrder(async () => {
Expand All @@ -180,16 +191,16 @@ describe.concurrent('tsdown --watch', () => {

it('should rebuild when a file is added to a missing runtime directory', async ({ onTestFailed }) => {
const dir = await fixture('.temp-watch/without-runtime', {
config: PLUGIN,
config: WATCHED_PLUGIN,
remove: ['src/runtime'],
module: `import { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({ meta: { name: 'my-module' } })\n`,
})
const watcher = watch(dir, [tsdownBin, '--watch'], onTestFailed)
try {
await waitFor(() => exists(dir, 'dist/module.json'))
await mkdir(join(dir, 'src/runtime/utils'), { recursive: true })
await writeFile(join(dir, 'src/runtime/utils/added.ts'), `export const added: string = 'added'\n`)
await waitFor(() => exists(dir, 'dist/runtime/utils/added.js') && exists(dir, 'dist/runtime/utils/added.d.ts'))
await waitFor(() => watcher.builds() > 0)
await watcher.rebuild(() => addDirectory(dir, 'src/runtime', { 'utils/added.ts': `export const added: string = 'added'\n` }), join(dir, 'src/runtime/utils/added.ts'))
expect(exists(dir, 'dist/runtime/utils/added.js')).toBe(true)
expect(exists(dir, 'dist/runtime/utils/added.d.ts')).toBe(true)
}
finally {
await watcher.stop()
Expand All @@ -214,7 +225,7 @@ describe.concurrent('tsdown --watch', () => {
try {
await waitFor(async () => {
missing ||= !exists(distDir, 'module.mjs') || !exists(distDir, 'runtime/plugins/plugin.js')
return /Rebuilt in/.test(watcher.output())
return watcher.builds() > 0
})
const after = await outputs(distDir)
expect(missing).toBe(false)
Expand All @@ -237,14 +248,14 @@ describe.concurrent('tsdown --watch', () => {
removed: [...before.keys()].filter(file => !after.has(file)).sort(),
})
const watcher = watch(dir, [tsdownBin, '--watch'], onTestFailed)
const rebuilds = () => watcher.output().match(/Rebuilt in/g)?.length ?? 0
const rebuilds = () => watcher.builds()
const rebuild = async (change: () => Promise<void>, file?: string) => {
const before = await outputs(distDir)
const count = rebuilds()
const seen = watcher.output().length
const rebuilt = file && new RegExp(`Found [^\\n]*${escapeRegExp(file)}[^\\n]* changed[\\s\\S]*Rebuilt in`)
await change()
await waitFor(() => rebuilt ? rebuilt.test(watcher.output().slice(seen).replaceAll('\\', '/')) : rebuilds() > count)
await waitFor(() => rebuilt ? rebuilt.test(watcher.output().slice(seen).replaceAll('\\', '/')) : rebuilds() > count, watcher.timeout(), 50)
return changes(before, await outputs(distDir))
}
const edit = (file: string, from: string, to: string) => rebuild(async () => writeFileSync(join(dir, file), (await read(dir, file)).replace(from, to)), file)
Expand Down
Loading