47 lines
2.3 KiB
JavaScript
47 lines
2.3 KiB
JavaScript
// The flows of "the package is missing, install it" (no DOM, tested with fakes in api-install.test.mjs): API Platform / the JWT bundle
|
|
// offered when an entity asks for #[ApiResource], and the quick fix "Install the missing package…" of an undefined class.
|
|
|
|
/**
|
|
* Offers and runs `composer require` for a package the project lacks.
|
|
* deps: plan(what) -> {installed, package, constraint, command}, confirm(plan) -> bool, run({action, package, constraint, dev}) -> {code},
|
|
* enable() -> refreshes the IDE's capabilities (the API Platform window appears).
|
|
* Resolves with {status: 'present' | 'declined' | 'failed' | 'installed', plan, exit?}.
|
|
*/
|
|
export async function installPackage(deps, what = 'api') {
|
|
const plan = await deps.plan(what);
|
|
if (plan.installed) return { status: 'present', plan };
|
|
if (!await deps.confirm(plan)) return { status: 'declined', plan };
|
|
const exit = await deps.run({ action: 'require', package: plan.package, constraint: plan.constraint || '', dev: false });
|
|
if (!exit || exit.code !== 0) return { status: 'failed', plan, exit };
|
|
if (what === 'api') await deps.enable();
|
|
return { status: 'installed', plan, exit };
|
|
}
|
|
|
|
/** The class of an "Undefined class 'X\\Y'" problem (null for any other message). */
|
|
export function undefinedClass(message) {
|
|
const m = /^Undefined class '([^']+)'$/.exec(String(message || ''));
|
|
return m ? m[1].replace(/^\\+/, '') : null;
|
|
}
|
|
|
|
/** The markers of a code action request that are an undefined class: [{name, marker}] (without doubles). */
|
|
export function missingClasses(markers) {
|
|
const seen = new Set();
|
|
const out = [];
|
|
for (const marker of markers || []) {
|
|
const name = undefinedClass(marker.message);
|
|
if (name && !seen.has(name)) { seen.add(name); out.push({ name, marker }); }
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** The `composer require` line shown before it runs. */
|
|
export function requireLine({ package: pkg, constraint = '', dev = false }) {
|
|
const c = String(constraint || '').trim();
|
|
return `composer require ${pkg.trim()}${c ? ':' + c : ''}${dev ? ' --dev' : ''}`;
|
|
}
|
|
|
|
/** Is a typed package name something Composer accepts (vendor/name, or a Flex alias like "api")? */
|
|
export function validPackage(name) {
|
|
const n = String(name || '').trim().toLowerCase();
|
|
return n === 'api' || /^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$/.test(n);
|
|
}
|