Skip to content

[AssetMapper] Warn of missing or incompat dependencies #51849

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2023
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"require": {
"php": ">=8.1",
"composer-runtime-api": ">=2.1",
"composer/semver": "^3.0",
"ext-xml": "*",
"friendsofphp/proxy-manager-lts": "^1.0.2",
"doctrine/event-manager": "^1.2|^2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use Symfony\Component\AssetMapper\ImportMap\ImportMapManager;
use Symfony\Component\AssetMapper\ImportMap\ImportMapRenderer;
use Symfony\Component\AssetMapper\ImportMap\ImportMapUpdateChecker;
use Symfony\Component\AssetMapper\ImportMap\ImportMapVersionChecker;
use Symfony\Component\AssetMapper\ImportMap\RemotePackageDownloader;
use Symfony\Component\AssetMapper\ImportMap\RemotePackageStorage;
use Symfony\Component\AssetMapper\ImportMap\Resolver\JsDelivrEsmResolver;
Expand Down Expand Up @@ -171,6 +172,12 @@
service('asset_mapper.importmap.resolver'),
])

->set('asset_mapper.importmap.version_checker', ImportMapVersionChecker::class)
->args([
service('asset_mapper.importmap.config_reader'),
service('asset_mapper.importmap.remote_package_downloader'),
])

->set('asset_mapper.importmap.resolver', JsDelivrEsmResolver::class)
->args([service('http_client')])

Expand Down Expand Up @@ -199,6 +206,7 @@
->args([
service('asset_mapper.importmap.manager'),
param('kernel.project_dir'),
service('asset_mapper.importmap.version_checker'),
])
->tag('console.command')

Expand All @@ -207,7 +215,10 @@
->tag('console.command')

->set('asset_mapper.importmap.command.update', ImportMapUpdateCommand::class)
->args([service('asset_mapper.importmap.manager')])
->args([
service('asset_mapper.importmap.manager'),
service('asset_mapper.importmap.version_checker'),
])
->tag('console.command')

