@wp-operations/wp-ops 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,31 +1,57 @@
1
1
  # @wp-operations/wp-ops
2
2
 
3
- The unified operations CLI for [wp-operations](https://github.com/wordpress-operations/wordpress-operations) monorepos. One binary, two faces:
4
-
5
- **TUI** — run bare for the menu:
3
+ The operations CLI for wp-operations platform repositories: the GitHub repository the wp-operations theme manages, holding every app (WordPress theme) and every plugin.
6
4
 
5
+ ```bash
6
+ npm install -g @wp-operations/wp-ops
7
7
  ```
8
- wp-ops
8
+
9
+ Requires Node.js 20.10 or later and git. Composer is needed for plugins.
10
+
11
+ ## Platform repository
12
+
13
+ ```bash
14
+ wp-ops init my-platform --platform=path/to/wp-operations-theme # layout + composer.yml + git init
15
+ cd my-platform
16
+ wp-ops new plugin acme/forms # packages/acme/forms (type psr4-plugin)
17
+ wp-ops new app service-apps shop --server=prod-1 --app-path=/var/www/shop
18
+ wp-ops composer add --apps=service-apps/shop --packages="acme/forms"
19
+ wp-ops apps
20
+ wp-ops plugins
21
+ wp-ops doctor
9
22
  ```
10
23
 
11
- WPOps banner, then: start an app, dev mode, build all packages, doctor, exit.
24
+ | Command | What it does |
25
+ |---|---|
26
+ | `init [dir] [--platform=]` | Creates `.github/platform.json`, the kind manifests, the `packages/` and kind folders, `.github/workflows/composer.yml` and `.gitignore`, then runs `git init` (branch `main`). It never overwrites a file. `--platform` copies the theme's `platform.json` to the root. |
27
+ | `new app <kind> <slug>` | Creates the app folder: composer.json `type: wp-app`, style.css, index.php, and a functions.php that boots every installed plugin. It also adds the slug to the kind's manifest, with `--server`, `--app-path` and `--theme-slug`. |
28
+ | `new plugin <vendor/name>` | Creates `packages/<vendor>/<name>` with composer.json `type: psr4-plugin`, version 0.1.0, PSR-4 autoload and `extra.wp-operations.plugin-class`, plus `src/Plugin.php` with `init()`. |
29
+ | `apps`, `plugins` | List what is in the repository, with deploy targets, which apps use which plugin, and any contract problems. |
30
+ | `composer <add\|remove\|update> --apps= --packages=` | Makes the same composer.json edit the theme commits (a no-op when the theme already did it), then refreshes `composer.lock` without installing anything. `update` with no `--apps` covers every app that requires the plugins. This is what `composer.yml` runs on GitHub Actions. |
31
+ | `sandbox` | The preview runtime. See below. |
32
+ | `edit` | Opens the wp-ide editor for this repository. |
33
+ | `doctor` | Checks the environment and the repository contract. |
12
34
 
13
- **Plain commands** — for scripts and muscle memory:
35
+ ## Sandbox runtime
14
36
 
15
37
  ```bash
16
- wp-ops start apps/my-theme --wp=classicpress
17
- wp-ops dev apps/my-theme
18
- wp-ops build # runs the build script of every package in packages/
19
- wp-ops doctor # environment checks
38
+ SANDBOX_TOKEN=… wp-ops sandbox --port=8080 --url=https://sandbox.example.com --git
20
39
  ```
21
40
 
22
- ## Doctor
41
+ One server for every app, matching the theme's sandbox contract:
42
+
43
+ - **Health.** `GET /` (change it with `--health`) answers 200. When `$SANDBOX_TOKEN` is set (or the variable named by `--token-env`), health checks need `Authorization: Bearer <token>`. In Settings → Operations → Sandboxes, set the token constant to the same value.
44
+ - **Preview.** Each app runs at `/{kind}/{slug}/` on its own WordPress site (wp-app engine, SQLite), with the app active as the theme. Its plugins are installed with `composer install` and booted.
45
+ - **Framing.** `X-Frame-Options` is removed and `Content-Security-Policy: frame-ancestors` is set from `--frame-ancestors` (default `*`; use the platform's origin in production).
46
+ - **Git mode.** With `--git`, the runtime must be a clone with a remote. Each app is served from its own worktree under `.local/sandbox/`, refreshed on every page load: from `vibe/{slug}` (the AI work branch; change it with `--work-branch`) when that branch exists on the remote, otherwise from the deploy branch (`--branch`, default the remote's default branch). New commits show up when the preview reloads.
47
+ - **Without `--git`.** The runtime serves your working tree as it is.
48
+ - **Memory.** At most `--max` sites (default 3) stay running. The least recently used idle site is stopped and starts again on its next request.
23
49
 
24
- `wp-ops doctor` verifies: node >= 18, git, composer (optional), filesystem symlink support (some filesystems need a copy-based installer instead of npm), wp-app resolvability, and the `.local` data directory.
50
+ `--url` must be the public address the platform loads previews from, because WordPress builds its links from it.
25
51
 
26
- ## How it finds things
52
+ ## Single app
27
53
 
28
- Walks up from cwd to the repo root (`wp-operations.json`, `.git`, or `package.json`), then resolves `wp-app` from `packages/wp-app/cli.js` or an installed `@wp-operations/wp-app`. Apps are listed from `wp-operations.json` (`"apps": { ... }`) or by scanning `apps/` and `examples/`.
54
+ `wp-ops start [dir]`, `wp-ops dev [dir]` and `wp-ops build` delegate to [`wp-app`](../wp-app). Running `wp-ops` with no arguments opens the interactive menu.
29
55
 
30
56
  ## License
31
57
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wp-operations/wp-ops",
3
- "version": "0.1.0",
4
- "description": "Unified operations CLI and TUI for wp-operations monorepos: start, build, dev, doctor.",
3
+ "version": "0.2.0",
4
+ "description": "Operations CLI and TUI for wp-operations platform repositories: init, apps, plugins, composer, sandbox runtime, start, build, doctor.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
7
7
  "bin": {
@@ -17,19 +17,21 @@
17
17
  "author": "de-er-kid",
18
18
  "repository": {
19
19
  "type": "git",
20
- "url": "https://github.com/wordpress-operations/wordpress-operations",
20
+ "url": "git+https://github.com/wordpress-operations/wordpress-operations.git",
21
21
  "directory": "packages/wp-ops"
22
22
  },
23
23
  "homepage": "https://github.com/wordpress-operations/wordpress-operations/tree/main/packages/wp-ops",
24
24
  "bugs": "https://github.com/wordpress-operations/wordpress-operations/issues",
25
25
  "engines": {
26
- "node": ">=18.0.0"
26
+ "node": ">=20.10.0"
27
27
  },
28
28
  "publishConfig": {
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
32
  "@clack/prompts": "0.7.0",
33
+ "@wp-operations/wp-app": "^0.4.1",
34
+ "@wp-operations/wp-ide": "^0.3.0",
33
35
  "picocolors": "1.1.1"
34
36
  },
35
37
  "keywords": [
@@ -37,6 +39,8 @@
37
39
  "classicpress",
38
40
  "monorepo",
39
41
  "operations",
42
+ "platform",
43
+ "sandbox",
40
44
  "tui",
41
45
  "wp-operations"
42
46
  ]
package/src/args.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Splits argv into positionals and --key=value / --flag / --no-flag options.
3
+ */
4
+ export function parseArgs(argv) {
5
+ const positional = [];
6
+ const options = {};
7
+ for (const arg of argv) {
8
+ if (!arg.startsWith('--')) {
9
+ positional.push(arg);
10
+ continue;
11
+ }
12
+ const body = arg.slice(2);
13
+ const eq = body.indexOf('=');
14
+ if (eq >= 0) {
15
+ options[body.slice(0, eq)] = body.slice(eq + 1);
16
+ } else if (body.startsWith('no-')) {
17
+ options[body.slice(3)] = false;
18
+ } else {
19
+ options[body] = true;
20
+ }
21
+ }
22
+ return { positional, options };
23
+ }
24
+
25
+ export class UsageError extends Error {}
@@ -4,6 +4,7 @@ import path from 'path';
4
4
  import { execSync } from 'child_process';
5
5
  import pc from 'picocolors';
6
6
  import { findRootDir, findWpAppCli } from '../project.js';
7
+ import { ide } from '../deps.js';
7
8
 
8
9
  function check(label, ok, detail = '') {
9
10
  const mark = ok ? pc.green('ok') : pc.red('!!');
@@ -11,6 +12,10 @@ function check(label, ok, detail = '') {
11
12
  return ok;
12
13
  }
13
14
 
15
+ function warn(label, detail = '') {
16
+ console.log(` ${pc.yellow('--')} ${label}${detail ? pc.dim(` — ${detail}`) : ''}`);
17
+ }
18
+
14
19
  function commandExists(command) {
15
20
  try {
16
21
  execSync(`${command} --version`, { stdio: 'pipe', shell: true });
@@ -37,14 +42,46 @@ function supportsSymlinks(dir) {
37
42
  }
38
43
  }
39
44
 
40
- export function doctor(startDir = process.cwd()) {
45
+ async function platformChecks(rootDir) {
46
+ const { hasLayout, readLayout, listApps, listPlugins } = await ide();
47
+ if (!hasLayout(rootDir)) {
48
+ warn('platform repository', 'no .github/platform.json (run "wp-ops init" to create one)');
49
+ return;
50
+ }
51
+ let layout;
52
+ try {
53
+ layout = readLayout(rootDir);
54
+ } catch (error) {
55
+ check('.github/platform.json', false, error.message);
56
+ return;
57
+ }
58
+ check('.github/platform.json', layout.kinds.length > 0, `${layout.kinds.length} kinds, plugins in ${layout.packages}/`);
59
+ check('platform.json', fs.existsSync(path.join(rootDir, 'platform.json')), fs.existsSync(path.join(rootDir, 'platform.json')) ? 'present' : "missing; copy the theme's platform.json to the root");
60
+ const workflows = path.join(rootDir, '.github', 'workflows');
61
+ for (const name of ['composer.yml', 'deploy-apps.yml', 'deploy-platform.yml']) {
62
+ const present = fs.existsSync(path.join(workflows, name));
63
+ if (name === 'composer.yml') check(`workflow ${name}`, present, present ? '' : 'missing; "wp-ops init" adds it');
64
+ else if (!present) warn(`workflow ${name}`, 'not found; the theme dispatches it for deploys (the name is set in Settings → Operations)');
65
+ else check(`workflow ${name}`, true);
66
+ }
67
+ try {
68
+ const apps = listApps(rootDir, layout);
69
+ const plugins = listPlugins(rootDir, layout);
70
+ const problems = [...apps, ...plugins].filter((item) => item.warnings.length);
71
+ check(`${apps.length} apps, ${plugins.length} plugins`, problems.length === 0, problems.length ? problems.map((item) => `${item.path}: ${item.warnings.join('; ')}`).join(' | ') : '');
72
+ } catch (error) {
73
+ check('apps and plugins', false, error.message);
74
+ }
75
+ }
76
+
77
+ export async function doctor(startDir = process.cwd()) {
41
78
  const rootDir = findRootDir(startDir);
42
79
  console.log(pc.bold('\nwp-ops doctor\n'));
43
80
 
44
81
  const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
45
- check(`node ${process.versions.node}`, nodeMajor >= 18, 'need >= 18');
82
+ check(`node ${process.versions.node}`, nodeMajor >= 20, 'need >= 20.10 for wp-app');
46
83
  check('git', commandExists('git'));
47
- check('composer', commandExists('composer'), 'optional, used by wp-app build');
84
+ check('composer', commandExists('composer'), 'needed for plugins (wp-ops composer, sandbox)');
48
85
 
49
86
  const symlinks = supportsSymlinks(rootDir);
50
87
  check(
@@ -58,13 +95,8 @@ export function doctor(startDir = process.cwd()) {
58
95
  const wpAppCli = findWpAppCli(rootDir);
59
96
  check('wp-app resolvable', Boolean(wpAppCli), wpAppCli ?? 'not found');
60
97
 
61
- const localDir = path.join(rootDir, '.local');
62
- check(
63
- '.local data dir',
64
- true,
65
- fs.existsSync(localDir) ? localDir : 'not created yet (created on first ide-mode run)'
66
- );
98
+ await platformChecks(rootDir);
67
99
 
68
100
  console.log(pc.dim(`\n root: ${rootDir}`));
69
- console.log(pc.dim(` home data: ${path.join(os.homedir(), '.wp-app')}\n`));
101
+ console.log(pc.dim(` home data: ${process.env.WP_APP_HOME || path.join(os.homedir(), '.wp-app')}\n`));
70
102
  }
@@ -0,0 +1,304 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { execFileSync, spawnSync } from 'child_process';
4
+ import pc from 'picocolors';
5
+ import { ide } from '../deps.js';
6
+ import { UsageError } from '../args.js';
7
+ import {
8
+ APP_FUNCTIONS,
9
+ APP_INDEX,
10
+ GITIGNORE,
11
+ appStyle,
12
+ composerWorkflow,
13
+ pluginClass,
14
+ } from '../templates.js';
15
+
16
+ const COMPOSER_FLAGS = ['--no-interaction', '--no-install', '--no-scripts', '--no-plugins', '--no-progress', '--no-audit'];
17
+
18
+ function writeNew(file, content, created) {
19
+ if (fs.existsSync(file)) {
20
+ return false;
21
+ }
22
+ fs.mkdirSync(path.dirname(file), { recursive: true });
23
+ fs.writeFileSync(file, content);
24
+ created.push(file);
25
+ return true;
26
+ }
27
+
28
+ /**
29
+ * Walks up from startDir to the platform repository root
30
+ * (the folder holding .github/platform.json).
31
+ */
32
+ export async function platformRoot(startDir = process.cwd()) {
33
+ const { hasLayout } = await ide();
34
+ let current = path.resolve(startDir);
35
+ for (;;) {
36
+ if (hasLayout(current)) return current;
37
+ const parent = path.dirname(current);
38
+ if (parent === current) {
39
+ throw new UsageError(
40
+ `No .github/platform.json found from ${path.resolve(startDir)} upwards. Run "wp-ops init" first.`
41
+ );
42
+ }
43
+ current = parent;
44
+ }
45
+ }
46
+
47
+ export async function init({ dir = process.cwd(), platform, version, log = console.log }) {
48
+ const { DEFAULT_KINDS, LAYOUT_FILE, encodeJson, layoutJson } = await ide();
49
+ const root = path.resolve(dir);
50
+ fs.mkdirSync(root, { recursive: true });
51
+ const created = [];
52
+
53
+ writeNew(
54
+ path.join(root, LAYOUT_FILE),
55
+ encodeJson(
56
+ layoutJson({
57
+ platform: { server: '', app_path: '', theme_slug: 'wp-operations' },
58
+ packages: 'packages',
59
+ kinds: DEFAULT_KINDS,
60
+ })
61
+ ),
62
+ created
63
+ );
64
+ for (const kind of DEFAULT_KINDS) {
65
+ writeNew(path.join(root, kind.manifest), encodeJson({}), created);
66
+ writeNew(path.join(root, kind.folder, '.gitkeep'), '', created);
67
+ }
68
+ writeNew(path.join(root, 'packages', '.gitkeep'), '', created);
69
+ writeNew(path.join(root, '.github', 'workflows', 'composer.yml'), composerWorkflow(version), created);
70
+ writeNew(path.join(root, '.gitignore'), GITIGNORE, created);
71
+
72
+ if (platform) {
73
+ const source = path.resolve(platform);
74
+ const file = fs.existsSync(source) && fs.statSync(source).isDirectory() ? path.join(source, 'platform.json') : source;
75
+ if (!fs.existsSync(file)) {
76
+ throw new UsageError(`--platform: ${file} does not exist.`);
77
+ }
78
+ JSON.parse(fs.readFileSync(file, 'utf8').replace(/^/, ''));
79
+ writeNew(path.join(root, 'platform.json'), fs.readFileSync(file), created);
80
+ }
81
+
82
+ let gitInit = false;
83
+ if (!fs.existsSync(path.join(root, '.git'))) {
84
+ execFileSync('git', ['init', '--initial-branch=main'], { cwd: root, stdio: 'pipe' });
85
+ gitInit = true;
86
+ }
87
+
88
+ for (const file of created) log(` ${pc.green('+')} ${path.relative(root, file).split(path.sep).join('/')}`);
89
+ if (gitInit) log(` ${pc.green('+')} git repository (branch main)`);
90
+ if (!created.length && !gitInit) log(' Already a platform repository; nothing to add.');
91
+ if (!fs.existsSync(path.join(root, 'platform.json'))) {
92
+ log(pc.yellow(`\n platform.json is missing at the root. Copy the theme's platform.json here, or run: wp-ops init --platform=<path to the theme>`));
93
+ }
94
+ log(pc.dim('\n Deploy workflows (deploy-apps.yml, deploy-platform.yml) are yours to add under .github/workflows/.'));
95
+ return { root, created, gitInit };
96
+ }
97
+
98
+ function composerName(value) {
99
+ return value.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^[-_.]+|[-_.]+$/g, '');
100
+ }
101
+
102
+ function pascal(value) {
103
+ const result = value
104
+ .split(/[^A-Za-z0-9]+/)
105
+ .filter(Boolean)
106
+ .map((word) => word[0].toUpperCase() + word.slice(1))
107
+ .join('');
108
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(result)) {
109
+ throw new UsageError(`"${value}" does not make a valid PHP namespace segment.`);
110
+ }
111
+ return result;
112
+ }
113
+
114
+ export async function newApp({ root, kind: kindKey, slug: rawSlug, server = '', appPath = '', themeSlug, log = console.log }) {
115
+ const { readLayout, findKind, slug, readManifest, writeManifest, encodeJson } = await ide();
116
+ if (!kindKey || !rawSlug) throw new UsageError('Usage: wp-ops new app <kind> <slug>');
117
+ const layout = readLayout(root);
118
+ let kind;
119
+ try {
120
+ kind = findKind(layout, kindKey);
121
+ } catch (error) {
122
+ throw new UsageError(error.message);
123
+ }
124
+ const appSlug = slug(rawSlug);
125
+ const name = composerName(appSlug);
126
+ if (!appSlug || !name) throw new UsageError(`"${rawSlug}" is not a usable app name.`);
127
+ const dir = path.join(root, kind.folder, appSlug);
128
+ if (fs.existsSync(dir)) throw new UsageError(`${kind.folder}/${appSlug} already exists.`);
129
+ const manifest = readManifest(root, kind);
130
+ if (manifest[appSlug]) throw new UsageError(`${appSlug} is already in ${kind.manifest}.`);
131
+
132
+ const created = [];
133
+ writeNew(
134
+ path.join(dir, 'composer.json'),
135
+ encodeJson({
136
+ name: `platform/${name}`,
137
+ type: 'wp-app',
138
+ description: '',
139
+ license: 'proprietary',
140
+ require: { php: '>=8.0' },
141
+ repositories: [],
142
+ }),
143
+ created
144
+ );
145
+ writeNew(path.join(dir, 'style.css'), appStyle(appSlug), created);
146
+ writeNew(path.join(dir, 'index.php'), APP_INDEX, created);
147
+ writeNew(path.join(dir, 'functions.php'), APP_FUNCTIONS, created);
148
+ manifest[appSlug] = { server, app_path: appPath, theme_slug: themeSlug || appSlug };
149
+ writeManifest(root, kind, manifest);
150
+
151
+ for (const file of created) log(` ${pc.green('+')} ${path.relative(root, file).split(path.sep).join('/')}`);
152
+ log(` ${pc.green('~')} ${kind.manifest} (${appSlug})`);
153
+ return { dir, path: `${kind.folder}/${appSlug}` };
154
+ }
155
+
156
+ export async function newPlugin({ root, name, description = '', log = console.log }) {
157
+ const { readLayout, listPlugins, PACKAGE_NAME, encodeJson } = await ide();
158
+ if (!name || !PACKAGE_NAME.test(name)) {
159
+ throw new UsageError('Usage: wp-ops new plugin <vendor/name> (lowercase letters, digits, - _ .)');
160
+ }
161
+ const layout = readLayout(root);
162
+ if (listPlugins(root, layout).some((plugin) => plugin.name === name)) {
163
+ throw new UsageError(`${name} already exists.`);
164
+ }
165
+ const [vendor, pkg] = name.split('/');
166
+ const dir = path.join(root, layout.packages, vendor, pkg);
167
+ if (fs.existsSync(dir)) throw new UsageError(`${path.relative(root, dir)} already exists.`);
168
+ const namespace = `${pascal(vendor)}\\${pascal(pkg)}`;
169
+
170
+ const created = [];
171
+ writeNew(
172
+ path.join(dir, 'composer.json'),
173
+ encodeJson({
174
+ name,
175
+ version: '0.1.0',
176
+ type: 'psr4-plugin',
177
+ description,
178
+ license: 'proprietary',
179
+ require: { php: '>=8.0' },
180
+ autoload: { 'psr-4': { [`${namespace}\\`]: 'src/' } },
181
+ extra: { 'wp-operations': { 'plugin-class': `${namespace}\\Plugin` } },
182
+ }),
183
+ created
184
+ );
185
+ writeNew(path.join(dir, 'src', 'Plugin.php'), pluginClass(namespace), created);
186
+ for (const file of created) log(` ${pc.green('+')} ${path.relative(root, file).split(path.sep).join('/')}`);
187
+ return { dir, namespace };
188
+ }
189
+
190
+ export async function apps({ root, log = console.log }) {
191
+ const { listApps } = await ide();
192
+ const list = listApps(root);
193
+ if (!list.length) {
194
+ log(' No apps yet. Create one: wp-ops new app <kind> <slug>');
195
+ return list;
196
+ }
197
+ for (const app of list) {
198
+ const target = app.manifest?.server ? pc.dim(` → ${app.manifest.server}${app.manifest.app_path ? `:${app.manifest.app_path}` : ''}`) : '';
199
+ log(` ${app.path}${target}${app.warnings.length ? pc.yellow(` (${app.warnings.join('; ')})`) : ''}`);
200
+ }
201
+ return list;
202
+ }
203
+
204
+ export async function plugins({ root, log = console.log }) {
205
+ const { listPlugins, readLayout, listApps } = await ide();
206
+ const layout = readLayout(root);
207
+ const list = listPlugins(root, layout);
208
+ const appList = listApps(root, layout);
209
+ if (!list.length) {
210
+ log(' No plugins yet. Create one: wp-ops new plugin <vendor/name>');
211
+ return list;
212
+ }
213
+ for (const plugin of list) {
214
+ const users = appList.filter((app) => {
215
+ try {
216
+ return Boolean(JSON.parse(fs.readFileSync(path.join(app.dir, 'composer.json'), 'utf8')).require?.[plugin.name]);
217
+ } catch {
218
+ return false;
219
+ }
220
+ });
221
+ log(` ${plugin.name} ${pc.dim(plugin.version || 'no version')} ${pc.dim(plugin.path)}${users.length ? ` in ${users.map((a) => a.path).join(', ')}` : ''}${plugin.warnings.length ? pc.yellow(` (${plugin.warnings.join('; ')})`) : ''}`);
222
+ }
223
+ return list;
224
+ }
225
+
226
+ /**
227
+ * Runs composer. On Windows composer is a .bat shim, which needs a shell;
228
+ * every argument here is a fixed flag or a validated package name.
229
+ */
230
+ export function runComposer(cwd, args) {
231
+ const options = { cwd, stdio: 'inherit', env: { ...process.env, COMPOSER_NO_INTERACTION: '1' } };
232
+ const result =
233
+ process.platform === 'win32'
234
+ ? spawnSync(['composer', ...args].join(' '), { ...options, shell: true })
235
+ : spawnSync('composer', args, options);
236
+ if (result.error) throw new Error(`composer could not be started: ${result.error.message}`);
237
+ if (result.status !== 0) throw new Error(`composer exited with ${result.status} in ${cwd}`);
238
+ }
239
+
240
+ /**
241
+ * What the platform's composer.yml workflow runs: applies add/remove to each
242
+ * app's composer.json (a no-op when the theme already committed it), then
243
+ * refreshes composer.lock for those packages without installing anything.
244
+ */
245
+ export async function composer({ root, action, apps: appsArg = '', packages: packagesArg = '', constraint = '*', lock = true, log = console.log }) {
246
+ const { readLayout, listPlugins, listApps, folder, PACKAGE_NAME, COMPOSER_ACTIONS, editComposer, readJson, encodeJson } = await ide();
247
+ if (!COMPOSER_ACTIONS.includes(action)) {
248
+ throw new UsageError(`Usage: wp-ops composer <${COMPOSER_ACTIONS.join('|')}> --apps=<a,b> --packages="<x y>"`);
249
+ }
250
+ const names = [...new Set(String(packagesArg).split(/[\s,]+/).filter(Boolean))];
251
+ if (!names.length) throw new UsageError('Give at least one plugin: --packages="vendor/name"');
252
+ for (const name of names) {
253
+ if (!PACKAGE_NAME.test(name)) throw new UsageError(`"${name}" is not a composer package name.`);
254
+ }
255
+ if (!/^[A-Za-z0-9.*@^~|<>=, -]+$/.test(constraint)) throw new UsageError(`Invalid --constraint "${constraint}".`);
256
+
257
+ const layout = readLayout(root);
258
+ const pluginList = listPlugins(root, layout);
259
+ const byName = new Map(pluginList.map((plugin) => [plugin.name, plugin]));
260
+ if (action === 'add') {
261
+ for (const name of names) {
262
+ if (!byName.has(name)) throw new UsageError(`${name} is not in ${layout.packages}/.`);
263
+ }
264
+ }
265
+
266
+ const known = new Map(listApps(root, layout).map((app) => [app.path, app]));
267
+ let targets = [...new Set(String(appsArg).split(',').map((value) => folder(value.trim())).filter(Boolean))];
268
+ if (!targets.length && action === 'update') {
269
+ targets = [...known.values()]
270
+ .filter((app) => {
271
+ const data = readJson(path.join(app.dir, 'composer.json'));
272
+ return names.some((name) => data?.require?.[name]);
273
+ })
274
+ .map((app) => app.path);
275
+ }
276
+ if (!targets.length) throw new UsageError('Give at least one app: --apps=<kind folder>/<slug>');
277
+ for (const target of targets) {
278
+ if (!known.has(target) || !fs.existsSync(path.join(root, target, 'composer.json'))) {
279
+ throw new UsageError(`${target} is not an app with a composer.json.`);
280
+ }
281
+ }
282
+
283
+ for (const target of targets) {
284
+ const file = path.join(root, target, 'composer.json');
285
+ const before = readJson(file);
286
+ if (!before || typeof before !== 'object' || Array.isArray(before)) {
287
+ throw new Error(`${target}/composer.json is not a JSON object.`);
288
+ }
289
+ if (action !== 'update') {
290
+ const after = editComposer(before, action, target, names.map((name) => byName.get(name) ?? { name, path: '' }), constraint);
291
+ const text = encodeJson(after);
292
+ if (text !== fs.readFileSync(file, 'utf8')) {
293
+ fs.writeFileSync(file, text);
294
+ log(` ${pc.green('~')} ${target}/composer.json`);
295
+ }
296
+ }
297
+ if (lock) {
298
+ const partial = fs.existsSync(path.join(root, target, 'composer.lock')) ? names : [];
299
+ log(pc.dim(` composer update ${partial.join(' ') || '(new lock)'} (${target})`));
300
+ runComposer(path.join(root, target), ['update', ...partial, ...COMPOSER_FLAGS]);
301
+ }
302
+ }
303
+ return { apps: targets, packages: names };
304
+ }