Skip to content
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

feat(cli): Check npm workspace packages for plugins #7723

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"@ionic/utils-fs": "^3.1.6",
"@ionic/utils-subprocess": "2.1.11",
"@ionic/utils-terminal": "^2.3.3",
"@npmcli/map-workspaces": "^4.0.1",
"commander": "^9.3.0",
"debug": "^4.3.4",
"env-paths": "^2.2.0",
Expand All @@ -65,6 +66,7 @@
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/jest": "^29.5.0",
"@types/npmcli__map-workspaces": "^3.0.4",
"@types/plist": "^3.0.2",
"@types/prompts": "^2.0.14",
"@types/semver": "^7.3.10",
Expand Down
23 changes: 22 additions & 1 deletion cli/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { fatal, isFatal } from './errors';
import { logger } from './log';
import { tryFn } from './util/fn';
import { formatJSObject } from './util/js';
import { findNXMonorepoRoot, isNXMonorepo } from './util/monorepotools';
import { findMonorepoRoot, findNXMonorepoRoot, isMonorepo, isNXMonorepo } from './util/monorepotools';
import { requireTS, resolveNode } from './util/node';
import { lazy } from './util/promise';
import { getCommandOutput } from './util/subprocess';
Expand Down Expand Up @@ -40,6 +40,26 @@ export async function loadConfig(): Promise<Config> {
return {};
})();

const workspacesSetup = await (async (): Promise<Config['app']['workspaces'] | undefined> => {
if (isMonorepo(appRootDir) && conf.extConfig.workspaces === 'npm') {
const { fileType, path: rootOfMonorepo } = findMonorepoRoot(appRootDir);
if (fileType === 'yaml') {
return undefined;
}
const pkgJSONOfMonorepoRoot: { workspaces: string[] } | null = await tryFn(
readJSON,
resolve(rootOfMonorepo, 'package.json'),
);
const workspaces = pkgJSONOfMonorepoRoot?.workspaces ?? [];
return {
type: conf.extConfig.workspaces,
workspaceDirs: workspaces,
workspaceRoot: rootOfMonorepo,
};
}
return undefined;
})();

const appId = conf.extConfig.appId ?? '';
const appName = conf.extConfig.appName ?? '';
const webDir = conf.extConfig.webDir ?? 'www';
Expand All @@ -61,6 +81,7 @@ export async function loadConfig(): Promise<Config> {
version: '1.0.0',
...depsForNx,
},
workspaces: workspacesSetup,
...conf,
},
};
Expand Down
11 changes: 11 additions & 0 deletions cli/src/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,17 @@ export interface CapacitorConfig {
* @since 3.0.0
*/
includePlugins?: string[];

/**
* Name of the workspace tool you are using.
*
* Setting this option tells `npx cap sync` to check you workspace packages for capacitor plugins.
*
* Currently only `npm` workspaces are supported.
*
* @since X.X.X
* */
readonly workspaces?: 'npm';
}

export interface PluginsConfig {
Expand Down
4 changes: 4 additions & 0 deletions cli/src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const enum OS {
export interface PackageJson {
readonly name: string;
readonly version: string;
readonly workspaces?: string[];
readonly dependencies?: { readonly [key: string]: string | undefined };
readonly devDependencies?: { readonly [key: string]: string | undefined };
}
Expand Down Expand Up @@ -62,6 +63,9 @@ export interface AppConfig {
readonly extConfigName: string;
readonly extConfigFilePath: string;
readonly extConfig: ExternalConfig;
readonly workspaces:
| { type: 'npm'; workspaceDirs: string[]; workspaceRoot: string }
| undefined;
}

export interface AndroidConfig extends PlatformConfig {
Expand Down
39 changes: 35 additions & 4 deletions cli/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readJSON } from '@ionic/utils-fs';
import mapWorkspaces from '@npmcli/map-workspaces';
import { dirname, join } from 'path';

import c from './colors';
Expand Down Expand Up @@ -52,8 +53,29 @@ export function getIncludedPluginPackages(config: Config, platform: string): rea
return extConfig.ios?.includePlugins ?? extConfig.includePlugins;
}
}

