diff --git a/bin/pest-tia-vite-deps.mjs b/bin/pest-tia-vite-deps.mjs index f39af395..7ab3905b 100644 --- a/bin/pest-tia-vite-deps.mjs +++ b/bin/pest-tia-vite-deps.mjs @@ -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 = /]*)>([\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 `\n", + ['imports' => ['@/A.vue'], 'moduleType' => 'js'], + ], + 'plain-script-with-default' => [ + "", + ['imports' => ['@/A.vue'], 'moduleType' => 'js'], + ], + 'typescript-lang' => [ + "", + ['imports' => ['@/types', '@/B.vue'], 'moduleType' => 'ts'], + ], + 'lang-tsx' => [ + "", + ['imports' => ['@/C.vue'], 'moduleType' => 'ts'], + ], + 'lang-unquoted' => [ + "", + ['imports' => ['@/D.vue'], 'moduleType' => 'ts'], + ], + 'both-script-blocks' => [ + "\n", + ['imports' => ['@/A.vue', '@/B.vue'], 'moduleType' => 'js'], + ], + 'template-only' => [ + '', + ['imports' => [], 'moduleType' => 'js'], + ], + 'style-block-ignored' => [ + "\n", + ['imports' => ['@/A.vue'], 'moduleType' => 'js'], + ], + 'dynamic-import' => [ + "", + ['imports' => ['@/Lazy.vue'], 'moduleType' => 'js'], + ], + 'svelte-component' => [ + "\n

hi

", + ['imports' => ['./A.svelte'], 'moduleType' => 'js'], + ], + 'no-script-at-all' => [ + '
plain markup
', + ['imports' => [], 'moduleType' => 'js'], + ], + 'default-export-in-line-comment' => [ + "", + ['imports' => ['@/A.vue'], 'moduleType' => 'js'], + ], + 'default-export-in-block-comment' => [ + "", + ['imports' => ['@/A.vue'], 'moduleType' => 'js'], + ], + 'default-export-in-string' => [ + "", + ['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 = << 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 = <<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('and(tiaSfcResults()['style-block-ignored']['code'])->not->toContain('color: red') + ->and(tiaSfcResults()['script-setup']['code'])->not->toContain('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' + + + VUE); + file_put_contents($root.'/resources/js/components/Widget.vue', <<<'VUE' + + + 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'], + ]); +}); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 77e31c06..df90709f 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -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, 1675 passed (3682 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1727 passed (3739 assertions)'; expect($output) ->toContain("Tests: {$expected}")