Compare commits

..

3 Commits

Author SHA1 Message Date
Punyapal Shah ff1292102c release: 5.3.7 (#2037) 2026-11-16 23:20:56 +05:30
atymic 433b9893d4 fix(tia): parse SFC entries when building the JS module graph (#1919)
* fix(tia): parse SFC entries when building the JS module graph

rolldown has no SFC handling, so every .vue/.svelte page failed to parse at the
first byte of <script> and the JS graph came back empty. Reduce the component to
its script blocks before rolldown sees it, which is enough for import specifiers.

Closes #1918

* fix(tia): keep template-only TS imports and stub CSS as JS

TypeScript elision dropped imports used only in a <template>, so lang="ts" pages lost those edges. Newer rolldown also rejects asset stubs without an explicit moduleType, failing the build on any CSS import.

* fix(tia): ignore comments when detecting default export

* Refresh SFC module graph regression snapshots

---------

Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-16 23:05:31 +05:30
Jasper Tey 2d9dcd750a fix(tia): answer the stream_lock support probe (#2029)
* fix(tia): answer the stream_lock support probe

* Refresh stream lock regression snapshots

* Correct scoped callback typing and PHPStan compatibility

---------

Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-16 19:27:18 +05:30
11 changed files with 410 additions and 16 deletions
+90 -9
View File
@@ -12,6 +12,8 @@ const PAGE_EXTENSIONS = new Set([
'.ts', '.js',
'.mts', '.cts', '.mjs', '.cjs',
])
const SFC_RE = /\.(vue|svelte)$/i
const SCRIPT_BLOCK_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi
const ASSET_EXT_RE = /\.(css|scss|sass|less|styl|stylus|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|eot|otf|md|mdx|txt|html|mp4|webm|mp3|wav|ogg|m4a|pdf|wasm|glsl|frag|vert)$/i
const PROJECT_ROOT = resolve(process.argv[2] ?? process.cwd())
const PAGE_DIR_CANDIDATES = [
@@ -172,6 +174,79 @@ export async function loadAliasFromViteConfig(projectRoot = PROJECT_ROOT) {
return alias
}
// Comments and string contents are blanked so a mention of `export default` in either is
// not taken for a real one. Only used to detect the export, never handed to rolldown.
export function stripJsCommentsAndStrings(code) {
let out = ''
let quote = ''
for (let i = 0; i < code.length; i++) {
const c = code[i]
const n = code[i + 1]
if (quote) {
if (c === '\\') { i++; continue }
if (c === quote) { quote = ''; out += c }
else if (c === '\n') out += c
continue
}
if (c === '"' || c === "'" || c === '`') { quote = c; out += c; continue }
if (c === '/' && n === '/') {
const end = code.indexOf('\n', i)
if (end === -1) break
i = end - 1
continue
}
if (c === '/' && n === '*') {
const end = code.indexOf('*/', i + 2)
if (end === -1) break
out += ' '
i = end + 1
continue
}
out += c
}
return out
}
// rolldown has no SFC handling, so a `.vue`/`.svelte` entry fails to parse at the first
// byte of `<script>`. Only import specifiers are needed, so the markup is dropped.
export function extractSfcScript(raw) {
let code = ''
let lang = null
for (const m of raw.matchAll(SCRIPT_BLOCK_RE)) {
if (lang === null) {
const l = /\blang\s*=\s*["']?([\w-]+)/i.exec(m[1] || '')
if (l) lang = l[1].toLowerCase()
}
code += m[2] + '\n'
}
// `<script setup>` and template-only components carry no literal `export default`,
// which importers resolve against: without one rolldown fails with MISSING_EXPORT.
if (!/(^|[\s;}])export\s+default\b/.test(stripJsCommentsAndStrings(code))) code += '\nexport default {}\n'
return {
code,
moduleType: lang === 'ts' || lang === 'tsx' ? 'ts' : 'js',
moduleSideEffects: false,
}
}
// rolldown no longer bundles CSS, so a stub without an explicit `moduleType` is
// rejected as an unsupported module and fails the whole build.
export function stubAsset(id) {
if (!id || !ASSET_EXT_RE.test(id)) return null
return { code: 'export default null', moduleType: 'js', moduleSideEffects: false }
}
// A component used only in a `<template>` has no binding the extracted script reads,
// so TypeScript elision would drop its import and the edge with it.
export const TRANSFORM_OPTIONS = { jsx: 'preserve', typescript: { onlyRemoveTypeImports: true } }
async function listPageFiles(pagesDir) {
if (!existsSync(pagesDir)) return []
@@ -289,15 +364,21 @@ async function main() {
},
}
const sfcScript = {
name: 'pest-tia-sfc-script',
async load(id) {
if (!id || !SFC_RE.test(id)) return null
let raw
try { raw = await readFile(id, 'utf8') } catch { return null }
return extractSfcScript(raw)
},
}
const assetStub = {
name: 'pest-tia-asset-stub',
load(id) {
if (!id) return null
if (ASSET_EXT_RE.test(id)) {
return { code: 'export default null', moduleSideEffects: false }
}
return null
},
load: stubAsset,
}
const input = Object.create(null)
@@ -310,9 +391,9 @@ async function main() {
alias,
extensions: ['.tsx', '.ts', '.jsx', '.js', '.mts', '.cts', '.mjs', '.cjs', '.json', '.vue', '.svelte'],
},
transform: { jsx: 'preserve' },
transform: TRANSFORM_OPTIONS,
treeshake: false,
plugins: [externalBare, assetStub, collector],
plugins: [externalBare, assetStub, sfcScript, collector],
logLevel: 'silent',
onLog: () => {},
})
+1
View File
@@ -65,6 +65,7 @@
"pestphp/pest-plugin-phpstan": "^5.3.1",
"pestphp/pest-plugin-rector": "^5.0.6",
"pestphp/pest-plugin-type-coverage": "^5.1.0",
"phpstan/phpstan": "^2.3.5 <2.3.6",
"psy/psysh": "^0.12.24"
},
"minimum-stability": "dev",
+1 -1
View File
@@ -71,7 +71,7 @@ final class HigherOrderExpectation
}
/**
* @param Closure(Expectation<TValue>): void $expectation
* @param Closure(Expectation<TValue>|EachExpectation<TValue>): void $expectation
* @return HigherOrderExpectation<TOriginalValue, TOriginalValue>
*/
public function scoped(Closure $expectation): self
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Pest;
function version(): string
{
return '5.3.6';
return '5.3.7';
}
function testDirectory(string $file = ''): string
+4
View File
@@ -197,6 +197,10 @@ final class ReadCapture
*/
public function stream_lock(int $operation): bool
{
if (($operation & ~LOCK_NB) === 0) {
return true;
}
return $this->forward('stream_lock', fn (mixed $resource): bool => flock($resource, $operation), $operation) === true;
}
@@ -1,5 +1,5 @@
Pest Testing Framework 5.3.6.
Pest Testing Framework 5.3.7.
USAGE: pest <file> [options]
@@ -1,3 +1,3 @@
Pest Testing Framework 5.3.6.
Pest Testing Framework 5.3.7.
+56 -2
View File
@@ -2037,6 +2037,7 @@
✓ the file wrapper → it is replaced while a test records and restored after it
✓ the file wrapper → it is restored when the recorder resets
✓ the file wrapper → it passes filesystem operations through while a test records
✓ the file wrapper → it writes with LOCK_EX while a test records
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file"
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link"
✓ a wrapper already registered for file:// → it opens reads through it and still links them
@@ -2085,7 +2086,7 @@
✓ isTestFile() → it honours a bare .php suffix
✓ isTestFile() → it does not require a dot before the suffix
PASS Tests\Unit\Plugins\Tia\ViteDepsHelper
WARN Tests\Unit\Plugins\Tia\ViteDepsHelper
✓ it strips JSONC down to something JSON.parse accepts with ('plain-object')
✓ it strips JSONC down to something JSON.parse accepts with ('plain-array')
✓ it strips JSONC down to something JSON.parse accepts with ('nested')
@@ -2158,6 +2159,59 @@
✓ it accepts a page directory candidate only when it matches the casing on disk with ('wrong leaf')
✓ it accepts a page directory candidate only when it matches the casing on disk with ('wrong parent')
✓ it accepts a page directory candidate only when it matches the casing on disk with ('absent')
✓ it keeps every import a single file component declares with ('script-setup')
✓ it keeps every import a single file component declares with ('plain-script-with-default')
✓ it keeps every import a single file component declares with ('typescript-lang')
✓ it keeps every import a single file component declares with ('lang-tsx')
✓ it keeps every import a single file component declares with ('lang-unquoted')
✓ it keeps every import a single file component declares with ('both-script-blocks')
✓ it keeps every import a single file component declares with ('template-only')
✓ it keeps every import a single file component declares with ('style-block-ignored')
✓ it keeps every import a single file component declares with ('dynamic-import')
✓ it keeps every import a single file component declares with ('svelte-component')
✓ it keeps every import a single file component declares with ('no-script-at-all')
✓ it keeps every import a single file component declares with ('default-export-in-line-comment')
✓ it keeps every import a single file component declares with ('default-export-in-block-comment')
✓ it keeps every import a single file component declares with ('default-export-in-string')
✓ it reports the script block language so the parser matches it with ('script-setup')
✓ it reports the script block language so the parser matches it with ('plain-script-with-default')
✓ it reports the script block language so the parser matches it with ('typescript-lang')
✓ it reports the script block language so the parser matches it with ('lang-tsx')
✓ it reports the script block language so the parser matches it with ('lang-unquoted')
✓ it reports the script block language so the parser matches it with ('both-script-blocks')
✓ it reports the script block language so the parser matches it with ('template-only')
✓ it reports the script block language so the parser matches it with ('style-block-ignored')
✓ it reports the script block language so the parser matches it with ('dynamic-import')
✓ it reports the script block language so the parser matches it with ('svelte-component')
✓ it reports the script block language so the parser matches it with ('no-script-at-all')
✓ it reports the script block language so the parser matches it with ('default-export-in-line-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-block-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-string')
✓ it always leaves a default export for importers to resolve against with ('script-setup')
✓ it always leaves a default export for importers to resolve against with ('plain-script-with-default')
✓ it always leaves a default export for importers to resolve against with ('typescript-lang')
✓ it always leaves a default export for importers to resolve against with ('lang-tsx')
✓ it always leaves a default export for importers to resolve against with ('lang-unquoted')
✓ it always leaves a default export for importers to resolve against with ('both-script-blocks')
✓ it always leaves a default export for importers to resolve against with ('template-only')
✓ it always leaves a default export for importers to resolve against with ('style-block-ignored')
✓ it always leaves a default export for importers to resolve against with ('dynamic-import')
✓ it always leaves a default export for importers to resolve against with ('svelte-component')
✓ it always leaves a default export for importers to resolve against with ('no-script-at-all')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-line-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-block-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-string')
✓ it does not add a second default export when the block already has one
✓ it drops template and style markup that the parser would reject
✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/resources/css/app.css')
✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/logo.svg')
✓ it leaves source modules for the other loaders with ('/app/Page.vue')
✓ it leaves source modules for the other loaders with ('/app/util.ts')
✓ it keeps value imports that only a template uses through the TypeScript transform
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-line-comment')
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-block-comment')
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-string')
- it bundles a script setup component that mentions export default in a comment → rolldown is not resolvable.
PASS Tests\Unit\Plugins\Tia\WatchPatterns
✓ it keeps the built-in fallbacks enabled by default
@@ -2388,4 +2442,4 @@
✓ pass with dataset with ('my-datas-set-value')
✓ within describe → pass with dataset with ('my-datas-set-value')
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 37 skipped, 1703 passed (3758 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1756 passed (3817 assertions)
+15
View File
@@ -187,6 +187,21 @@ describe('the file wrapper', function (): void {
]);
});
it('writes with LOCK_EX while a test records', function (): void {
$path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-lock-'.bin2hex(random_bytes(8));
try {
tiaReadCaptureLinks(function () use ($path, &$written): void {
$written = file_put_contents($path, 'locked', LOCK_EX);
});
expect($written)->toBe(6)
->and(file_get_contents($path))->toBe('locked');
} finally {
@unlink($path);
}
});
it('reports symlinks as links while a test records', function (bool $targetExists, bool $expectedExists): void {
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-'.bin2hex(random_bytes(8));
mkdir($directory);
+239
View File
@@ -414,6 +414,147 @@ function tiaViteCasingResults(): array
return $cache = $results;
}
function tiaSfcFixtures(): array
{
return [
'script-setup' => [
"<script setup>\nimport A from '@/A.vue'\n</script>\n<template><A /></template>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'plain-script-with-default' => [
"<script>\nimport A from '@/A.vue'\nexport default { components: { A } }\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'typescript-lang' => [
"<script setup lang=\"ts\">\nimport type { Foo } from '@/types'\nimport B from '@/B.vue'\n</script>",
['imports' => ['@/types', '@/B.vue'], 'moduleType' => 'ts'],
],
'lang-tsx' => [
"<script setup lang=\"tsx\">\nimport C from '@/C.vue'\n</script>",
['imports' => ['@/C.vue'], 'moduleType' => 'ts'],
],
'lang-unquoted' => [
"<script setup lang=ts>\nimport D from '@/D.vue'\n</script>",
['imports' => ['@/D.vue'], 'moduleType' => 'ts'],
],
'both-script-blocks' => [
"<script>\nimport A from '@/A.vue'\nexport default {}\n</script>\n<script setup>\nimport B from '@/B.vue'\n</script>",
['imports' => ['@/A.vue', '@/B.vue'], 'moduleType' => 'js'],
],
'template-only' => [
'<template><div>hello</div></template>',
['imports' => [], 'moduleType' => 'js'],
],
'style-block-ignored' => [
"<script setup>\nimport A from '@/A.vue'\n</script>\n<style scoped>\n.a { color: red }\n</style>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'dynamic-import' => [
"<script setup>\nconst C = () => import('@/Lazy.vue')\n</script>",
['imports' => ['@/Lazy.vue'], 'moduleType' => 'js'],
],
'svelte-component' => [
"<script>\nimport A from './A.svelte'\n</script>\n<h1>hi</h1>",
['imports' => ['./A.svelte'], 'moduleType' => 'js'],
],
'no-script-at-all' => [
'<div>plain markup</div>',
['imports' => [], 'moduleType' => 'js'],
],
'default-export-in-line-comment' => [
"<script setup>\n// export default is generated by Vue\nimport A from '@/A.vue'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'default-export-in-block-comment' => [
"<script setup>\n/* export default {} */\nimport A from '@/A.vue'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'default-export-in-string' => [
"<script setup>\nimport A from '@/A.vue'\nconst hint = 'export default'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
];
}
function tiaSfcResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$payload = [];
foreach (tiaSfcFixtures() as $name => [$raw]) {
$payload[] = ['name' => $name, 'raw' => $raw];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-sfc-');
file_put_contents($inputFile, json_encode($payload));
$helper = str_replace('\\', '/', tiaViteHelperPath());
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { extractSfcScript } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) {
const r = extractSfcScript(c.raw)
const imports = [...r.code.matchAll(/(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g)].map((m) => m[1])
out[c.name] = { code: r.code, moduleType: r.moduleType, imports }
}
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
@unlink($inputFile);
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
function tiaRolldownPackageDir(): ?string
{
$locate = fn (array $command, ?string $cwd = null): ?string => ($process = new Process($command, $cwd))->run() === 0
? (trim($process->getOutput()) ?: null)
: null;
$paths = [dirname(__DIR__, 4)];
if (($global = $locate(['npm', 'root', '-g'])) !== null) {
$paths[] = $global;
}
$manifest = $locate(['node', '-p', "require.resolve('rolldown/package.json', { paths: process.argv.slice(1) })", ...$paths]);
return $manifest === null ? null : dirname($manifest);
}
function tiaBuildOptionResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$helper = str_replace('\\', '/', tiaViteHelperPath());
$script = <<<JS
import { stubAsset, TRANSFORM_OPTIONS } from '{$helper}'
const stubs = {}
for (const id of ['/app/resources/css/app.css', '/app/logo.svg', '/app/Page.vue', '/app/util.ts']) {
stubs[id] = stubAsset(id)
}
process.stdout.write(JSON.stringify({ stubs, transform: TRANSFORM_OPTIONS }))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
beforeEach(function (): void {
if ((new ExecutableFinder)->find('node') === null) {
$this->markTestSkipped('node is not available.');
@@ -472,3 +613,101 @@ it('accepts a page directory candidate only when it matches the casing on disk',
expect(tiaViteCasingResults()[$name])->toBe($expected);
})->with(array_keys(tiaViteCasingFixtures()));
it('keeps every import a single file component declares', function (string $name): void {
[, $expected] = tiaSfcFixtures()[$name];
expect(tiaSfcResults()[$name]['imports'])->toEqual($expected['imports']);
})->with(array_keys(tiaSfcFixtures()));
it('reports the script block language so the parser matches it', function (string $name): void {
[, $expected] = tiaSfcFixtures()[$name];
expect(tiaSfcResults()[$name]['moduleType'])->toBe($expected['moduleType']);
})->with(array_keys(tiaSfcFixtures()));
it('always leaves a default export for importers to resolve against', function (string $name): void {
expect(tiaSfcResults()[$name]['code'])->toMatch('/export\s+default\b/');
})->with(array_keys(tiaSfcFixtures()));
it('does not add a second default export when the block already has one', function (): void {
preg_match_all('/export\s+default\b/', tiaSfcResults()['plain-script-with-default']['code'], $matches);
expect($matches[0])->toHaveCount(1);
});
it('drops template and style markup that the parser would reject', function (): void {
expect(tiaSfcResults()['style-block-ignored']['code'])->not->toContain('<style')
->and(tiaSfcResults()['style-block-ignored']['code'])->not->toContain('color: red')
->and(tiaSfcResults()['script-setup']['code'])->not->toContain('<template');
});
it('stubs assets as JS modules so rolldown does not reject them as CSS', function (string $id): void {
expect(tiaBuildOptionResults()['stubs'][$id])->toBe([
'code' => 'export default null',
'moduleType' => 'js',
'moduleSideEffects' => false,
]);
})->with(['/app/resources/css/app.css', '/app/logo.svg']);
it('leaves source modules for the other loaders', function (string $id): void {
expect(tiaBuildOptionResults()['stubs'][$id])->toBeNull();
})->with(['/app/Page.vue', '/app/util.ts']);
it('keeps value imports that only a template uses through the TypeScript transform', function (): void {
expect(tiaBuildOptionResults()['transform']['typescript']['onlyRemoveTypeImports'])->toBeTrue();
});
it('ignores a default export that only appears in a comment or string', function (string $name): void {
preg_match_all('/export\s+default\b/', tiaSfcResults()[$name]['code'], $matches);
expect(tiaSfcResults()[$name]['code'])->toEndWith("\nexport default {}\n")
->and($matches[0])->toHaveCount(2);
})->with(['default-export-in-line-comment', 'default-export-in-block-comment', 'default-export-in-string']);
it('bundles a script setup component that mentions export default in a comment', function (): void {
$rolldown = tiaRolldownPackageDir();
if ($rolldown === null) {
$this->markTestSkipped('rolldown is not resolvable.');
}
$root = sys_get_temp_dir().'/pest-tia-rolldown-'.bin2hex(random_bytes(6));
mkdir($root.'/resources/js/pages', 0755, true);
mkdir($root.'/resources/js/components', 0755, true);
mkdir($root.'/node_modules', 0755, true);
$root = realpath($root);
symlink($rolldown, $root.'/node_modules/rolldown');
file_put_contents($root.'/package.json', '{}');
file_put_contents($root.'/resources/js/pages/Dashboard.vue', <<<'VUE'
<script setup>
import Widget from '../components/Widget.vue'
</script>
<template><Widget /></template>
VUE);
file_put_contents($root.'/resources/js/components/Widget.vue', <<<'VUE'
<script setup>
// export default is generated by Vue
import { format } from './format.js'
</script>
<template>{{ format(1) }}</template>
VUE);
file_put_contents($root.'/resources/js/components/format.js', "export const format = (v) => String(v)\n");
$process = new Process(['node', tiaViteHelperPath(), $root]);
$process->run();
unlink($root.'/node_modules/rolldown');
foreach (['resources/js/pages/Dashboard.vue', 'resources/js/components/Widget.vue', 'resources/js/components/format.js', 'package.json'] as $file) {
@unlink($root.'/'.$file);
}
foreach (['node_modules', 'resources/js/pages', 'resources/js/components', 'resources/js', 'resources', ''] as $dir) {
@rmdir($root.'/'.$dir);
}
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toMatchArray([
'resources/js/components/Widget.vue' => ['Dashboard'],
'resources/js/components/format.js' => ['Dashboard'],
]);
});
+1 -1
View File
@@ -21,7 +21,7 @@ test('parallel', function () use ($run): void {
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
$profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile');
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 29 skipped, 1674 passed (3680 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1727 passed (3739 assertions)';
expect($output)
->toContain("Tests: {$expected}")