export async function getPlugins(config: Config, platform: string): Promise<Plugin[]> {
if (config.app.workspaces?.type === 'npm') {
const { workspaceDirs, workspaceRoot } = config.app.workspaces;
const workspacePackages = await mapWorkspaces({
cwd: workspaceRoot,
pkg: { workspaces: workspaceDirs },
});
const resolvedWorkspacePackages = await Promise.all(
Array.from(workspacePackages.entries()).map(async ([name, path]) => {
return parsePluginMeta(join(path, 'package.json'), name);
}),
);
const possiblePackageJsonPlugins = getIncludedPluginPackages(config, platform) ?? getDependencies(config);

const resolvedPackageJsonPlugins = await Promise.all(
possiblePackageJsonPlugins.map(async (p) => resolvePlugin(config, p)),
);

const plugins = [...resolvedPackageJsonPlugins, ...resolvedWorkspacePackages].filter(
(p): p is Plugin => p !== null,
);
return plugins;
}
const possiblePlugins = getIncludedPluginPackages(config, platform) ?? getDependencies(config);
const resolvedPlugins = await Promise.all(possiblePlugins.map(async (p) => resolvePlugin(config, p)));

Expand All @@ -67,6 +89,15 @@ export async function resolvePlugin(config: Config, name: string): Promise<Plugi
fatal(`Unable to find ${c.strong(`node_modules/${name}`)}.\n` + `Are you sure ${c.strong(name)} is installed?`);
}

return parsePluginMeta(packagePath, name);
} catch (e) {
// ignore
}
return null;
}

const parsePluginMeta = async (packagePath: string, name: string): Promise<Plugin | null> => {
try {
const rootPath = dirname(packagePath);
const meta = await readJSON(packagePath);
if (!meta) {
Expand All @@ -92,11 +123,11 @@ export async function resolvePlugin(config: Config, name: string): Promise<Plugi
repository: meta.repository,
xml: xmlMeta.plugin,
};
} catch (e) {
// ignore
} catch {
// ignore;
}
return null;
}
};

export function getDependencies(config: Config): string[] {
return [
Expand Down
21 changes: 13 additions & 8 deletions cli/src/util/monorepotools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@ import { join, dirname, relative } from 'node:path';
/**
* Finds the monorepo root from the given path.
* @param currentPath - The current path to start searching from.
* @returns The path to the monorepo root.
* @return an object describing the monorepo root and the type of file where the workspace config was detected.
* @throws An error if the monorepo root is not found.
*/
export function findMonorepoRoot(currentPath: string): string {
export function findMonorepoRoot(currentPath: string): {
/**
* The type of file where the workspace config was detected (ex. json for npm/yarn, yaml for pnpm).
*/
fileType: 'json' | 'yaml';
path: string;
} {
const packageJsonPath = join(currentPath, 'package.json');
const pnpmWorkspacePath = join(currentPath, 'pnpm-workspace.yaml');
if (
existsSync(pnpmWorkspacePath) ||
(existsSync(packageJsonPath) && JSON.parse(readFileSync(packageJsonPath, 'utf-8')).workspaces)
) {
return currentPath;
if (existsSync(pnpmWorkspacePath)) {
return { fileType: 'yaml', path: currentPath };
} else if (existsSync(packageJsonPath) && JSON.parse(readFileSync(packageJsonPath, 'utf-8')).workspaces) {
return { fileType: 'json', path: currentPath };
}
const parentPath = dirname(currentPath);
if (parentPath === currentPath) {
Expand Down Expand Up @@ -73,7 +78,7 @@ export function findPackagePath(
* @returns The relative path to the package, or null if not found.
*/
export function findPackageRelativePathInMonorepo(packageName: string, currentPath: string): string | null {
const monorepoRoot = findMonorepoRoot(currentPath);
const { path: monorepoRoot } = findMonorepoRoot(currentPath);
const packagePath = findPackagePath(packageName, currentPath, monorepoRoot);
if (packagePath) {
return relative(currentPath, packagePath);
Expand Down