@elumixor/devkit 0.8.0 → 0.10.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.
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { cp, rename, rm } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { $ } from "bun";
5
+
6
+ /** A client-rendered web app and a Nitro API packed into one Vercel deployment. */
7
+ export interface WebBuildOptions {
8
+ /** Web app dir, run with `bun run build` (default `apps/frontend`). */
9
+ frontendDir?: string;
10
+ /** Nitro dir, built with `bunx nitro build --preset vercel` (default `apps/backend`). */
11
+ backendDir?: string;
12
+ /** Where the web build lands inside `frontendDir` (default `build`). */
13
+ webBuildDir?: string;
14
+ /** Path prefixes the API owns; everything else answers with the app shell. */
15
+ apiPrefixes: string[];
16
+ /** Extra staged directories to serve, as `{ "<source dir>": "<path under the site>" }`. */
17
+ include?: Record<string, string>;
18
+ }
19
+
20
+ /**
21
+ * Build a client-rendered web app and a Nitro API into a single Vercel deployment: the app as
22
+ * static files, the API as the one serverless function behind them. Both end up at the same
23
+ * origin, so the web client calls the API without CORS and there is one URL to remember.
24
+ */
25
+ export async function buildWeb(options: WebBuildOptions) {
26
+ const root = process.cwd();
27
+ const frontend = resolve(root, options.frontendDir ?? "apps/frontend");
28
+ const backend = resolve(root, options.backendDir ?? "apps/backend");
29
+ const webDir = join(backend, "public");
30
+ const nitroOutput = join(backend, ".vercel/output");
31
+ const finalOutput = join(root, ".vercel/output");
32
+
33
+ await $`bun run build`.cwd(frontend);
34
+ await rm(webDir, { recursive: true, force: true });
35
+ await cp(join(frontend, options.webBuildDir ?? "build"), webDir, { recursive: true });
36
+
37
+ // Anything a sibling platform staged for the site to hand out — an installer, say — rides along
38
+ // with the web files rather than living in the frontend's static folder, which other builds
39
+ // copy wholesale.
40
+ for (const [from, to] of Object.entries(options.include ?? {})) {
41
+ const staged = resolve(root, from);
42
+ if (!existsSync(staged)) {
43
+ console.log(`Nothing staged at ${from} — the site will serve no ${to}`);
44
+ continue;
45
+ }
46
+ await cp(staged, join(webDir, to), { recursive: true });
47
+ console.log(`Serving ${from} at /${to}`);
48
+ }
49
+
50
+ await rm(nitroOutput, { recursive: true, force: true });
51
+ await $`bunx nitro build --preset vercel`.cwd(backend);
52
+
53
+ await rm(finalOutput, { recursive: true, force: true });
54
+ await rename(nitroOutput, finalOutput);
55
+
56
+ await routeUnmatchedPathsToTheApp(finalOutput, options.apiPrefixes ?? []);
57
+ }
58
+
59
+ /**
60
+ * The app is one client-rendered bundle, so every path it owns has to answer with `index.html`
61
+ * and let the router sort it out. Nitro ends its routes with a catch-all into the function, which
62
+ * would otherwise answer an unknown web path with an API-shaped 404 JSON body.
63
+ */
64
+ async function routeUnmatchedPathsToTheApp(output: string, apiPrefixes: readonly string[]) {
65
+ if (!apiPrefixes.length) throw new Error('"apiPrefixes" must list the paths the API owns');
66
+
67
+ const configPath = join(output, "config.json");
68
+ const config = await Bun.file(configPath).json();
69
+ const staticDir = join(output, "static");
70
+ if (!existsSync(staticDir)) throw new Error(`No static output at ${staticDir} — did the web build land?`);
71
+
72
+ const catchAll = config.routes.findIndex((route: { dest?: string }) => route.dest === "/__fallback");
73
+ config.routes.splice(catchAll < 0 ? config.routes.length : catchAll, 0, {
74
+ src: `/((?!${apiPrefixes.join("|")}).*)`,
75
+ dest: "/index.html",
76
+ });
77
+
78
+ await Bun.write(configPath, JSON.stringify(config, null, 2));
79
+ console.log("Unmatched web paths route to the app shell");
80
+ }
@@ -0,0 +1,9 @@
1
+ import { type XcodeBuild, xcodeBuild } from "../apple.ts";
2
+
3
+ /**
4
+ * Compiles one Xcode scheme for a simulator — a watch app, a widget, anything native that carries
5
+ * no web bundle of its own and so needs nothing built before it.
6
+ */
7
+ export async function buildXcode(options: XcodeBuild) {
8
+ await xcodeBuild(options);
9
+ }
package/src/build.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { loadConfig } from "./config.ts";
2
+ import { type GraphOptions, runGraph } from "./graph.ts";
3
+
4
+ /** Build every configured platform at once, or only the ones named. */
5
+ export async function runBuild(only: string[], options: GraphOptions = {}) {
6
+ const { build, generate } = loadConfig();
7
+ await runGraph("build", build, only, generate, options);
8
+ }
package/src/config.ts CHANGED
@@ -1,24 +1,61 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
 
