-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
JavaScriptImportPathCompiler.php
209 lines (173 loc) · 7.93 KB
/
JavaScriptImportPathCompiler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\AssetMapper\Compiler;
use Psr\Log\LoggerInterface;
use Symfony\Component\AssetMapper\AssetMapperInterface;
use Symfony\Component\AssetMapper\Exception\CircularAssetsException;
use Symfony\Component\AssetMapper\Exception\RuntimeException;
use Symfony\Component\AssetMapper\ImportMap\ImportMapConfigReader;
use Symfony\Component\AssetMapper\ImportMap\JavaScriptImport;
use Symfony\Component\AssetMapper\MappedAsset;
use Symfony\Component\Filesystem\Path;
/**
* Resolves import paths in JS files.
*
* @author Ryan Weaver <ryan@symfonycasts.com>
*/
final class JavaScriptImportPathCompiler implements AssetCompilerInterface
{
// https://regex101.com/r/fquriB/1
private const IMPORT_PATTERN = '/(?:import\s*(?:(?:\*\s*as\s+\w+|[\w\s{},*]+)\s*from\s*)?|\bimport\()\s*[\'"`](\.\/[^\'"`]+|(\.\.\/)*[^\'"`]+)[\'"`]\s*[;\)]?/m';
public function __construct(
private readonly ImportMapConfigReader $importMapConfigReader,
private readonly string $missingImportMode = self::MISSING_IMPORT_WARN,
private readonly ?LoggerInterface $logger = null,
) {
}
public function compile(string $content, MappedAsset $asset, AssetMapperInterface $assetMapper): string
{
return preg_replace_callback(self::IMPORT_PATTERN, function ($matches) use ($asset, $assetMapper, $content) {
$fullImportString = $matches[0][0];
if ($this->isCommentedOut($matches[0][1], $content)) {
return $fullImportString;
}
$importedModule = $matches[1][0];
// we don't support absolute paths, so ignore completely
if (str_starts_with($importedModule, '/')) {
return $fullImportString;
}
$isRelativeImport = str_starts_with($importedModule, '.');
if (!$isRelativeImport) {
// URL or /absolute imports will also go here, but will be ignored
$dependentAsset = $this->findAssetForBareImport($importedModule, $assetMapper);
} else {
$dependentAsset = $this->findAssetForRelativeImport($importedModule, $asset, $assetMapper);
}
if (!$dependentAsset) {
return $fullImportString;
}
// List as a JavaScript import.
// This will cause the asset to be included in the importmap (for relative imports)
// and will be used to generate the preloads in the importmap.
$isLazy = str_contains($fullImportString, 'import(');
$addToImportMap = $isRelativeImport;
$asset->addJavaScriptImport(new JavaScriptImport(
$addToImportMap ? $dependentAsset->publicPathWithoutDigest : $importedModule,
$dependentAsset->logicalPath,
$dependentAsset->sourcePath,
$isLazy,
$addToImportMap,
));
if (!$addToImportMap) {
// only (potentially) adjust for automatic relative imports
return $fullImportString;
}
// support possibility where the final public files have moved relative to each other
$relativeImportPath = Path::makeRelative($dependentAsset->publicPathWithoutDigest, \dirname($asset->publicPathWithoutDigest));
$relativeImportPath = $this->makeRelativeForJavaScript($relativeImportPath);
return str_replace($importedModule, $relativeImportPath, $fullImportString);
}, $content, -1, $count, \PREG_OFFSET_CAPTURE);
}
public function supports(MappedAsset $asset): bool
{
return 'js' === $asset->publicExtension;
}
private function makeRelativeForJavaScript(string $path): string
{
if (str_starts_with($path, '../')) {
return $path;
}
return './'.$path;
}
private function handleMissingImport(string $message, \Throwable $e = null): void
{
match ($this->missingImportMode) {
AssetCompilerInterface::MISSING_IMPORT_IGNORE => null,
AssetCompilerInterface::MISSING_IMPORT_WARN => $this->logger?->warning($message),
AssetCompilerInterface::MISSING_IMPORT_STRICT => throw new RuntimeException($message, 0, $e),
};
}
/**
* Simple check for the most common types of comments.
*
* This is not a full parser, but should be good enough for most cases.
*/
private function isCommentedOut(mixed $offsetStart, string $fullContent): bool
{
$lineStart = strrpos($fullContent, "\n", $offsetStart - \strlen($fullContent));
$lineContentBeforeImport = substr($fullContent, $lineStart, $offsetStart - $lineStart);
$firstTwoChars = substr(ltrim($lineContentBeforeImport), 0, 2);
if ('//' === $firstTwoChars) {
return true;
}
if ('/*' === $firstTwoChars) {
$commentEnd = strpos($fullContent, '*/', $lineStart);
// if we can't find the end comment, be cautious: assume this is not a comment
if (false === $commentEnd) {
return false;
}
return $offsetStart < $commentEnd;
}
return false;
}
private function findAssetForBareImport(string $importedModule, AssetMapperInterface $assetMapper): ?MappedAsset
{
if (!$importMapEntry = $this->importMapConfigReader->findRootImportMapEntry($importedModule)) {
// don't warn on missing non-relative (bare) imports: these could be valid URLs
return null;
}
try {
if ($asset = $assetMapper->getAsset($importMapEntry->path)) {
return $asset;
}
return $assetMapper->getAssetFromSourcePath($this->importMapConfigReader->convertPathToFilesystemPath($importMapEntry->path));
} catch (CircularAssetsException $exception) {
return $exception->getIncompleteMappedAsset();
}
}
private function findAssetForRelativeImport(string $importedModule, MappedAsset $asset, AssetMapperInterface $assetMapper): ?MappedAsset
{
try {
$resolvedSourcePath = Path::join(\dirname($asset->sourcePath), $importedModule);
} catch (RuntimeException $e) {
// avoid warning about vendor imports - these are often comments
if (!$asset->isVendor) {
$this->handleMissingImport(sprintf('Error processing import in "%s": ', $asset->sourcePath).$e->getMessage(), $e);
}
return null;
}
try {
$dependentAsset = $assetMapper->getAssetFromSourcePath($resolvedSourcePath);
} catch (CircularAssetsException $exception) {
$dependentAsset = $exception->getIncompleteMappedAsset();
}
if ($dependentAsset) {
return $dependentAsset;
}
// avoid warning about vendor imports - these are often comments
if ($asset->isVendor) {
return null;
}
$message = sprintf('Unable to find asset "%s" imported from "%s".', $importedModule, $asset->sourcePath);
if (is_file($resolvedSourcePath)) {
$message .= sprintf('The file "%s" exists, but it is not in a mapped asset path. Add it to the "paths" config.', $resolvedSourcePath);
} else {
try {
if (null !== $assetMapper->getAssetFromSourcePath(sprintf('%s.js', $resolvedSourcePath))) {
$message .= sprintf(' Try adding ".js" to the end of the import - i.e. "%s.js".', $importedModule);
}
} catch (CircularAssetsException) {
// avoid circular error if there is self-referencing import comments
}
}
$this->handleMissingImport($message);
return null;
}
}