@elumixor/devkit 0.9.0 → 0.10.1

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/src/deploy.ts CHANGED
@@ -1,262 +1,8 @@
1
- import { spawn } from "node:child_process";
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { resolve } from "node:path";
4
- import { type DeployTarget, loadConfig, type Named } from "./config.ts";
1
+ import { loadConfig } from "./config.ts";
2
+ import { type GraphOptions, runGraph } from "./graph.ts";
5
3
 
6
- const PALETTE: readonly string[] = ["magenta", "cyan", "yellow", "green", "blue", "red"];
7
- const COLORS: Record<string, string> = {
8
- black: "30",
9
- red: "31",
10
- green: "32",
11
- yellow: "33",
12
- blue: "34",
13
- magenta: "35",
14
- cyan: "36",
15
- white: "37",
16
- gray: "90",
17
- };
18
- const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
19
- const FRAME_MS = 80;
20
- const TAIL_ON_FAILURE = 25;
21
-
22
- const paint = (text: string, color: string) => `\x1b[${COLORS[color] ?? "37"}m${text}\x1b[0m`;
23
- const dim = (text: string) => `\x1b[2m${text}\x1b[0m`;
24
- const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
25
-
26
- type Status = "waiting" | "running" | "done" | "failed" | "skipped";
27
-
28
- /** One target's progress, and everything the board needs to draw its line. */
29
- interface Job {
30
- target: Named<DeployTarget> & { command: string };
31
- label: string;
32
- color: string;
33
- status: Status;
34
- note: string;
35
- startedAt?: number;
36
- endedAt?: number;
37
- lines: string[];
38
- logPath: string;
39
- }
40
-
41
- /**
42
- * Run the configured deploys, in parallel where they don't depend on each other.
43
- *
44
- * A deploy is several long builds that each print thousands of lines, and interleaving all of it
45
- * is unreadable — so on a terminal this draws one line per target (what it's doing, for how long)
46
- * and keeps the full output in `.devkit/deploy/<name>.log`, printing the tail of whichever target
47
- * failed. Anywhere else — CI, a pipe, a log file — it falls back to prefixed streaming, because a
48
- * redrawing board in a file is worse than useless.
49
- */
50
- export async function runDeploy(only: string[], options: { dry?: boolean; verbose?: boolean } = {}) {
51
- const { deploy } = loadConfig();
52
- if (!deploy.length) throw new Error('No "devkit.deploy" targets in package.json');
53
-
54
- const unknown = only.filter((name) => !deploy.some((target) => target.name === name));
55
- if (unknown.length) {
56
- throw new Error(`Unknown target${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}`);
57
- }
58
-
59
- for (const target of deploy) {
60
- const missing = (target.needs ?? []).filter((need) => !deploy.some((other) => other.name === need));
61
- if (missing.length)
62
- throw new Error(`${target.name} needs unknown target${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}`);
63
- if (!target.command && !target.type) throw new Error(`${target.name} needs a "command" or a "type"`);
64
- }
65
-
66
- const jobs = selected(deploy, only).map(toJob);
67
- if (options.dry) return printPlan(jobs);
68
-
69
- const logDir = resolve(process.cwd(), ".devkit/deploy");
70
- mkdirSync(logDir, { recursive: true });
71
-
72
- const live = Boolean(process.stdout.isTTY) && !options.verbose;
73
- console.log(
74
- bold(`\ndeploying ${jobs.map((job) => job.label).join(", ")}`) +
75
- dim(live ? ` · logs in ${"./.devkit/deploy"}` : ""),
76
- );
77
- console.log();
78
- const board = live ? startBoard(jobs) : null;
79
-
80
- // Each target waits on the gates of the targets it needs, so the graph runs itself: independent
81
- // targets start together, dependents start the moment their last dependency lands.
82
- const gates = new Map(jobs.map((job) => [job.label, gate()]));
83
-
84
- const started = Date.now();
85
- await Promise.all(
86
- jobs.map(async (job) => {
87
- const needs = (job.target.needs ?? []).map((name) => jobs.find((other) => other.label === name)) as Job[];
88
- await Promise.all(needs.map((need) => gates.get(need.label)?.promise));
89
- await runJob(job, needs, live);
90
- gates.get(job.label)?.open();
91
- }),
92
- );
93
- board?.stop();
94
-
95
- report(jobs, Date.now() - started);
96
- if (jobs.some((job) => job.status !== "done")) process.exitCode = 1;
97
- }
98
-
99
- /** The targets asked for, plus whatever they depend on — a target can't run without its needs. */
100
- function selected(targets: Named<DeployTarget>[], only: string[]) {
101
- if (!only.length) return targets;
102
- const wanted = new Set(only);
103
- let grew = true;
104
- while (grew) {
105
- grew = false;
106
- for (const target of targets) {
107
- if (!wanted.has(target.name)) continue;
108
- for (const need of target.needs ?? []) {
109
- if (!wanted.has(need)) {
110
- wanted.add(need);
111
- grew = true;
112
- }
113
- }
114
- }
115
- }
116
- return targets.filter((target) => wanted.has(target.name));
4
+ /** Deploy every configured platform, in parallel where they don't depend on each other. */
5
+ export async function runDeploy(only: string[], options: GraphOptions = {}) {
6
+ const { deploy, generate } = loadConfig();
7
+ await runGraph("deploy", deploy, only, generate, options);
117
8
  }
118
-
119
- function toJob(target: Named<DeployTarget>, index: number): Job {
120
- // A built-in target has no shell command of its own — it runs through `devkit _deploy-target`,
121
- // which looks its options back up from this same config by name.
122
- const command = target.command ?? `devkit _deploy-target ${JSON.stringify(target.name)}`;
123
- return {
124
- target: { ...target, command },
125
- label: target.name,
126
- color: target.color ?? (PALETTE[index % PALETTE.length] as string),
127
- status: "waiting",
128
- note: target.needs?.length ? `waiting for ${target.needs.join(", ")}` : "",
129
- lines: [],
130
- logPath: resolve(process.cwd(), ".devkit/deploy", `${target.name}.log`),
131
- };
132
- }
133
-
134
- /** Runs one target's command to completion, unless something it needed didn't get there. */
135
- async function runJob(job: Job, needs: Job[], live: boolean) {
136
- const blocker = needs.find((need) => need.status !== "done");
137
- if (blocker) {
138
- job.status = "skipped";
139
- job.note = `skipped — ${blocker.label} ${blocker.status === "failed" ? "failed" : "never ran"}`;
140
- return;
141
- }
142
-
143
- job.status = "running";
144
- job.startedAt = Date.now();
145
- job.note = job.target.command;
146
-
147
- const code = await new Promise<number>((done) => {
148
- const child = spawn(job.target.command, { shell: true, stdio: ["ignore", "pipe", "pipe"] });
149
- for (const stream of [child.stdout, child.stderr]) {
150
- let rest = "";
151
- stream.on("data", (chunk: Buffer) => {
152
- const parts = (rest + chunk.toString()).split("\n");
153
- rest = parts.pop() ?? "";
154
- for (const line of parts) {
155
- job.lines.push(line);
156
- job.note = line.trim() || job.note;
157
- if (!live) console.log(`${paint(`[${job.label}]`, job.color)} ${line}`);
158
- }
159
- });
160
- }
161
- child.on("close", (status) => done(status ?? 1));
162
- });
163
-
164
- job.endedAt = Date.now();
165
- job.status = code === 0 ? "done" : "failed";
166
- job.note = code === 0 ? "done" : `exit ${code}`;
167
- writeFileSync(job.logPath, `${job.lines.join("\n")}\n`);
168
- }
169
-
170
- /** Redraws the board until stopped. One line per target, in the order they were configured. */
171
- function startBoard(jobs: Job[]) {
172
- let drawn = 0;
173
- let frame = 0;
174
-
175
- const draw = () => {
176
- // A pty with no window size reports 0 — treat that as a sane default rather than clipping to nothing.
177
- const width = process.stdout.columns || 100;
178
- const pad = Math.max(...jobs.map((job) => job.label.length));
179
- const lines = jobs.map((job) => {
180
- const mark =
181
- job.status === "running"
182
- ? paint(SPINNER[frame % SPINNER.length] as string, job.color)
183
- : job.status === "done"
184
- ? paint("✓", "green")
185
- : job.status === "failed"
186
- ? paint("✗", "red")
187
- : job.status === "skipped"
188
- ? dim("–")
189
- : dim("·");
190
- const time = job.startedAt ? dim(` ${elapsed(job)}`) : "";
191
- const head = `${mark} ${paint(job.label.padEnd(pad), job.color)}${time} `;
192
- // The note is whatever the target last printed, so it has to be cut to the terminal rather
193
- // than wrapped — a wrapped line breaks the cursor arithmetic that redraws this block.
194
- const room = Math.max(10, width - visibleLength(head) - 1);
195
- return head + dim(clip(job.note, room));
196
- });
197
-
198
- process.stdout.write(`${drawn ? `\x1b[${drawn}A` : ""}${lines.map((line) => `\x1b[2K${line}`).join("\n")}\n`);
199
- drawn = lines.length;
200
- frame++;
201
- };
202
-
203
- process.stdout.write("\x1b[?25l");
204
- draw();
205
- const timer = setInterval(draw, FRAME_MS);
206
-
207
- return {
208
- stop() {
209
- clearInterval(timer);
210
- draw();
211
- process.stdout.write("\x1b[?25h");
212
- },
213
- };
214
- }
215
-
216
- function report(jobs: Job[], total: number) {
217
- const failed = jobs.filter((job) => job.status === "failed");
218
- for (const job of failed) {
219
- console.log(`\n${paint(`── ${job.label} failed`, "red")} ${dim(job.logPath)}`);
220
- for (const line of job.lines.slice(-TAIL_ON_FAILURE)) console.log(dim(` ${line}`));
221
- }
222
-
223
- const done = jobs.filter((job) => job.status === "done").length;
224
- const skipped = jobs.filter((job) => job.status === "skipped").length;
225
- const parts = [
226
- failed.length ? paint(`${failed.length} failed`, "red") : paint("all good", "green"),
227
- skipped ? dim(`${skipped} skipped`) : "",
228
- dim(duration(total)),
229
- ].filter(Boolean);
230
- console.log(`\n${bold(`${done}/${jobs.length} deployed`)} · ${parts.join(" · ")}\n`);
231
- }
232
-
233
- function printPlan(jobs: Job[]) {
234
- console.log(bold("\ndeploy plan\n"));
235
- for (const job of jobs) {
236
- const after = job.target.needs?.length ? dim(` after ${job.target.needs.join(", ")}`) : "";
237
- console.log(` ${paint(job.label, job.color)}${after}\n ${dim(job.target.command)}`);
238
- }
239
- console.log();
240
- }
241
-
242
- /** A promise plus the handle that settles it — one per target, opened when that target ends. */
243
- function gate() {
244
- let open!: () => void;
245
- const promise = new Promise<void>((resolve) => {
246
- open = resolve;
247
- });
248
- return { promise, open };
249
- }
250
-
251
- const elapsed = (job: Job) => duration((job.endedAt ?? Date.now()) - (job.startedAt ?? Date.now()));
252
-
253
- function duration(ms: number) {
254
- const seconds = Math.round(ms / 1000);
255
- return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, "0")}s`;
256
- }
257
-
258
- // Colour codes take no space on screen, so the board has to measure what a reader would see.
259
- // biome-ignore lint/suspicious/noControlCharactersInRegex: an escape sequence is the thing being matched
260
- const ANSI = /\x1b\[[0-9;]*m/g;
261
- const visibleLength = (text: string) => text.replace(ANSI, "").length;
262
- const clip = (text: string, room: number) => (text.length <= room ? text : `${text.slice(0, room - 1)}…`);
@@ -0,0 +1,54 @@
1
+ import { join } from "node:path";
2
+ import { $ } from "bun";
3
+ import { bootSimulator, installAndLaunch, productPath, rerunOnChange, type XcodeBuild, xcodeBuild } from "../apple.ts";
4
+ import { waitForPort } from "../wait-port.ts";
5
+
6
+ export interface CapacitorIosDevOptions extends XcodeBuild {
7
+ /** Capacitor dir, holding `capacitor.config.ts` and `ios/` (default `apps/frontend`). */
8
+ frontendDir?: string;
9
+ /** Bundle id to install and launch. */
10
+ bundleId: string;
11
+ /** Simulator to run on — overridable with `--device` or `DEVKIT_SIM_DEVICE`. */
12
+ device: string;
13
+ /** Port the web dev server listens on, waited for before the app is launched (default 8081). */
14
+ port?: number;
15
+ /** Env var the Capacitor config reads to point the webview at the dev server. */
16
+ liveReloadEnv?: string;
17
+ /** Native source dirs that, when saved, rebuild and relaunch the app. */
18
+ watch?: string[];
19
+ }
20
+
21
+ /**
22
+ * Runs the iPhone app on a simulator against the running dev server.
23
+ *
24
+ * The webview loads the page over the network rather than from the bundle, so every web edit is
25
+ * already live by the time it lands — `cap sync` here copies the plugins and the configuration,
26
+ * not the app. Native edits still need a compile, which is what the watch at the end is for.
27
+ */
28
+ export async function devCapacitorIos(options: CapacitorIosDevOptions, flags: { device?: string } = {}) {
29
+ const frontendDir = options.frontendDir ?? "apps/frontend";
30
+ const deviceName = flags.device ?? process.env.DEVKIT_SIM_DEVICE ?? options.device;
31
+ const port = options.port ?? 8081;
32
+ const sdk = options.sdk ?? "iphonesimulator";
33
+ const build = { ...options, sdk };
34
+
35
+ // Syncing before the server is up would bake a URL nothing answers on into the webview, and the
36
+ // app would open on a blank page until it is restarted by hand.
37
+ if (!(await waitForPort(port))) throw new Error(`Nothing came up on port ${port} — is the web dev server running?`);
38
+
39
+ await $`bunx cap sync ios`.cwd(frontendDir).env({
40
+ ...process.env,
41
+ [options.liveReloadEnv ?? "CAPACITOR_LIVE_RELOAD"]: "true",
42
+ });
43
+
44
+ const udid = await bootSimulator(deviceName);
45
+
46
+ const launch = async () => {
47
+ await xcodeBuild({ ...build, destination: `id=${udid}` });
48
+ await installAndLaunch(udid, productPath(build), options.bundleId);
49
+ console.log(`${options.scheme} running on ${deviceName}, loading http://<lan>:${port}`);
50
+ };
51
+
52
+ await launch();
53
+ await rerunOnChange(options.watch ?? [join(frontendDir, "ios/App/App")], launch);
54
+ }
@@ -0,0 +1,43 @@
1
+ import { bootSimulator, installAndLaunch, productPath, rerunOnChange, type XcodeBuild, xcodeBuild } from "../apple.ts";
2
+
3
+ export interface XcodeSimOptions extends XcodeBuild {
4
+ /** Bundle id to install and launch. */
5
+ bundleId: string;
6
+ /** Simulator to run on — overridable with `--device` or `DEVKIT_SIM_DEVICE`. */
7
+ device: string;
8
+ /** Env var the app reads to show sample data; set unless `--real` is passed. */
9
+ previewEnv?: string;
10
+ /** Source dirs that, when saved, rebuild and relaunch the app. */
11
+ watch?: string[];
12
+ }
13
+
14
+ /**
15
+ * Build an Apple app and run it on a simulator, without going through Xcode, then keep rebuilding
16
+ * it as its sources change.
17
+ *
18
+ * A watch app usually has no sign-in of its own, so on a simulator with no paired phone it can
19
+ * only show its signed-out screen. `previewEnv` launches it with the app's own preview flag set
20
+ * instead, which is the point of running it here at all: gestures have to be felt.
21
+ */
22
+ export async function devXcodeSim(options: XcodeSimOptions, flags: { real?: boolean; device?: string } = {}) {
23
+ const deviceName = flags.device ?? process.env.DEVKIT_SIM_DEVICE ?? options.device;
24
+ const preview = !flags.real;
25
+ const sdk = options.sdk ?? "watchsimulator";
26
+ const build = { ...options, sdk };
27
+
28
+ const udid = await bootSimulator(deviceName);
29
+
30
+ const launch = async () => {
31
+ await xcodeBuild({ ...build, destination: `id=${udid}` });
32
+ await installAndLaunch(
33
+ udid,
34
+ productPath(build),
35
+ options.bundleId,
36
+ preview && options.previewEnv ? { [options.previewEnv]: "1" } : {},
37
+ );
38
+ console.log(`${options.scheme} running on ${deviceName}${preview && options.previewEnv ? " with sample data" : ""}`);
39
+ };
40
+
41
+ await launch();
42
+ await rerunOnChange(options.watch ?? [], launch);
43
+ }
package/src/dev.ts CHANGED
@@ -1,54 +1,101 @@
1
1
  import concurrently from "concurrently";
