• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / assets / 15837508079

23 Jun 2025 11:40PM UTC coverage: 94.012% (+0.06%) from 93.952%
15837508079

push

github

dg
ViteMapper: supports sass & jsx on dev server

5 of 5 new or added lines in 1 file covered. (100.0%)

5 existing lines in 1 file now uncovered.

471 of 501 relevant lines covered (94.01%)

0.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.91
/src/Assets/ViteMapper.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Nette\Assets;
6

7
use Nette\Utils\FileSystem;
8
use Nette\Utils\Json;
9
use function array_filter, array_values, is_array, preg_match, str_starts_with;
10

11

12
/**
13
 * Maps asset references to Vite-generated files using a Vite manifest.json.
14
 * Supports both development mode (Vite dev server) and production mode.
15
 */
16
class ViteMapper implements Mapper
17
{
18
        private array $chunks;
19
        private array $dependencies = [];
20

21

22
        public function __construct(
1✔
23
                private readonly string $baseUrl,
24
                private readonly string $basePath,
25
                private readonly ?string $manifestPath = null,
26
                private readonly ?string $devServer = null,
27
                private readonly ?Mapper $publicMapper = null,
28
        ) {
29
                if ($devServer !== null && !str_starts_with($devServer, 'http')) {
1✔
30
                        throw new \InvalidArgumentException("Vite devServer must be absolute URL, '$devServer' given");
×
31
                }
32
        }
1✔
33

34

35
        /**
36
         * Retrieves an Asset for a given Vite entry point.
37
         * @throws AssetNotFoundException when the asset cannot be found in the manifest
38
         */
39
        public function getAsset(string $reference, array $options = []): Asset
1✔
40
        {
41
                Helpers::checkOptions($options);
1✔
42

43
                if ($this->devServer) {
1✔
44
                        return $this->createDevelopmentAsset($reference);
1✔
45
                }
46

47
                $this->chunks ??= $this->readChunks();
1✔
48

49
                if (isset($this->chunks[$reference])) {
1✔
50
                        return $this->createProductionAsset($reference);
1✔
51

52
                } elseif ($this->publicMapper) {
1✔
53
                        return $this->publicMapper->getAsset($reference);
1✔
54

55
                } else {
56
                        throw new AssetNotFoundException("File '$reference' not found in Vite manifest");
1✔
57
                }
58
        }
59

60

61
        private function createProductionAsset(string $reference): Asset
1✔
62
        {
63
                $chunk = $this->chunks[$reference];
1✔
64
                $entry = isset($chunk['isEntry']) || isset($chunk['isDynamicEntry']);
1✔
65
                if (str_starts_with($reference, '_') && !$entry) {
1✔
66
                        throw new AssetNotFoundException("Cannot directly access internal chunk '$reference'");
1✔
67
                }
68

69
                $dependencies = $this->collectDependencies($reference);
1✔
70
                unset($dependencies[$chunk['file']]);
1✔
71

72
                return $dependencies
1✔
73
                        ? new EntryAsset(
1✔
74
                                url: $this->baseUrl . '/' . $chunk['file'],
1✔
75
                                file: $this->basePath . '/' . $chunk['file'],
1✔
76
                                imports: array_values(array_filter($dependencies, fn($asset) => $asset instanceof StyleAsset)),
1✔
77
                                preloads: array_values(array_filter($dependencies, fn($asset) => $asset instanceof ScriptAsset)),
1✔
78
                                crossorigin: true,
1✔
79
                        )
80
                        : Helpers::createAssetFromUrl(
1✔
81
                                $this->baseUrl . '/' . $chunk['file'],
1✔
82
                                $this->basePath . '/' . $chunk['file'],
1✔
83
                                ['crossorigin' => true],
1✔
84
                        );
85
        }
86

87

88
        private function createDevelopmentAsset(string $reference): Asset
1✔
89
        {
90
                $url = $this->devServer . '/' . $reference;
1✔
91
                return match (true) {
92
                        (bool) preg_match('~\.(jsx?|mjs|tsx?)$~i', $reference) => new EntryAsset(
1✔
93
                                $url,
1✔
94
                                imports: [new ScriptAsset($this->devServer . '/@vite/client', type: 'module')],
1✔
95
                        ),
96
                        (bool) preg_match('~\.(sass|scss)$~i', $reference) => new StyleAsset($url),
1✔
97
                        default => Helpers::createAssetFromUrl($url),
1✔
98
                };
99
        }
100

101

102
        /**
103
         * Recursively collects all imports (including nested) from a chunk.
104
         */
105
        private function collectDependencies(string $chunkId): array
1✔
106
        {
107
                $deps = &$this->dependencies[$chunkId];
1✔
108
                if ($deps === null) {
1✔
109
                        $deps = [];
1✔
110
                        $chunk = $this->chunks[$chunkId] ?? [];
1✔
111
                        foreach ($chunk['css'] ?? [] as $file) {
1✔
112
                                $deps[$file] = Helpers::createAssetFromUrl(
1✔
113
                                        $this->baseUrl . '/' . $file,
1✔
114
                                        $this->basePath . '/' . $file,
1✔
115
                                        ['crossorigin' => true],
1✔
116
                                );
117
                        }
118
                        foreach ($chunk['imports'] ?? [] as $id) {
1✔
119
                                $file = $this->chunks[$id]['file'];
1✔
120
                                $deps[$file] = Helpers::createAssetFromUrl(
1✔
121
                                        $this->baseUrl . '/' . $file,
1✔
122
                                        $this->basePath . '/' . $file,
1✔
123
                                        ['type' => 'module', 'crossorigin' => true],
1✔
124
                                );
125
                                $deps += $this->collectDependencies($id);
1✔
126
                        }
127
                }
128
                return $deps;
1✔
129
        }
130

131

132
        private function readChunks(): array
133
        {
134
                $path = $this->manifestPath ?? $this->basePath . '/.vite/manifest.json';
1✔
135
                try {
136
                        $res = Json::decode(FileSystem::read($path), forceArrays: true);
1✔
UNCOV
137
                } catch (\Throwable $e) {
×
UNCOV
138
                        throw new \RuntimeException("Failed to read Vite manifest from '$path'. Did you run 'npm run build'?", 0, $e);
×
139
                }
140
                if (!is_array($res)) {
1✔
UNCOV
141
                        throw new \RuntimeException("Invalid Vite manifest format in '$path'");
×
142
                }
143
                return $res;
1✔
144
        }
145

146

147
        /**
148
         * Returns the base URL for this mapper.
149
         */
150
        public function getBaseUrl(): string
151
        {
UNCOV
152
                return $this->baseUrl;
×
153
        }
154

155

156
        /**
157
         * Returns the base path for this mapper.
158
         */
159
        public function getBasePath(): string
160
        {
UNCOV
161
                return $this->basePath;
×
162
        }
163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc