emd-agents 0.0.0-stage → 0.14.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.
Files changed (77) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +121 -2
  4. package/dist/adapters/expo/index.d.ts +3 -0
  5. package/dist/adapters/expo/index.js +55 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +11 -0
  8. package/dist/cli/main.d.ts +1 -0
  9. package/dist/cli/main.js +265 -0
  10. package/dist/core/adapter.d.ts +32 -0
  11. package/dist/core/adapter.js +3 -0
  12. package/dist/core/check.d.ts +20 -0
  13. package/dist/core/check.js +214 -0
  14. package/dist/core/checkrecord.d.ts +22 -0
  15. package/dist/core/checkrecord.js +34 -0
  16. package/dist/core/detect.d.ts +2 -0
  17. package/dist/core/detect.js +27 -0
  18. package/dist/core/device/axe.d.ts +10 -0
  19. package/dist/core/device/axe.js +66 -0
  20. package/dist/core/device/backend.d.ts +43 -0
  21. package/dist/core/device/backend.js +72 -0
  22. package/dist/core/device/maestro.d.ts +4 -0
  23. package/dist/core/device/maestro.js +86 -0
  24. package/dist/core/device/screen.d.ts +9 -0
  25. package/dist/core/device/screen.js +7 -0
  26. package/dist/core/doctor.d.ts +12 -0
  27. package/dist/core/doctor.js +70 -0
  28. package/dist/core/evidence.d.ts +9 -0
  29. package/dist/core/evidence.js +107 -0
  30. package/dist/core/gc.d.ts +22 -0
  31. package/dist/core/gc.js +172 -0
  32. package/dist/core/index.d.ts +17 -0
  33. package/dist/core/index.js +16 -0
  34. package/dist/core/input.d.ts +15 -0
  35. package/dist/core/input.js +59 -0
  36. package/dist/core/isolate.d.ts +4 -0
  37. package/dist/core/isolate.js +43 -0
  38. package/dist/core/jobs.d.ts +21 -0
  39. package/dist/core/jobs.js +114 -0
  40. package/dist/core/jobstore.d.ts +21 -0
  41. package/dist/core/jobstore.js +45 -0
  42. package/dist/core/launch.d.ts +8 -0
  43. package/dist/core/launch.js +273 -0
  44. package/dist/core/log.d.ts +5 -0
  45. package/dist/core/log.js +54 -0
  46. package/dist/core/logs.d.ts +19 -0
  47. package/dist/core/logs.js +122 -0
  48. package/dist/core/owned.d.ts +19 -0
  49. package/dist/core/owned.js +91 -0
  50. package/dist/core/probe.d.ts +2 -0
  51. package/dist/core/probe.js +14 -0
  52. package/dist/core/process.d.ts +10 -0
  53. package/dist/core/process.js +32 -0
  54. package/dist/core/project.d.ts +6 -0
  55. package/dist/core/project.js +76 -0
  56. package/dist/core/registry.d.ts +3 -0
  57. package/dist/core/registry.js +13 -0
  58. package/dist/core/result.d.ts +248 -0
  59. package/dist/core/result.js +147 -0
  60. package/dist/core/run.d.ts +15 -0
  61. package/dist/core/run.js +22 -0
  62. package/dist/core/setup.d.ts +29 -0
  63. package/dist/core/setup.js +202 -0
  64. package/dist/core/simulator.d.ts +21 -0
  65. package/dist/core/simulator.js +107 -0
  66. package/dist/core/state.d.ts +2 -0
  67. package/dist/core/state.js +9 -0
  68. package/dist/core/tool.d.ts +5 -0
  69. package/dist/core/tool.js +54 -0
  70. package/dist/core/version.d.ts +1 -0
  71. package/dist/core/version.js +5 -0
  72. package/dist/core/workspace.d.ts +1 -0
  73. package/dist/core/workspace.js +109 -0
  74. package/dist/mcp/server.d.ts +1 -0
  75. package/dist/mcp/server.js +188 -0
  76. package/package.json +58 -4
  77. package/skills/emd/SKILL.md +35 -0