4
- /** One dev process, keyed by its name. Resolved into a shell command by {@link commandFor}. */
5
- export interface DevApp {
6
- /** Explicit `bun --filter <target>` (defaults to the name). */
4
+ /**
5
+ * The three things a repo does with its platforms, and the three commands that do them.
6
+ *
7
+ * Every phase is the same shape — a map of platform name to one step — so `devkit build` and
8
+ * `devkit build:mac` are the same command with a different selection, and a platform is named
9
+ * once and means the same thing everywhere.
10
+ */
11
+ export type Phase = "dev" | "build" | "deploy";
12
+
13
+ export const PHASES: readonly Phase[] = ["dev", "build", "deploy"];
14
+
15
+ /** One step of a phase: a shell command, or a built-in target named by `type`. */
16
+ export interface Step {
17
+ /** Shell command that performs this step. Omit when `type` names a built-in target instead. */
18
+ command?: string;
19
+ /** A built-in target — see `src/<phase>-targets/`. `options` is that target's own config. */
20
+ type?: string;
21
+ // biome-ignore lint/suspicious/noExplicitAny: each `type` has its own options shape
22
+ options?: any;
23
+ /** Platforms that must run first — built before this one, or already up in the dev case. */
24
+ needs?: string[];
25
+ /** Colour for this step's line on the board. */
26
+ color?: string;
27
+ }
28
+
29
+ /** One long-running dev process. Resolved into a shell command by `commandFor` in `dev.ts`. */
30
+ export interface DevProcess extends Step {
31
+ /** Explicit `bun --filter <target>` (defaults to the process name). */
7
32
  filter?: string;
8
- /** Run via `bun --cwd <cwd> run <script>` instead of `--filter`. */
33
+ /** Run via `bun run --cwd <cwd> <script>` instead of `--filter`. */
9
34
  cwd?: string;
10
35
  /** Script to run in the workspace (default `dev`). */
11
36
  script?: string;
12
- /** Raw shell command; overrides filter/cwd/script (e.g. `vite dev`). */
13
- command?: string;
14
37
  /** Port to free on start and show in the URL banner. */
15
38
  port?: number;
16
- /** Prefix color for this process's output. */
17
- color?: string;
18
- /** With `--open`, open this app's URL once its port is live. */
39
+ /** With `--open`, open this process's URL once its port is live. */
19
40
  open?: boolean;
20
41
  }
21
42
 
43
+ /**
44
+ * One platform's dev setup: either a single process, or several under `processes` — a web
45
+ * platform is a client and an API, and neither is worth naming as a platform of its own.
46
+ */
47
+ export interface DevPlatform extends DevProcess {
48
+ processes?: Record<string, DevProcess>;
49
+ }
50
+
51
+ /** A command run once before a build or deploy graph, ahead of everything running in parallel. */
52
+ export interface GenerateConfig {
53
+ /** Shell command to run (e.g. `bunx nitro-client`). */
54
+ command: string;
55
+ /** Directory to run it in, relative to the root (default `.`). */
56
+ cwd?: string;
57
+ }
58
+
22
59
  /** A gitignored env file that must be carried to a new machine, and the template listing its keys. */
23
60
  export interface EnvFile {
24
61
  /** Path to the env file, relative to the root (default `.env`). */
@@ -51,29 +88,30 @@ export interface SetupConfig {
51
88
  steps?: string[];
52
89
  }
53
90
 
54
- /**
55
- * One deploy step. Targets with no `needs` all start at once; a target with `needs` waits for
56
- * those, which is what lets a build that another one packages up run first without serialising
57
- * the whole release.
58
- */
59
- export interface DeployTarget {
60
- /** Shell command that performs this deploy. Omit when `type` names a built-in target instead. */
61
- command?: string;
62
- /** A built-in deploy target — see `src/deploy-targets/`. `options` is that target's own config. */
63
- type?: "vercel" | "tauri-macos" | "fastlane-ios";
64
- // biome-ignore lint/suspicious/noExplicitAny: each `type` has its own options shape
65
- options?: any;
66
- /** Targets that must finish first. */
67
- needs?: string[];
68
- /** Colour for this target's line on the board. */
69
- color?: string;
91
+ /** `devkit version`: one version, declared once and written everywhere else it appears. */
92
+ export interface VersionConfig {
93
+ /** JSON file whose `version` field is the number the rest follow. */
94
+ source: string;
95
+ /** `package.json`-shaped files. */
96
+ packages?: string[];
97
+ /** `Cargo.toml` files. */
98
+ cargo?: string[];
99
+ /** `project.pbxproj` files, whose `MARKETING_VERSION` every target's plist reads. */
100
+ xcodeProjects?: string[];
101
+ /** Plists of targets in those projects — pointed at `$(MARKETING_VERSION)` rather than a number. */
102
+ marketingVersionPlists?: string[];
103
+ /** Plists of targets with no project setting of their own, which carry the number itself. */
104
+ plists?: string[];
70
105
  }
71
106
 
72
- /** Apps and deploy targets are written as name-keyed maps, so a name is never repeated or missing. */
107
+ /** Phases are name-keyed maps, so a platform is never repeated or missing a name. */
73
108
  export interface DevkitConfig {
74
- apps?: Record<string, DevApp>;
109
+ dev?: Record<string, DevPlatform>;
110
+ build?: Record<string, Step>;
111
+ deploy?: Record<string, Step>;
112
+ generate?: GenerateConfig;
75
113
  setup?: SetupConfig;
76
- deploy?: Record<string, DeployTarget>;
114
+ version?: VersionConfig;
77
115
  }
78
116
 
79
117
  /** A config entry with its map key attached — the name every command prints and refers to. */
@@ -81,9 +119,12 @@ export type Named<T> = T & { readonly name: string };
81
119
 
82
120
  /** What the commands read: the same config, with each map flattened into named entries. */
83
121
  export interface LoadedConfig {
84
- apps: Named<DevApp>[];
122
+ dev: Named<DevPlatform>[];
123
+ build: Named<Step>[];
124
+ deploy: Named<Step>[];
125
+ generate?: GenerateConfig;
85
126
  setup?: SetupConfig;
86
- deploy: Named<DeployTarget>[];
127
+ version?: VersionConfig;
87
128
  }
88
129
 
89
130
  /** Read the `devkit` config from the nearest package.json. */
@@ -91,19 +132,56 @@ export function loadConfig(dir: string = process.cwd()): LoadedConfig {
91
132
  const pkgPath = resolve(dir, "package.json");
92
133
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { devkit?: DevkitConfig };
93
134
  const cfg = pkg.devkit;
94
- // `devkit deploy` is useful in a repo that runs nothing locally, so only the dev command
95
- // insists on apps.
135
+ // `devkit deploy` is useful in a repo that runs nothing locally, so no phase is required here —
136
+ // each command says what it needs when it finds nothing to run.
96
137
  if (!cfg) throw new Error(`No "devkit" config found in ${pkgPath}`);
97
138
  return {
98
- apps: named(cfg.apps, "apps", pkgPath),
99
- setup: cfg.setup,
139
+ dev: named(cfg.dev, "dev", pkgPath),
140
+ build: named(cfg.build, "build", pkgPath),
100
141
  deploy: named(cfg.deploy, "deploy", pkgPath),
142
+ generate: cfg.generate,
143
+ setup: cfg.setup,
144
+ version: cfg.version,
101
145
  };
102
146
  }
103
147
 
148
+ /** The entries of one phase, in config order. */
149
+ export function phaseOf(config: LoadedConfig, phase: Phase): Named<Step>[] {
150
+ return phase === "dev" ? config.dev : phase === "build" ? config.build : config.deploy;
151
+ }
152
+
104
153
  function named<T>(map: Record<string, T> | undefined, key: string, pkgPath: string): Named<T>[] {
105
154
  if (map === undefined) return [];
106
155
  if (Array.isArray(map))
107
156
  throw new Error(`"devkit.${key}" in ${pkgPath} is a list — it is now a map of name to settings`);
108
157
  return Object.entries(map).map(([name, entry]) => ({ ...entry, name }));
109
158
  }
159
+
160
+ /**
161
+ * The platforms asked for, plus whatever they depend on — a step can't run without its needs,
162
+ * and a dev process can't be developed against a stack that isn't up.
163
+ */
164
+ export function withNeeds<T extends Step>(entries: Named<T>[], only: string[]): Named<T>[] {
165
+ if (!only.length) return entries;
166
+ const unknown = only.filter((name) => !entries.some((entry) => entry.name === name));
167
+ if (unknown.length) {
168
+ const known = entries.map((entry) => entry.name).join(", ") || "none configured";
169
+ throw new Error(`Unknown platform${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")} (have: ${known})`);
170
+ }
171
+
172
+ const wanted = new Set(only);
173
+ let grew = true;
174
+ while (grew) {
175
+ grew = false;
176
+ for (const entry of entries) {
177
+ if (!wanted.has(entry.name)) continue;
178
+ for (const need of entry.needs ?? []) {
179
+ if (!wanted.has(need)) {
180
+ wanted.add(need);
181
+ grew = true;
182
+ }
183
+ }
184
+ }
185
+ }
186
+ return entries.filter((entry) => wanted.has(entry.name));
187
+ }
@@ -2,12 +2,11 @@ import { existsSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { $ } from "bun";
5
+ import { isolatedWebEnv } from "../web-build.ts";
5
6
 
6
7
  export interface FastlaneIosTargetOptions {
7
8
  /** Capacitor/frontend dir (default `apps/frontend`). */
8
9
  frontendDir?: string;
9
- /** Backend dir to generate a typed API client from before building, if any. */
10
- backendDir?: string;
11
10
  /** iOS project dir (default `<frontendDir>/ios`). */
12
11
  iosDir?: string;
13
12
  /** Fastlane lane to run (default `beta`). */
@@ -56,21 +55,10 @@ export async function deployFastlaneIos(options: FastlaneIosTargetOptions) {
56
55
  };
57
56
  if (!existsSync(keyPath)) throw new Error(`No App Store Connect key at ${keyPath}`);
58
57
 
59
- // Same order as a web deploy: the typed client is generated from the routes the app compiles
60
- // against. A `deploy` running every target generates it once up front, because two builds
61
- // writing those files at the same time is the one thing running in parallel can't survive.
62
- if (options.backendDir && !process.env.SKIP_CLIENT_GEN) await $`bunx nitro-client`.cwd(options.backendDir);
63
-
64
58
  // The web build a release ships to Vercel is happening in the next directory over, against the
65
59
  // same sources — this one gets its own output, cache and Capacitor web root so neither sees half
66
60
  // of the other's build.
67
- const buildEnv = {
68
- ...process.env,
69
- VITE_API_BASE_URL: apiBaseUrl,
70
- BUILD_DIR: "build-ios",
71
- KIT_DIR: ".svelte-kit-ios",
72
- VITE_CACHE_DIR: "node_modules/.vite-ios",
73
- };
61
+ const buildEnv = { ...process.env, VITE_API_BASE_URL: apiBaseUrl, ...isolatedWebEnv("ios") };
74
62
  await $`bun run build`.cwd(frontendDir).env(buildEnv);
75
63
  await $`bunx cap sync ios`.cwd(frontendDir).env(buildEnv);
76
64
 
package/src/deploy.ts CHANGED
@@ -1,258 +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) throw new Error(`${target.name} needs unknown target${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}`);
62
- if (!target.command && !target.type) throw new Error(`${target.name} needs a "command" or a "type"`);
63
- }
64
-
65
- const jobs = selected(deploy, only).map(toJob);
66
- if (options.dry) return printPlan(jobs);
67
-
68
- const logDir = resolve(process.cwd(), ".devkit/deploy");
69
- mkdirSync(logDir, { recursive: true });
70
-
71
- const live = Boolean(process.stdout.isTTY) && !options.verbose;
72
- console.log(bold(`\ndeploying ${jobs.map((job) => job.label).join(", ")}`) + dim(live ? ` · logs in ${"./.devkit/deploy"}` : ""));
73
- console.log();
74
- const board = live ? startBoard(jobs) : null;
75
-
76
- // Each target waits on the gates of the targets it needs, so the graph runs itself: independent
77
- // targets start together, dependents start the moment their last dependency lands.
78
- const gates = new Map(jobs.map((job) => [job.label, gate()]));
79
-
80
- const started = Date.now();
81
- await Promise.all(
82
- jobs.map(async (job) => {
83
- const needs = (job.target.needs ?? []).map((name) => jobs.find((other) => other.label === name)) as Job[];
84
- await Promise.all(needs.map((need) => gates.get(need.label)?.promise));
85
- await runJob(job, needs, live);
86
- gates.get(job.label)?.open();
87
- }),
88
- );
89
- board?.stop();
90
-
91
- report(jobs, Date.now() - started);
92
- if (jobs.some((job) => job.status !== "done")) process.exitCode = 1;
93
- }
94
-
95
- /** The targets asked for, plus whatever they depend on — a target can't run without its needs. */
96
- function selected(targets: Named<DeployTarget>[], only: string[]) {
97
- if (!only.length) return targets;
98
- const wanted = new Set(only);
99
- let grew = true;
100
- while (grew) {
101
- grew = false;
102
- for (const target of targets) {
103
- if (!wanted.has(target.name)) continue;
104
- for (const need of target.needs ?? []) {
105
- if (!wanted.has(need)) {
106
- wanted.add(need);
107
- grew = true;
108
- }
109
- }
110
- }
111
- }
112
- 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);
113
8
  }
114
-
115
- function toJob(target: Named<DeployTarget>, index: number): Job {
116
- // A built-in target has no shell command of its own — it runs through `devkit _deploy-target`,
117
- // which looks its options back up from this same config by name.
118
- const command = target.command ?? `devkit _deploy-target ${JSON.stringify(target.name)}`;
119
- return {
120
- target: { ...target, command },
121
- label: target.name,
122
- color: target.color ?? (PALETTE[index % PALETTE.length] as string),
123
- status: "waiting",
124
- note: target.needs?.length ? `waiting for ${target.needs.join(", ")}` : "",
125
- lines: [],
126
- logPath: resolve(process.cwd(), ".devkit/deploy", `${target.name}.log`),
127
- };
128
- }
129
-
130
- /** Runs one target's command to completion, unless something it needed didn't get there. */
131
- async function runJob(job: Job, needs: Job[], live: boolean) {
132
- const blocker = needs.find((need) => need.status !== "done");
133
- if (blocker) {
134
- job.status = "skipped";
135
- job.note = `skipped — ${blocker.label} ${blocker.status === "failed" ? "failed" : "never ran"}`;
136
- return;
137
- }
138
-
139
- job.status = "running";
140
- job.startedAt = Date.now();
141
- job.note = job.target.command;
142
-
143
- const code = await new Promise<number>((done) => {
144
- const child = spawn(job.target.command, { shell: true, stdio: ["ignore", "pipe", "pipe"] });
145
- for (const stream of [child.stdout, child.stderr]) {
146
- let rest = "";
147
- stream.on("data", (chunk: Buffer) => {
148
- const parts = (rest + chunk.toString()).split("\n");
149
- rest = parts.pop() ?? "";
150
- for (const line of parts) {
151
- job.lines.push(line);
152
- job.note = line.trim() || job.note;
153
- if (!live) console.log(`${paint(`[${job.label}]`, job.color)} ${line}`);
154
- }
155
- });
156
- }
157
- child.on("close", (status) => done(status ?? 1));
158
- });
159
-
160
- job.endedAt = Date.now();
161
- job.status = code === 0 ? "done" : "failed";
162
- job.note = code === 0 ? "done" : `exit ${code}`;
163
- writeFileSync(job.logPath, `${job.lines.join("\n")}\n`);
164
- }
165
-
166
- /** Redraws the board until stopped. One line per target, in the order they were configured. */
167
- function startBoard(jobs: Job[]) {
168
- let drawn = 0;
169
- let frame = 0;
170
-
171
- const draw = () => {
172
- // A pty with no window size reports 0 — treat that as a sane default rather than clipping to nothing.
173
- const width = process.stdout.columns || 100;
174
- const pad = Math.max(...jobs.map((job) => job.label.length));
175
- const lines = jobs.map((job) => {
176
- const mark =
177
- job.status === "running"
178
- ? paint(SPINNER[frame % SPINNER.length] as string, job.color)
179
- : job.status === "done"
180
- ? paint("✓", "green")
181
- : job.status === "failed"
182
- ? paint("✗", "red")
183
- : job.status === "skipped"
184
- ? dim("–")
185
- : dim("·");
186
- const time = job.startedAt ? dim(` ${elapsed(job)}`) : "";
187
- const head = `${mark} ${paint(job.label.padEnd(pad), job.color)}${time} `;
188
- // The note is whatever the target last printed, so it has to be cut to the terminal rather
189
- // than wrapped — a wrapped line breaks the cursor arithmetic that redraws this block.
190
- const room = Math.max(10, width - visibleLength(head) - 1);
191
- return head + dim(clip(job.note, room));
192
- });
193
-
194
- process.stdout.write(`${drawn ? `\x1b[${drawn}A` : ""}${lines.map((line) => `\x1b[2K${line}`).join("\n")}\n`);
195
- drawn = lines.length;
196
- frame++;
197
- };
198
-
199
- process.stdout.write("\x1b[?25l");
200
- draw();
201
- const timer = setInterval(draw, FRAME_MS);
202
-
203
- return {
204
- stop() {
205
- clearInterval(timer);
206
- draw();
207
- process.stdout.write("\x1b[?25h");
208
- },
209
- };
210
- }
211
-
212
- function report(jobs: Job[], total: number) {
213
- const failed = jobs.filter((job) => job.status === "failed");
214
- for (const job of failed) {
215
- console.log(`\n${paint(`── ${job.label} failed`, "red")} ${dim(job.logPath)}`);
216
- for (const line of job.lines.slice(-TAIL_ON_FAILURE)) console.log(dim(` ${line}`));
217
- }
218
-
219
- const done = jobs.filter((job) => job.status === "done").length;
220
- const skipped = jobs.filter((job) => job.status === "skipped").length;
221
- const parts = [
222
- failed.length ? paint(`${failed.length} failed`, "red") : paint("all good", "green"),
223
- skipped ? dim(`${skipped} skipped`) : "",
224
- dim(duration(total)),
225
- ].filter(Boolean);
226
- console.log(`\n${bold(`${done}/${jobs.length} deployed`)} · ${parts.join(" · ")}\n`);
227
- }
228
-
229
- function printPlan(jobs: Job[]) {
230
- console.log(bold("\ndeploy plan\n"));
231
- for (const job of jobs) {
232
- const after = job.target.needs?.length ? dim(` after ${job.target.needs.join(", ")}`) : "";
233
- console.log(` ${paint(job.label, job.color)}${after}\n ${dim(job.target.command)}`);
234
- }
235
- console.log();
236
- }
237
-
238
- /** A promise plus the handle that settles it — one per target, opened when that target ends. */
239
- function gate() {
240
- let open!: () => void;
241
- const promise = new Promise<void>((resolve) => {
242
- open = resolve;
243
- });
244
- return { promise, open };
245
- }
246
-
247
- const elapsed = (job: Job) => duration((job.endedAt ?? Date.now()) - (job.startedAt ?? Date.now()));
248
-
249
- function duration(ms: number) {
250
- const seconds = Math.round(ms / 1000);
251
- return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, "0")}s`;
252
- }
253
-
254
- // Colour codes take no space on screen, so the board has to measure what a reader would see.
255
- // biome-ignore lint/suspicious/noControlCharactersInRegex: an escape sequence is the thing being matched
256
- const ANSI = /\x1b\[[0-9;]*m/g;
257
- const visibleLength = (text: string) => text.replace(ANSI, "").length;
258
- 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
+ }