@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,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
  }
package/src/graph.ts ADDED
@@ -0,0 +1,258 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { $ } from "bun";
5
+ import { type GenerateConfig, type Named, type Phase, type Step, withNeeds } from "./config.ts";
6
+
7
+ const PALETTE: readonly string[] = ["magenta", "cyan", "yellow", "green", "blue", "red"];
8
+ const COLORS: Record<string, string> = {
9
+ black: "30",
10
+ red: "31",
11
+ green: "32",
12
+ yellow: "33",
13
+ blue: "34",
14
+ magenta: "35",
15
+ cyan: "36",
16
+ white: "37",
17
+ gray: "90",
18
+ };
19
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
20
+ const FRAME_MS = 80;
21
+ const TAIL_ON_FAILURE = 25;
22
+
23
+ const paint = (text: string, color: string) => `\x1b[${COLORS[color] ?? "37"}m${text}\x1b[0m`;
24
+ const dim = (text: string) => `\x1b[2m${text}\x1b[0m`;
25
+ const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
26
+
27
+ type Status = "waiting" | "running" | "done" | "failed" | "skipped";
28
+
29
+ /** One step's progress, and everything the board needs to draw its line. */
30
+ interface Job {
31
+ target: Named<Step> & { command: string };
32
+ label: string;
33
+ color: string;
34
+ status: Status;
35
+ note: string;
36
+ startedAt?: number;
37
+ endedAt?: number;
38
+ lines: string[];
39
+ logPath: string;
40
+ }
41
+
42
+ export interface GraphOptions {
43
+ dry?: boolean;
44
+ verbose?: boolean;
45
+ }
46
+
47
+ /**
48
+ * Run one phase's steps, in parallel where they don't depend on each other.
49
+ *
50
+ * A build or a deploy is several long compiles that each print thousands of lines, and
51
+ * interleaving all of it is unreadable — so on a terminal this draws one line per platform (what
52
+ * it's doing, for how long) and keeps the full output in `.devkit/<phase>/<name>.log`, printing
53
+ * the tail of whichever one failed. Anywhere else — CI, a pipe, a log file — it falls back to
54
+ * prefixed streaming, because a redrawing board in a file is worse than useless.
55
+ */
56
+ export async function runGraph(
57
+ phase: Exclude<Phase, "dev">,
58
+ targets: Named<Step>[],
59
+ only: string[],
60
+ generate: GenerateConfig | undefined,
61
+ options: GraphOptions = {},
62
+ ) {
63
+ if (!targets.length) throw new Error(`No "devkit.${phase}" platforms in package.json`);
64
+
65
+ for (const target of targets) {
66
+ const missing = (target.needs ?? []).filter((need) => !targets.some((other) => other.name === need));
67
+ if (missing.length)
68
+ throw new Error(`${target.name} needs unknown platform${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}`);
69
+ if (!target.command && !target.type) throw new Error(`${target.name} needs a "command" or a "type"`);
70
+ }
71
+
72
+ const jobs = withNeeds(targets, only).map((target, index) => toJob(phase, target, index));
73
+ if (options.dry) return printPlan(phase, jobs, generate);
74
+
75
+ const logDir = resolve(process.cwd(), ".devkit", phase);
76
+ mkdirSync(logDir, { recursive: true });
77
+
78
+ const live = Boolean(process.stdout.isTTY) && !options.verbose;
79
+ console.log(
80
+ bold(`\n${phase}ing ${jobs.map((job) => job.label).join(", ")}`) +
81
+ dim(live ? ` · logs in ./.devkit/${phase}` : ""),
82
+ );
83
+
84
+ // Generated sources — a typed API client, say — are read by every platform's compile, so they
85
+ // are written once here rather than by each of them at the same time as the others read them.
86
+ if (generate) {
87
+ console.log(dim(` ${generate.command}`));
88
+ await $`sh -c ${generate.command}`.cwd(resolve(process.cwd(), generate.cwd ?? "."));
89
+ process.env.SKIP_CLIENT_GEN = "1";
90
+ }
91
+
92
+ console.log();
93
+ const board = live ? startBoard(jobs) : null;
94
+
95
+ // Each step waits on the gates of the steps it needs, so the graph runs itself: independent
96
+ // platforms start together, dependents start the moment their last dependency lands.
97
+ const gates = new Map(jobs.map((job) => [job.label, gate()]));
98
+
99
+ const started = Date.now();
100
+ await Promise.all(
101
+ jobs.map(async (job) => {
102
+ const needs = (job.target.needs ?? []).map((name) => jobs.find((other) => other.label === name)) as Job[];
103
+ await Promise.all(needs.map((need) => gates.get(need.label)?.promise));
104
+ await runJob(job, needs, live);
105
+ gates.get(job.label)?.open();
106
+ }),
107
+ );
108
+ board?.stop();
109
+
110
+ report(phase, jobs, Date.now() - started);
111
+ if (jobs.some((job) => job.status !== "done")) process.exitCode = 1;
112
+ }
113
+
114
+ function toJob(phase: Phase, target: Named<Step>, index: number): Job {
115
+ // A built-in target has no shell command of its own — it runs through `devkit _run`, which
116
+ // looks its options back up from this same config by phase and name.
117
+ const command = target.command ?? `devkit _run ${phase} ${JSON.stringify(target.name)}`;
118
+ return {
119
+ target: { ...target, command },
120
+ label: target.name,
121
+ color: target.color ?? (PALETTE[index % PALETTE.length] as string),
122
+ status: "waiting",
123
+ note: target.needs?.length ? `waiting for ${target.needs.join(", ")}` : "",
124
+ lines: [],
125
+ logPath: resolve(process.cwd(), ".devkit", phase, `${target.name}.log`),
126
+ };
127
+ }
128
+
129
+ /** Runs one step's command to completion, unless something it needed didn't get there. */
130
+ async function runJob(job: Job, needs: Job[], live: boolean) {
131
+ const blocker = needs.find((need) => need.status !== "done");
132
+ if (blocker) {
133
+ job.status = "skipped";
134
+ job.note = `skipped — ${blocker.label} ${blocker.status === "failed" ? "failed" : "never ran"}`;
135
+ return;
136
+ }
137
+
138
+ job.status = "running";
139
+ job.startedAt = Date.now();
140
+ job.note = job.target.command;
141
+
142
+ const code = await new Promise<number>((done) => {
143
+ const child = spawn(job.target.command, { shell: true, stdio: ["ignore", "pipe", "pipe"] });
144
+ for (const stream of [child.stdout, child.stderr]) {
145
+ let rest = "";
146
+ stream.on("data", (chunk: Buffer) => {
147
+ const parts = (rest + chunk.toString()).split("\n");
148
+ rest = parts.pop() ?? "";
149
+ for (const line of parts) {
150
+ job.lines.push(line);
151
+ job.note = line.trim() || job.note;
152
+ if (!live) console.log(`${paint(`[${job.label}]`, job.color)} ${line}`);
153
+ }
154
+ });
155
+ }
156
+ child.on("close", (status) => done(status ?? 1));
157
+ });
158
+
159
+ job.endedAt = Date.now();
160
+ job.status = code === 0 ? "done" : "failed";
161
+ job.note = code === 0 ? "done" : `exit ${code}`;
162
+ writeFileSync(job.logPath, `${job.lines.join("\n")}\n`);
163
+ }
164
+
165
+ /** Redraws the board until stopped. One line per platform, in the order they were configured. */
166
+ function startBoard(jobs: Job[]) {
167
+ let drawn = 0;
168
+ let frame = 0;
169
+
170
+ const draw = () => {
171
+ // A pty with no window size reports 0 — treat that as a sane default rather than clipping to nothing.
172
+ const width = process.stdout.columns || 100;
173
+ const pad = Math.max(...jobs.map((job) => job.label.length));
174
+ const lines = jobs.map((job) => {
175
+ const mark =
176
+ job.status === "running"
177
+ ? paint(SPINNER[frame % SPINNER.length] as string, job.color)
178
+ : job.status === "done"
179
+ ? paint("✓", "green")
180
+ : job.status === "failed"
181
+ ? paint("✗", "red")
182
+ : job.status === "skipped"
183
+ ? dim("–")
184
+ : dim("·");
185
+ const time = job.startedAt ? dim(` ${elapsed(job)}`) : "";
186
+ const head = `${mark} ${paint(job.label.padEnd(pad), job.color)}${time} `;
187
+ // The note is whatever the step last printed, so it has to be cut to the terminal rather
188
+ // than wrapped — a wrapped line breaks the cursor arithmetic that redraws this block.
189
+ const room = Math.max(10, width - visibleLength(head) - 1);
190
+ return head + dim(clip(job.note, room));
191
+ });
192
+
193
+ process.stdout.write(`${drawn ? `\x1b[${drawn}A` : ""}${lines.map((line) => `\x1b[2K${line}`).join("\n")}\n`);
194
+ drawn = lines.length;
195
+ frame++;
196
+ };
197
+
198
+ process.stdout.write("\x1b[?25l");
199
+ draw();
200
+ const timer = setInterval(draw, FRAME_MS);
201
+
202
+ return {
203
+ stop() {
204
+ clearInterval(timer);
205
+ draw();
206
+ process.stdout.write("\x1b[?25h");
207
+ },
208
+ };
209
+ }
210
+
211
+ function report(phase: Phase, jobs: Job[], total: number) {
212
+ const failed = jobs.filter((job) => job.status === "failed");
213
+ for (const job of failed) {
214
+ console.log(`\n${paint(`── ${job.label} failed`, "red")} ${dim(job.logPath)}`);
215
+ for (const line of job.lines.slice(-TAIL_ON_FAILURE)) console.log(dim(` ${line}`));
216
+ }
217
+
218
+ const done = jobs.filter((job) => job.status === "done").length;
219
+ const skipped = jobs.filter((job) => job.status === "skipped").length;
220
+ const parts = [
221
+ failed.length ? paint(`${failed.length} failed`, "red") : paint("all good", "green"),
222
+ skipped ? dim(`${skipped} skipped`) : "",
223
+ dim(duration(total)),
224
+ ].filter(Boolean);
225
+ console.log(`\n${bold(`${done}/${jobs.length} ${phase === "build" ? "built" : "deployed"}`)} · ${parts.join(" · ")}\n`);
226
+ }
227
+
228
+ function printPlan(phase: Phase, jobs: Job[], generate: GenerateConfig | undefined) {
229
+ console.log(bold(`\n${phase} plan\n`));
230
+ if (generate) console.log(` ${paint("generate", "gray")}\n ${dim(generate.command)}`);
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 step, opened when that step 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)}…`);
package/src/release.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { $ } from "bun";
2
+
3
+ /**
4
+ * Tag the current commit and push the tag, which is how a CI release is asked for: `ios` becomes
5
+ * `ios-v20260820203000`. The timestamp is what keeps two releases of the same commit apart.
6
+ */
7
+ export async function runRelease(prefix: string) {
8
+ if (!prefix) throw new Error("usage: devkit release <prefix>");
9
+
10
+ const now = new Date();
11
+ const stamp = [
12
+ now.getFullYear(),
13
+ now.getMonth() + 1,
14
+ now.getDate(),
15
+ now.getHours(),
16
+ now.getMinutes(),
17
+ now.getSeconds(),
18
+ ]
19
+ .map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0"))
20
+ .join("");
21
+
22
+ const tag = `${prefix}-v${stamp}`;
23
+ await $`git tag ${tag}`;
24
+ await $`git push origin ${tag}`;
25
+ console.log(`Pushed ${tag}`);
26
+ }
@@ -0,0 +1,64 @@
1
+ import { buildCapacitorIos } from "./build-targets/capacitor-ios.ts";
2
+ import { buildTauriMacos } from "./build-targets/tauri-macos.ts";
3
+ import { buildWeb } from "./build-targets/web.ts";
4
+ import { buildXcode } from "./build-targets/xcode.ts";
5
+ import { loadConfig, type Phase, phaseOf } from "./config.ts";
6
+ import { deployFastlaneIos } from "./deploy-targets/fastlane-ios.ts";
7
+ import { deployTauriMacos } from "./deploy-targets/tauri-macos.ts";
8
+ import { deployVercel } from "./deploy-targets/vercel.ts";
9
+ import { devCapacitorIos } from "./dev-targets/capacitor-ios.ts";
10
+ import { devXcodeSim } from "./dev-targets/xcode-sim.ts";
11
+
12
+ /** Flags a dev target may be given from the command line, passed straight through to it. */
13
+ export interface TargetFlags {
14
+ real?: boolean;
15
+ device?: string;
16
+ }
17
+
18
+ // biome-ignore lint/suspicious/noExplicitAny: each target validates its own options shape
19
+ type Target = (options: any, flags: TargetFlags) => Promise<void>;
20
+
21
+ /**
22
+ * What a `type` in the config means, per phase.
23
+ *
24
+ * The same word means different things in different phases on purpose: `capacitor-ios` builds the
25
+ * iPhone app when a build asks for it, runs it against the dev server when dev does, and ships it
26
+ * to TestFlight when a deploy does. The platform is the name; the phase says what to do with it.
27
+ */
28
+ const TARGETS: Record<Phase, Record<string, Target>> = {
29
+ dev: {
30
+ "capacitor-ios": devCapacitorIos,
31
+ "xcode-sim": devXcodeSim,
32
+ },
33
+ build: {
34
+ web: buildWeb,
35
+ "tauri-macos": buildTauriMacos,
36
+ "capacitor-ios": buildCapacitorIos,
37
+ xcode: buildXcode,
38
+ },
39
+ deploy: {
40
+ vercel: deployVercel,
41
+ "tauri-macos": deployTauriMacos,
42
+ "fastlane-ios": deployFastlaneIos,
43
+ },
44
+ };
45
+
46
+ /**
47
+ * Runs one built-in target, looked back up by phase and platform name.
48
+ *
49
+ * A typed step has no shell command of its own, so the graph (and `concurrently`, for dev) spawns
50
+ * `devkit _run <phase> <platform>` and this reads the same config back — which keeps every step a
51
+ * process of its own, with its own log file and its own line on the board.
52
+ */
53
+ export async function runTarget(phase: Phase, name: string, flags: TargetFlags = {}) {
54
+ const step = phaseOf(loadConfig(), phase).find((entry) => entry.name === name);
55
+ if (!step) throw new Error(`No "devkit.${phase}.${name}" in package.json`);
56
+ if (!step.type) throw new Error(`"devkit.${phase}.${name}" has no "type"`);
57
+
58
+ const target = TARGETS[phase][step.type];
59
+ if (!target) {
60
+ const known = Object.keys(TARGETS[phase]).join(", ");
61
+ throw new Error(`Unknown ${phase} type "${step.type}" — known types: ${known}`);
62
+ }
63
+ await target(step.options ?? {}, flags);
64
+ }
package/src/version.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { resolve } from "node:path";
2
+ import { loadConfig } from "./config.ts";
3
+
4
+ /**
5
+ * One version for the whole product. A single file holds it — the one the app already reads its
6
+ * version from at build time — and this writes that number everywhere else a version is declared,
7
+ * so the App Store, the installer and the line at the bottom of settings can't drift apart.
8
+ */
9
+ export async function runVersion() {
10
+ const { version: config } = loadConfig();
11
+ if (!config) throw new Error('No "devkit.version" config in package.json');
12
+
13
+ const root = process.cwd();
14
+ const sourcePath = resolve(root, config.source);
15
+ const version = (await Bun.file(sourcePath).json()).version as string | undefined;
16
+ if (!version || !/^\d+\.\d+\.\d+$/.test(version))
17
+ throw new Error(`${sourcePath} has no plain x.y.z version: ${version}`);
18
+
19
+ const path = (file: string) => resolve(root, file);
20
+
21
+ await Promise.all([
22
+ ...(config.packages ?? []).map((file) => edit(path(file), /("version":\s*")[^"]+/, version)),
23
+ ...(config.cargo ?? []).map((file) => edit(path(file), /(^version = ")[^"]+/m, version)),
24
+ // The Xcode project is the only place the iOS marketing version is written: each Info.plist
25
+ // that belongs to a target reads `$(MARKETING_VERSION)` from it.
26
+ ...(config.xcodeProjects ?? []).map((file) => edit(path(file), /(MARKETING_VERSION = )[^;]+/g, version)),
27
+ ...(config.marketingVersionPlists ?? []).map((file) => edit(path(file), SHORT_VERSION, "$(MARKETING_VERSION)")),
28
+ // Targets wired into a project by a script rather than by Xcode's template have no
29
+ // `MARKETING_VERSION` setting of their own, so their plists carry the number itself.
30
+ ...(config.plists ?? []).map((file) => edit(path(file), SHORT_VERSION, version)),
31
+ ]);
32
+
33
+ console.log(`Version ${version} across every declared file`);
34
+ }
35
+
36
+ const SHORT_VERSION = /(<key>CFBundleShortVersionString<\/key>\s*<string>)[^<]+/;
37
+
38
+ /** Rewrites the part of `pattern` after its first capture group, leaving the rest of the file alone. */
39
+ async function edit(path: string, pattern: RegExp, value: string) {
40
+ const before = await Bun.file(path).text();
41
+ const after = before.replace(pattern, (_, prefix) => `${prefix}${value}`);
42
+ if (after !== before) await Bun.write(path, after);
43
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Every native shell carries its own copy of the web app, built with its own API base URL — and
3
+ * `devkit build` runs those builds beside each other. Vite, SvelteKit and the output directory all
4
+ * default to one place per project, so each build is given its own or they overwrite each other's
5
+ * files halfway through.
6
+ */
7
+ export function isolatedWebEnv(suffix: string): Record<string, string> {
8
+ return {
9
+ BUILD_DIR: `build-${suffix}`,
10
+ KIT_DIR: `.svelte-kit-${suffix}`,
11
+ VITE_CACHE_DIR: `node_modules/.vite-${suffix}`,
12
+ };
13
+ }