2
- import { type DevApp, loadConfig, type Named } from "./config.ts";
2
+ import { type DevPlatform, type DevProcess, loadConfig, type Named, withNeeds } from "./config.ts";
3
3
  import { freePort } from "./free-port.ts";
4
4
  import { openUrl, waitForPort } from "./wait-port.ts";
5
5
 
6
6
  const PALETTE = ["blue", "magenta", "green", "yellow", "cyan", "red"];
7
7
 
8
- /** Turn an app entry into the shell command that runs it. */
9
- function commandFor(app: Named<DevApp>): string {
10
- if (app.command) return app.command;
11
- const script = app.script ?? "dev";
12
- if (app.cwd) return `bun run --cwd ${app.cwd} ${script}`;
13
- return `bun --filter ${app.filter ?? app.name} ${script}`;
8
+ /** One line of the dev board: a name, a shell command, and whatever the URL banner needs. */
9
+ interface Process extends DevProcess {
10
+ /** What this line is called on screen. */
11
+ label: string;
12
+ /** The platform it belongs to — how a built-in target finds its options again. */
13
+ platform: string;
14
14
  }
15
15
 
16
- /** Free ports, print URLs, run every app side-by-side, optionally open the browser. */
17
- export async function runDev(open: boolean, dry = false): Promise<void> {
18
- const { apps } = loadConfig();
19
- if (!apps.length) throw new Error('No "devkit.apps" to run');
20
- const withPort = apps.filter((app) => app.port != null);
21
-
22
- if (dry) {
23
- console.log("devkit (dry run):");
24
- for (const app of apps) {
25
- const url = app.port != null ? ` → http://localhost:${app.port}${app.open ? " (open)" : ""}` : "";
26
- console.log(` [${app.name}] ${commandFor(app)}${url}`);
16
+ /** Flatten a platform into the processes it runs — a web platform is a client and an API. */
17
+ function processesOf(platform: Named<DevPlatform>): Process[] {
18
+ const group = platform.processes;
19
+ if (!group) return [{ ...platform, label: platform.name, platform: platform.name }];
20
+ if (platform.type) throw new Error(`"devkit.dev.${platform.name}" has both a "type" and "processes"`);
21
+
22
+ const keys = Object.keys(group);
23
+ if (!keys.length) throw new Error(`"devkit.dev.${platform.name}.processes" is empty`);
24
+ return keys.map((key) => {
25
+ const process = group[key] as DevProcess;
26
+ return {
27
+ ...process,
28
+ // The workspace a bare process runs in is named by its key, not by the platform's.
29
+ filter: process.filter ?? key,
30
+ // A platform that runs one process is that process; several need telling apart.
31
+ label: keys.length === 1 ? platform.name : `${platform.name}:${key}`,
32
+ platform: platform.name,
33
+ };
34
+ });
35
+ }
36
+
37
+ /** Turn a process entry into the shell command that runs it. */
38
+ function commandFor(process: Process): string {
39
+ // A raw command still honours `cwd` — `bunx tauri dev` means the app's directory, not the root.
40
+ if (process.command)
41
+ return process.cwd ? `sh -c ${JSON.stringify(`cd ${process.cwd} && ${process.command}`)}` : process.command;
42
+ // A built-in dev target runs through `devkit _run dev`, which looks its options back up from
43
+ // this same config — the same trick the build and deploy graphs use.
44
+ if (process.type) return `devkit _run dev ${JSON.stringify(process.platform)}`;
45
+ const script = process.script ?? "dev";
46
+ if (process.cwd) return `bun run --cwd ${process.cwd} ${script}`;
47
+ return `bun --filter ${process.filter ?? process.label} ${script}`;
48
+ }
49
+
50
+ /**
51
+ * Run the dev processes for the platforms asked for, side by side.
52
+ *
53
+ * `devkit dev` runs every platform; `devkit dev:mac` runs the Mac shell and, because it declares
54
+ * `needs`, the web stack it points at — a native shell with no dev server behind it is a window
55
+ * onto nothing.
56
+ */
57
+ export async function runDev(only: string[], flags: { open?: boolean; dry?: boolean } = {}): Promise<void> {
58
+ const { dev } = loadConfig();
59
+ if (!dev.length) throw new Error('No "devkit.dev" platforms to run');
60
+
61
+ for (const platform of dev) {
62
+ const missing = (platform.needs ?? []).filter((need) => !dev.some((other) => other.name === need));
63
+ if (missing.length) throw new Error(`${platform.name} needs unknown platform: ${missing.join(", ")}`);
64
+ }
65
+
66
+ const processes = withNeeds(dev, only).flatMap(processesOf);
67
+ const withPort = processes.filter((process) => process.port != null);
68
+
69
+ if (flags.dry) {
70
+ console.log("devkit dev (dry run):");
71
+ for (const process of processes) {
72
+ const url = process.port != null ? ` → http://localhost:${process.port}${process.open ? " (open)" : ""}` : "";
73
+ console.log(` [${process.label}] ${commandFor(process)}${url}`);
27
74
  }
28
75
  return;
29
76
  }
30
77
 
31
- await Promise.all(withPort.map((app) => freePort(app.port as number)));
78
+ await Promise.all(withPort.map((process) => freePort(process.port as number)));
32
79
 
33
80
  if (withPort.length > 0) {
34
- const width = Math.max(...withPort.map((app) => app.name.length));
35
- const lines = withPort.map((app) => `${app.name.padEnd(width)} http://localhost:${app.port}`);
81
+ const width = Math.max(...withPort.map((process) => process.label.length));
82
+ const lines = withPort.map((p) => `${p.label.padEnd(width)} http://localhost:${p.port}`);
36
83
  console.log(`\n${lines.join("\n")}\n`);
37
84
  }
38
85
 
39
86
  const { result } = concurrently(
40
- apps.map((app, i) => ({
41
- command: commandFor(app),
42
- name: app.name,
43
- prefixColor: app.color ?? PALETTE[i % PALETTE.length],
87
+ processes.map((process, i) => ({
88
+ command: commandFor(process),
89
+ name: process.label,
90
+ prefixColor: process.color ?? PALETTE[i % PALETTE.length],
44
91
  })),
45
92
  { prefix: "name", killOthersOn: ["failure", "success"] },
46
93
  );
47
94
 
48
- if (open) {
49
- for (const app of apps.filter((a) => a.open && a.port != null)) {
50
- const url = `http://localhost:${app.port}`;
51
- void waitForPort(app.port as number).then((ready) => {
95
+ if (flags.open) {
96
+ for (const process of processes.filter((p) => p.open && p.port != null)) {
97
+ const url = `http://localhost:${process.port}`;
98
+ void waitForPort(process.port as number).then((ready) => {
52
99
  if (ready) void openUrl(url).then(() => console.log(`✓ Opened ${url}`));
53
100
  });
54
101
  }