@@ -0,0 +1,202 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { axeDir, axePin } from "./device/axe.js";
7
+ import { detectEnvironment } from "./device/backend.js";
8
+ import { doctor } from "./doctor.js";
9
+ import { firstLine } from "./log.js";
10
+ import { homeDir } from "./state.js";
11
+ import { runTool } from "./tool.js";
12
+ import { version } from "./version.js";
13
+ // The installers `setup` calls (decision 0002), pinned like AXe and Maestro.
14
+ const addMcp = "add-mcp@2.6.1";
15
+ const skillsCli = "skills@1.7.6";
16
+ // The agents `setup` supports (vision.md), each found by its home folder.
17
+ const agents = [
18
+ { id: "claude-code", dir: ".claude", config: ".claude.json" },
19
+ { id: "codex", dir: ".codex", config: ".codex/config.toml" },
20
+ { id: "cursor", dir: ".cursor", config: ".cursor/mcp.json" },
21
+ ];
22
+ // Each installer downloads its package on first use, so it gets 5 minutes.
23
+ const installSeconds = 300;
24
+ const realDeps = {
25
+ run: async (command, args) => {
26
+ const installer = args.find((a) => /^(add-mcp|skills)@/.test(a)) ?? command;
27
+ await runTool(installer, command, args, installSeconds);
28
+ },
29
+ platform: process.platform,
30
+ axe: axePin,
31
+ };
32
+ // Downloads the pinned archive, checks its SHA-256, unpacks it next to its
33
+ // final folder, runs it, and only then moves it there, so a failed install
34
+ // leaves nothing that `detectEnvironment` would find.
35
+ async function installAxe(axe, run) {
36
+ const archive = `${axe.dir}.tar.gz`;
37
+ const partial = `${axe.dir}.partial`;
38
+ rmSync(partial, { recursive: true, force: true });
39
+ mkdirSync(partial, { recursive: true });
40
+ try {
41
+ await run("curl", ["-fsSL", "--retry", "3", "-o", archive, axe.url]);
42
+ const sha = createHash("sha256")
43
+ .update(readFileSync(archive))
44
+ .digest("hex");
45
+ if (sha !== axe.sha256) {
46
+ throw new Error(`AXe's archive has SHA-256 ${sha}, not ${axe.sha256}.`);
47
+ }
48
+ await run("tar", ["-xzf", archive, "-C", partial]);
49
+ const bin = join(partial, "axe");
50
+ const { stdout } = await runTool("axe --version", bin, ["--version"], 60);
51
+ if (!stdout.split("\n").includes(axe.version)) {
52
+ throw new Error(`AXe printed ${firstLine(stdout)}, not ${axe.version}.`);
53
+ }
54
+ rmSync(axe.dir, { recursive: true, force: true });
55
+ renameSync(partial, axe.dir);
56
+ }
57
+ finally {
58
+ rmSync(archive, { force: true });
59
+ rmSync(partial, { recursive: true, force: true });
60
+ }
61
+ }
62
+ // The package root: the skill's source, and where EMD runs from.
63
+ const skillSource = () => fileURLToPath(new URL("../../", import.meta.url));
64
+ // From an installed package (npx's cache included), the server is this exact
65
+ // version through npx, so it stays the version of the skill that setup copies
66
+ // (decision 0011). From a clone, it is the clone's build.
67
+ const emdServer = () => skillSource().split(sep).includes("node_modules")
68
+ ? `npx -y emd-agents@${version()} mcp`
69
+ : `${process.execPath} ${fileURLToPath(new URL("../bin.js", import.meta.url))} mcp`;
70
+ function commands(ids) {
71
+ const to = ids.flatMap((id) => ["-a", id]);
72
+ return [
73
+ ["npx", ["-y", addMcp, emdServer(), "-n", "emd", "-g", ...to, "-y"]],
74
+ ["npx", ["-y", skillsCli, "add", skillSource(), "-g", ...to, "-y"]],
75
+ ];
76
+ }
77
+ const shown = ([command, args]) => [command, ...args.map((a) => (/\s/.test(a) ? `"${a}"` : a))].join(" ");
78
+ // A JSON config that doesn't parse stops setup before any write.
79
+ function unreadable(path) {
80
+ if (!path.endsWith(".json") || !existsSync(path))
81
+ return false;
82
+ try {
83
+ JSON.parse(readFileSync(path, "utf8"));
84
+ return false;
85
+ }
86
+ catch {
87
+ return true;
88
+ }
89
+ }
90
+ // Whether an agent has EMD's server, read back from its config.
91
+ function registered(path) {
92
+ if (!existsSync(path))
93
+ return false;
94
+ const text = readFileSync(path, "utf8");
95
+ return path.endsWith(".toml")
96
+ ? text.includes("[mcp_servers.emd]")
97
+ : Boolean(JSON.parse(text).mcpServers?.emd);
98
+ }
99
+ export async function setup(options = {}, deps = realDeps) {
100
+ const home = homedir();
101
+ const found = agents.filter((a) => existsSync(join(home, a.dir)));
102
+ const unknown = (options.only ?? []).filter((id) => !agents.some((a) => a.id === id));
103
+ if (unknown.length > 0) {
104
+ return {
105
+ verdict: "failed",
106
+ reason: `Unknown agent: ${unknown.join(", ")}. Supported: ${agents.map((a) => a.id).join(", ")}.`,
107
+ agents: [],
108
+ steps: [],
109
+ };
110
+ }
111
+ const picked = options.only
112
+ ? found.filter((a) => options.only?.includes(a.id))
113
+ : found;
114
+ const listed = picked.map((a) => ({
115
+ id: a.id,
116
+ config: join(home, a.config),
117
+ }));
118
+ if (picked.length === 0) {
119
+ return {
120
+ verdict: "failed",
121
+ reason: "No supported agent found (Claude Code, Codex or Cursor).",
122
+ agents: [],
123
+ steps: [],
124
+ };
125
+ }
126
+ const steps = commands(picked.map((a) => a.id));
127
+ // Every supported stack on macOS is iOS today, so a Mac gets AXe.
128
+ const axe = deps.platform === "darwin" && !(await detectEnvironment()).axe
129
+ ? { ...deps.axe, dir: axeDir() }
130
+ : undefined;
131
+ const plan = {
132
+ agents: listed,
133
+ steps: steps.map(shown),
134
+ ...(axe && { axe }),
135
+ };
136
+ const broken = listed.filter((a) => unreadable(a.config));
137
+ if (broken.length > 0) {
138
+ return {
139
+ verdict: "failed",
140
+ reason: `Not valid JSON, so nothing was changed: ${broken.map((a) => a.config).join(", ")}.`,
141
+ ...plan,
142
+ };
143
+ }
144
+ if (!options.apply)
145
+ return { verdict: "planned", ...plan };
146
+ // AXe first: if it fails, no agent config has changed.
147
+ if (axe) {
148
+ try {
149
+ await installAxe(axe, deps.run);
150
+ }
151
+ catch (error) {
152
+ return {
153
+ verdict: "failed",
154
+ reason: `AXe was not installed: ${firstLine(error)}`,
155
+ ...plan,
156
+ };
157
+ }
158
+ }
159
+ // Back up each config that exists, then change it.
160
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
161
+ const backups = join(homeDir(), "backups", stamp);
162
+ const withBackups = listed.map((a) => {
163
+ if (!existsSync(a.config))
164
+ return a;
165
+ const backup = join(backups, a.id, a.config.split(sep).at(-1) ?? "");
166
+ mkdirSync(dirname(backup), { recursive: true });
167
+ copyFileSync(a.config, backup);
168
+ return { ...a, backup };
169
+ });
170
+ try {
171
+ for (const [command, args] of steps)
172
+ await deps.run(command, args);
173
+ }
174
+ catch (error) {
175
+ return {
176
+ verdict: "failed",
177
+ reason: `${firstLine(error)} Backups: ${backups}.`,
178
+ ...plan,
179
+ agents: withBackups,
180
+ };
181
+ }
182
+ const skill = [".agents", ".claude"].some((dir) => existsSync(join(home, dir, "skills", "emd", "SKILL.md")));
183
+ const missing = listed
184
+ .filter((a) => !registered(a.config))
185
+ .map((a) => a.id)
186
+ .concat(skill ? [] : ["the skill"]);
187
+ if (missing.length > 0) {
188
+ return {
189
+ verdict: "failed",
190
+ reason: `Not in place after setup: ${missing.join(", ")}. Backups: ${backups}.`,
191
+ ...plan,
192
+ agents: withBackups,
193
+ };
194
+ }
195
+ return {
196
+ verdict: "done",
197
+ ...plan,
198
+ agents: withBackups,
199
+ restart: listed.map((a) => a.id),
200
+ doctor: await doctor(),
201
+ };
202
+ }
@@ -0,0 +1,21 @@
1
+ export type Device = {
2
+ id: string;
3
+ name: string;
4
+ state: string;
5
+ version: number[];
6
+ };
7
+ export declare function listDevices(): Promise<Device[]>;
8
+ export declare function pickDevice(devices: Device[], wanted?: string, sdk?: number[]): Device | undefined;
9
+ export declare function newerThan(device: Device, sdk: number[]): boolean;
10
+ export declare function simulatorSdk(): Promise<number[] | undefined>;
11
+ export declare function parseSdkVersion(output: string): number[] | undefined;
12
+ export declare function boot(device: Device): Promise<void>;
13
+ export declare function launchApp(device: Device, appId: string): Promise<number>;
14
+ export declare function cloneDevice(base: Device, name: string): Promise<string>;
15
+ export type Simulator = {
16
+ id: string;
17
+ name: string;
18
+ state: string;
19
+ };
20
+ export declare function listSimulators(): Promise<Simulator[]>;
21
+ export declare function removeSimulator(device: Simulator): Promise<void>;
@@ -0,0 +1,107 @@
1
+ import { runTool } from "./tool.js";
2
+ export async function listDevices() {
3
+ const { stdout } = await runTool("simctl list", "xcrun", ["simctl", "list", "devices", "available", "--json"], 60);
4
+ const { devices } = JSON.parse(stdout);
5
+ return Object.entries(devices).flatMap(([runtime, list]) => {
6
+ const match = runtime.match(/\.iOS-([\d-]+)$/);
7
+ if (!match?.[1])
8
+ return [];
9
+ const version = match[1].split("-").map(Number);
10
+ return list
11
+ .filter((d) => d.isAvailable !== false)
12
+ .map((d) => ({ id: d.udid, name: d.name, state: d.state, version }));
13
+ });
14
+ }
15
+ const newest = (a, b) => {
16
+ for (let i = 0; i < Math.max(a.version.length, b.version.length); i++) {
17
+ const diff = (b.version[i] ?? 0) - (a.version[i] ?? 0);
18
+ if (diff !== 0)
19
+ return diff;
20
+ }
21
+ return a.name.localeCompare(b.name);
22
+ };
23
+ // A named device wins; otherwise a booted iPhone; otherwise the newest iPhone.
24
+ // With no device named, only runtimes that `sdk` (the selected Xcode's iOS
25
+ // simulator SDK) can build for.
26
+ export function pickDevice(devices, wanted, sdk) {
27
+ const sorted = [...devices].sort(newest);
28
+ if (wanted) {
29
+ const key = wanted.toLowerCase();
30
+ return sorted.find((d) => d.id.toLowerCase() === key || d.name.toLowerCase() === key);
31
+ }
32
+ const iphones = sorted.filter((d) => d.name.startsWith("iPhone") && !(sdk && newerThan(d, sdk)));
33
+ return iphones.find((d) => d.state === "Booted") ?? iphones[0];
34
+ }
35
+ // True when the device's iOS major.minor is newer than `sdk`'s. A patch
36
+ // runtime (26.6.1) builds with its SDK (26.6).
37
+ export function newerThan(device, sdk) {
38
+ for (let i = 0; i < 2; i++) {
39
+ const diff = (device.version[i] ?? 0) - (sdk[i] ?? 0);
40
+ if (diff !== 0)
41
+ return diff > 0;
42
+ }
43
+ return false;
44
+ }
45
+ // The selected Xcode's iOS simulator SDK version, e.g. [26, 6]; undefined when
46
+ // xcrun cannot tell, so the pick is not limited.
47
+ export async function simulatorSdk() {
48
+ try {
49
+ const { stdout } = await runTool("xcrun --show-sdk-version", "xcrun", ["--sdk", "iphonesimulator", "--show-sdk-version"], 60);
50
+ return parseSdkVersion(stdout);
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ export function parseSdkVersion(output) {
57
+ const match = output.trim().match(/^(\d+)\.(\d+)/);
58
+ return match ? [Number(match[1]), Number(match[2])] : undefined;
59
+ }
60
+ export async function boot(device) {
61
+ if (device.state !== "Booted") {
62
+ try {
63
+ await runTool("simctl boot", "xcrun", ["simctl", "boot", device.id], 120);
64
+ }
65
+ catch (error) {
66
+ // Booting a device that is already booted is not a failure.
67
+ if (!/current state: Booted/i.test(String(error)))
68
+ throw error;
69
+ }
70
+ }
71
+ await runTool("simctl bootstatus", "xcrun", ["simctl", "bootstatus", device.id, "-b"], 300);
72
+ }
73
+ // Returns the app's pid. Brings the app forward if it is already running.
74
+ export async function launchApp(device, appId) {
75
+ const { stdout } = await runTool("simctl launch", "xcrun", ["simctl", "launch", device.id, appId], 120);
76
+ const pid = Number(stdout.trim().split(":").pop());
77
+ if (!Number.isInteger(pid))
78
+ throw new Error(`unexpected output: ${stdout}`);
79
+ return pid;
80
+ }
81
+ // A new simulator with the same type and runtime as `base`; returns its UDID.
82
+ // The base must be shut down.
83
+ export async function cloneDevice(base, name) {
84
+ const { stdout } = await runTool("simctl clone", "xcrun", ["simctl", "clone", base.id, name], 300);
85
+ return stdout.trim();
86
+ }
87
+ // Every simulator on the machine, available or not.
88
+ export async function listSimulators() {
89
+ const { stdout } = await runTool("simctl list", "xcrun", ["simctl", "list", "devices", "--json"], 60);
90
+ const { devices } = JSON.parse(stdout);
91
+ return Object.values(devices).flatMap((list) => list.map((d) => ({ id: d.udid, name: d.name, state: d.state })));
92
+ }
93
+ // Shuts a simulator down if it is booted, then deletes it. Each step names the
94
+ // simulator, so a failure says which one.
95
+ export async function removeSimulator(device) {
96
+ const simctl = (action) => runTool(`simctl ${action} ${device.id}`, "xcrun", ["simctl", action, device.id], 120);
97
+ if (device.state === "Booted") {
98
+ try {
99
+ await simctl("shutdown");
100
+ }
101
+ catch (error) {
102
+ if (!/current state: Shutdown/i.test(String(error)))
103
+ throw error;
104
+ }
105
+ }
106
+ await simctl("delete");
107
+ }
@@ -0,0 +1,2 @@
1
+ export declare const stateDir: () => string;
2
+ export declare const homeDir: () => string;
@@ -0,0 +1,9 @@
1
+ import { homedir, tmpdir } from "node:os";
2
+ import { join } from "node:path";
3
+ // Where EMD keeps jobs and run logs. Every `emd` process on the machine shares
4
+ // it, so a job started by one process can be read by another. Temporary on
5
+ // purpose; `emd gc` does not touch it. EMD_STATE_DIR overrides it (tests).
6
+ export const stateDir = () => process.env.EMD_STATE_DIR ?? join(tmpdir(), "emd");
7
+ // Where EMD keeps what must outlive a reboot: the ownership ledger, the
8
+ // per-worktree build folders and the check counts. EMD_STATE_DIR overrides it.
9
+ export const homeDir = () => process.env.EMD_STATE_DIR ?? join(homedir(), ".emd");
@@ -0,0 +1,5 @@
1
+ export declare function runTool(step: string, file: string, args: string[], seconds: number, options?: {
2
+ env?: Record<string, string>;
3
+ }): Promise<{
4
+ stdout: string;
5
+ }>;
@@ -0,0 +1,54 @@
1
+ import { spawn } from "node:child_process";
2
+ // Runs an outside tool and resolves with its stdout. It runs in its own process
3
+ // group, so when `seconds` pass the whole group dies, including anything the
4
+ // tool started (xcrun does not pass a signal on to the tool it runs). Its pipes
5
+ // close then too, so a child that left the group cannot hold the call open. A
6
+ // timeout rejects with "<step> timed out after Ns" so a verdict can name the
7
+ // step. Every rejection after the tool ran carries the stdout it printed.
8
+ export function runTool(step, file, args, seconds, options = {}) {
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawn(file, args, {
11
+ detached: true,
12
+ stdio: ["ignore", "pipe", "pipe"],
13
+ ...(options.env && { env: { ...process.env, ...options.env } }),
14
+ });
15
+ let stdout = "";
16
+ let stderr = "";
17
+ let timedOut = false;
18
+ // Decode as a stream: a character split between two reads stays whole.
19
+ child.stdout.setEncoding("utf8");
20
+ child.stderr.setEncoding("utf8");
21
+ child.stdout.on("data", (chunk) => {
22
+ stdout += chunk;
23
+ });
24
+ child.stderr.on("data", (chunk) => {
25
+ stderr += chunk;
26
+ });
27
+ const timer = setTimeout(() => {
28
+ timedOut = true;
29
+ try {
30
+ if (child.pid)
31
+ process.kill(-child.pid, "SIGKILL");
32
+ }
33
+ catch {
34
+ // The group may already be dead.
35
+ }
36
+ child.stdout.destroy();
37
+ child.stderr.destroy();
38
+ }, seconds * 1000);
39
+ child.on("error", (error) => {
40
+ clearTimeout(timer);
41
+ reject(error);
42
+ });
43
+ child.on("close", (code) => {
44
+ clearTimeout(timer);
45
+ const fail = (message) => reject(Object.assign(new Error(message), { stdout }));
46
+ if (timedOut)
47
+ fail(`${step} timed out after ${seconds}s`);
48
+ else if (code === 0)
49
+ resolve({ stdout });
50
+ else
51
+ fail(`${step} failed (exit ${code}): ${stderr.trim()}`);
52
+ });
53
+ });
54
+ }
@@ -0,0 +1 @@
1
+ export declare function version(): string;
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function version() {
3
+ const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
4
+ return pkg.version;
5
+ }
@@ -0,0 +1 @@
1
+ export declare function workspaceApps(root: string): Promise<string[]>;
@@ -0,0 +1,109 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { probeStack } from "./probe.js";
4
+ // At a workspace root (pnpm-workspace.yaml, or a `workspaces` field in
5
+ // package.json), the workspace packages that EMD can detect, as paths relative
6
+ // to the root. Reads only the workspace's package globs, never node_modules.
7
+ // No package manager command: each lists packages its own way, needs its own
8
+ // install, and EMD cannot pin the user's version (decision 0008).
9
+ const maxApps = 20;
10
+ const deepest = 4;
11
+ function workspaceGlobs(root) {
12
+ try {
13
+ const yaml = readFileSync(join(root, "pnpm-workspace.yaml"), "utf8");
14
+ return pnpmGlobs(yaml);
15
+ }
16
+ catch { }
17
+ try {
18
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
19
+ const list = Array.isArray(pkg.workspaces)
20
+ ? pkg.workspaces
21
+ : pkg.workspaces?.packages;
22
+ return Array.isArray(list)
23
+ ? list.filter((glob) => typeof glob === "string")
24
+ : [];
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ }
30
+ // The `packages:` list, as a block (`- apps/*` lines) or inline (`[a, b]`).
31
+ function pnpmGlobs(yaml) {
32
+ const unquote = (item) => item
33
+ .replace(/#.*$/, "")
34
+ .trim()
35
+ .replace(/^["']|["']$/g, "");
36
+ const lines = yaml.split("\n");
37
+ const start = lines.findIndex((line) => /^packages:/.test(line));
38
+ if (start < 0)
39
+ return [];
40
+ const inline = lines[start]?.match(/^packages:\s*\[(.*)\]/);
41
+ if (inline?.[1])
42
+ return inline[1].split(",").map(unquote).filter(Boolean);
43
+ const globs = [];
44
+ for (const line of lines.slice(start + 1)) {
45
+ if (/^\S/.test(line))
46
+ break;
47
+ const item = line.match(/^\s+-\s*(.+)$/)?.[1];
48
+ if (item)
49
+ globs.push(unquote(item));
50
+ }
51
+ return globs.filter(Boolean);
52
+ }
53
+ const subfolders = (dir) => {
54
+ try {
55
+ return readdirSync(dir, { withFileTypes: true })
56
+ .filter((entry) => entry.isDirectory() &&
57
+ entry.name !== "node_modules" &&
58
+ !entry.name.startsWith("."))
59
+ .map((entry) => join(dir, entry.name));
60
+ }
61
+ catch {
62
+ return [];
63
+ }
64
+ };
65
+ const below = (dir, depth) => depth === 0
66
+ ? []
67
+ : subfolders(dir).flatMap((sub) => [sub, ...below(sub, depth - 1)]);
68
+ // Folders that match one glob: literal parts, `*` within a part, and `**`.
69
+ function expand(root, glob) {
70
+ let dirs = [root];
71
+ for (const part of glob.replace(/^\.\//, "").split("/").filter(Boolean)) {
72
+ if (part === "node_modules")
73
+ return [];
74
+ if (part === "**") {
75
+ dirs = dirs.flatMap((dir) => [dir, ...below(dir, deepest)]);
76
+ }
77
+ else if (part.includes("*")) {
78
+ const pattern = new RegExp(`^${part
79
+ .split("*")
80
+ .map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
81
+ .join("[^/]*")}$`);
82
+ dirs = dirs.flatMap((dir) => subfolders(dir).filter((sub) => pattern.test(relative(dir, sub))));
83
+ }
84
+ else {
85
+ dirs = dirs
86
+ .map((dir) => join(dir, part))
87
+ .filter((dir) => existsSync(dir));
88
+ }
89
+ }
90
+ return dirs;
91
+ }
92
+ export async function workspaceApps(root) {
93
+ const globs = workspaceGlobs(root);
94
+ const excluded = new Set(globs
95
+ .filter((glob) => glob.startsWith("!"))
96
+ .flatMap((glob) => expand(root, glob.slice(1))));
97
+ const packages = new Set(globs
98
+ .filter((glob) => !glob.startsWith("!"))
99
+ .flatMap((glob) => expand(root, glob))
100
+ .filter((dir) => dir !== root && !excluded.has(dir)));
101
+ const apps = [];
102
+ for (const dir of [...packages].sort()) {
103
+ if (await probeStack(dir))
104
+ apps.push(relative(root, dir));
105
+ if (apps.length === maxApps)
106
+ break;
107
+ }
108
+ return apps;
109
+ }
@@ -0,0 +1 @@
1
+ export declare function startServer(): void;