->set('asset_mapper.importmap.command.install', ImportMapInstallCommand::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\AssetMapper\ImportMap\ImportMapEntry;
use Symfony\Component\AssetMapper\ImportMap\ImportMapManager;
use Symfony\Component\AssetMapper\ImportMap\ImportMapVersionChecker;
use Symfony\Component\AssetMapper\ImportMap\PackageRequireOptions;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
Expand All @@ -28,9 +29,12 @@
#[AsCommand(name: 'importmap:require', description: 'Require JavaScript packages')]
final class ImportMapRequireCommand extends Command
{
use VersionProblemCommandTrait;

public function __construct(
private readonly ImportMapManager $importMapManager,
private readonly string $projectDir,
private readonly ImportMapVersionChecker $importMapVersionChecker,
) {
parent::__construct();
}
Expand Down Expand Up @@ -108,6 +112,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

$newPackages = $this->importMapManager->require($packages);

$this->renderVersionProblems($this->importMapVersionChecker, $output);

if (1 === \count($newPackages)) {
$newPackage = $newPackages[0];
$message = sprintf('Package "%s" added to importmap.php', $newPackage->importName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\AssetMapper\ImportMap\ImportMapEntry;
use Symfony\Component\AssetMapper\ImportMap\ImportMapManager;
use Symfony\Component\AssetMapper\ImportMap\ImportMapVersionChecker;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
Expand All @@ -26,8 +27,11 @@
#[AsCommand(name: 'importmap:update', description: 'Update JavaScript packages to their latest versions')]
final class ImportMapUpdateCommand extends Command
{
use VersionProblemCommandTrait;

public function __construct(
protected readonly ImportMapManager $importMapManager,
private readonly ImportMapManager $importMapManager,
private readonly ImportMapVersionChecker $importMapVersionChecker,
) {
parent::__construct();
}
Expand Down Expand Up @@ -57,6 +61,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$io = new SymfonyStyle($input, $output);
$updatedPackages = $this->importMapManager->update($packages);

$this->renderVersionProblems($this->importMapVersionChecker, $output);

if (0 < \count($packages)) {
$io->success(sprintf(
'Updated %s package%s in importmap.php.',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?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\Command;

use Symfony\Component\AssetMapper\ImportMap\ImportMapVersionChecker;
use Symfony\Component\Console\Output\OutputInterface;

/**
* @internal
*/
trait VersionProblemCommandTrait
{
private function renderVersionProblems(ImportMapVersionChecker $importMapVersionChecker, OutputInterface $output): void
{
$problems = $importMapVersionChecker->checkVersions();
foreach ($problems as $problem) {
if (null === $problem->installedVersion) {
$output->writeln(sprintf('[warning] <info>%s</info> requires <info>%s</info> but it is not in the importmap.php. You may need to run "php bin/console importmap:require %s".', $problem->packageName, $problem->dependencyPackageName, $problem->dependencyPackageName));

continue;
}

if (null === $problem->requiredVersionConstraint) {
$output->writeln(sprintf('[warning] <info>%s</info> appears to import <info>%s</info> but this is not listed as a dependency of <info>%s</info>. This is odd and could be a misconfiguration of that package.', $problem->packageName, $problem->dependencyPackageName, $problem->packageName));

continue;
}

$output->writeln(sprintf('[warning] <info>%s</info> requires <info>%s</info>@<comment>%s</comment> but version <comment>%s</comment> is installed.', $problem->packageName, $problem->dependencyPackageName, $problem->requiredVersionConstraint, $problem->installedVersion));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?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\ImportMap;

use Composer\Semver\Semver;
use Symfony\Component\AssetMapper\Exception\RuntimeException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class ImportMapVersionChecker
{
private const PACKAGE_METADATA_PATTERN = 'https://registry.npmjs.org/%package%/%version%';

private HttpClientInterface $httpClient;

public function __construct(
private ImportMapConfigReader $importMapConfigReader,
private RemotePackageDownloader $packageDownloader,
HttpClientInterface $httpClient = null,
) {
$this->httpClient = $httpClient ?? HttpClient::create();
}

/**
* @return PackageVersionProblem[]
*/
public function checkVersions(): array
{
$entries = $this->importMapConfigReader->getEntries();

$packages = [];
foreach ($entries as $entry) {
if (!$entry->isRemotePackage()) {
continue;
}

$dependencies = $this->packageDownloader->getDependencies($entry->importName);
if (!$dependencies) {
continue;
}

$packageName = $entry->getPackageName();

$url = str_replace(
['%package%', '%version%'],
[$packageName, $entry->version],
self::PACKAGE_METADATA_PATTERN
);
$packages[$packageName] = [
$this->httpClient->request('GET', $url),
$dependencies,
];
}

$errors = [];
$problems = [];
foreach ($packages as $packageName => [$response, $dependencies]) {
if (200 !== $response->getStatusCode()) {
$errors[] = [$packageName, $response];
continue;
}

$data = json_decode($response->getContent(), true);
// dependencies seem to be found in both places
$packageDependencies = array_merge(
$data['dependencies'] ?? [],
$data['peerDependencies'] ?? []
);

foreach ($dependencies as $dependencyName) {
// dependency is not in the import map
if (!$entries->has($dependencyName)) {
$dependencyVersionConstraint = $packageDependencies[$dependencyName] ?? 'unknown';
$problems[] = new PackageVersionProblem($packageName, $dependencyName, $dependencyVersionConstraint, null);

continue;
}

$dependencyPackageName = $entries->get($dependencyName)->getPackageName();
$dependencyVersionConstraint = $packageDependencies[$dependencyPackageName] ?? null;

if (null === $dependencyVersionConstraint) {
$problems[] = new PackageVersionProblem($packageName, $dependencyPackageName, $dependencyVersionConstraint, $entries->get($dependencyName)->version);

continue;
}

if (!$this->isVersionSatisfied($dependencyVersionConstraint, $entries->get($dependencyName)->version)) {
$problems[] = new PackageVersionProblem($packageName, $dependencyPackageName, $dependencyVersionConstraint, $entries->get($dependencyName)->version);
}
}
}

try {
($errors[0][1] ?? null)?->getHeaders();
} catch (HttpExceptionInterface $e) {
$response = $e->getResponse();
$packageNames = implode('", "', array_column($errors, 0));

throw new RuntimeException(sprintf('Error %d finding metadata for package "%s". Response: ', $response->getStatusCode(), $packageNames).$response->getContent(false), 0, $e);
}

return $problems;
}

/**
* Converts npm-specific version constraints to composer-style.
*
* @internal
*/
public static function convertNpmConstraint(string $versionConstraint): ?string
{
// special npm constraint that don't translate to composer
if (\in_array($versionConstraint, ['latest', 'next'])
|| preg_match('/^(git|http|file):/', $versionConstraint)
|| str_contains($versionConstraint, '/')
) {
// GitHub shorthand like user/repo
return null;
}

// remove whitespace around hyphens
$versionConstraint = preg_replace('/\s?-\s?/', '-', $versionConstraint);
$segments = explode(' ', $versionConstraint);
$processedSegments = [];

foreach ($segments as $segment) {
if (str_contains($segment, '-') && !preg_match('/-(alpha|beta|rc)\./', $segment)) {
// This is a range
[$start, $end] = explode('-', $segment);
$processedSegments[] = '>='.self::cleanVersionSegment(trim($start)).' <='.self::cleanVersionSegment(trim($end));
} elseif (preg_match('/^~(\d+\.\d+)$/', $segment, $matches)) {
// Handle the tilde when only major.minor specified
$baseVersion = $matches[1];
$processedSegments[] = '>='.$baseVersion.'.0';
$processedSegments[] = '<'.$baseVersion[0].'.'.($baseVersion[2] + 1).'.0';
} else {
$processedSegments[] = self::cleanVersionSegment($segment);
}
}

return implode(' ', $processedSegments);
}

private static function cleanVersionSegment(string $segment): string
{
return str_replace(['v', '.x'], ['', '.*'], $segment);
}

private function isVersionSatisfied(string $versionConstraint, ?string $version): bool
{
if (!$version) {
return false;
}

try {
$versionConstraint = self::convertNpmConstraint($versionConstraint);

// if version isn't parseable/convertible, assume it's not satisfied
if (null === $versionConstraint) {
return false;
}

return Semver::satisfies($version, $versionConstraint);
} catch (\UnexpectedValueException $e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\ImportMap;

final class PackageVersionProblem
{
public function __construct(
public readonly string $packageName,
public readonly string $dependencyPackageName,
public readonly ?string $requiredVersionConstraint,
public readonly ?string $installedVersion
) {
}
}
Loading