@elumixor/devkit 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,25 +19,24 @@ Add a `devkit` block to your root `package.json`:
19
19
  "dev:open": "devkit --open"
20
20
  },
21
21
  "devkit": {
22
- "apps": [
23
- { "name": "backend", "port": 10000, "color": "blue" },
24
- { "name": "frontend", "port": 3000, "color": "magenta", "open": true }
25
- ]
22
+ "apps": {
23
+ "backend": { "port": 10000 },
24
+ "frontend": { "port": 3000, "open": true }
25
+ }
26
26
  }
27
27
  }
28
28
  ```
29
29
 
30
- Each app runs `bun --filter <name> dev` by default. Override with:
30
+ Each app is keyed by its name, and runs `bun --filter <name> dev` by default. Override with:
31
31
 
32
32
  | field | meaning |
33
33
  | --------- | ----------------------------------------------------------------- |
34
- | `name` | display label + default `bun --filter` target |
35
- | `filter` | explicit `bun --filter <target>` (defaults to `name`) |
34
+ | `filter` | explicit `bun --filter <target>` (defaults to the name) |
36
35
  | `cwd` | run `bun --cwd <cwd> run <script>` instead of `--filter` |
37
36
  | `script` | script to run in the workspace (default `dev`) |
38
37
  | `command` | raw shell command, overrides the above (e.g. `vite dev`) |
39
38
  | `port` | freed on start and shown in the URL banner |
40
- | `color` | prefix color (blue, magenta, green, yellow, cyan, red) |
39
+ | `color` | prefix color (blue, magenta, green, yellow, cyan, red); one is picked for you otherwise |
41
40
  | `open` | with `--open`, open this app's URL when its port comes up |
42
41
 
43
42
  ## Deploy
@@ -49,11 +48,11 @@ side by side, with one line each.
49
48
  {
50
49
  "scripts": { "deploy": "devkit deploy" },
51
50
  "devkit": {
52
- "deploy": [
53
- { "name": "desktop", "command": "bun scripts/deploy-desktop.ts", "color": "yellow" },
54
- { "name": "vercel", "command": "bun scripts/deploy-vercel.ts", "needs": ["desktop"] },
55
- { "name": "ios", "command": "bun scripts/deploy-ios.ts" }
56
- ]
51
+ "deploy": {
52
+ "desktop": { "command": "bun scripts/deploy-desktop.ts" },
53
+ "vercel": { "command": "bun scripts/deploy-vercel.ts", "needs": ["desktop"] },
54
+ "ios": { "command": "bun scripts/deploy-ios.ts" }
55
+ }
57
56
  }
58
57
  }
59
58
  ```
@@ -73,12 +72,88 @@ output goes to `.devkit/deploy/<name>.log`, and the tail of whichever target fai
73
72
  the end — a release prints tens of thousands of lines, and interleaving all of them is unreadable.
74
73
  Piped output (CI, a log file) gets prefixed streaming lines instead of the board.
75
74
 
75
+ Each target is keyed by its name — that is what the board shows, what `needs` points at, and what
76
+ you type on the command line.
77
+
76
78
  | field | meaning |
77
79
  | --------- | -------------------------------------------------- |
78
- | `name` | display name, and how it's named on the command line |
79
80
  | `command` | shell command that performs this deploy |
80
81
  | `needs` | targets that must finish first |
81
- | `color` | colour of this target's line |
82
+ | `color` | colour of this target's line; one is picked for you otherwise |
83
+
84
+ ## Build
85
+
86
+ `devkit build` packs a client-rendered web app and a Nitro API into one Vercel deployment: the app
87
+ as static files, the API as the one serverless function behind them. Same origin, so the web client
88
+ calls the API without CORS.
89
+
90
+ ```jsonc
91
+ "devkit": {
92
+ "build": {
93
+ "frontendDir": "apps/frontend",
94
+ "backendDir": "apps/backend",
95
+ "apiPrefixes": ["mobile", "health"],
96
+ "clientCommand": "bunx nitro-client",
97
+ "include": { "dist/download": "download" }
98
+ }
99
+ }
100
+ ```
101
+
102
+ | key | meaning |
103
+ | --------------- | ------------------------------------------------------------------------------ |
104
+ | `frontendDir` | web app dir, run with `bun run build` (default `apps/frontend`) |
105
+ | `backendDir` | Nitro dir (default `apps/backend`) |
106
+ | `webBuildDir` | where the web build lands inside `frontendDir` (default `build`) |
107
+ | `apiPrefixes` | paths the API owns; every other path answers with the app shell |
108
+ | `clientCommand` | run in `backendDir` first, unless `SKIP_CLIENT_GEN` is set |
109
+ | `include` | staged dirs to serve alongside the web files, as `{ "<source>": "<url path>" }` |
110
+
111
+ ## Versions
112
+
113
+ `devkit version` reads one version and writes it into every other file that declares one, so the
114
+ App Store, the installer and the number at the bottom of settings can't drift apart.
115
+
116
+ ```jsonc
117
+ "devkit": {
118
+ "version": {
119
+ "source": "apps/frontend/src-tauri/tauri.conf.json",
120
+ "packages": ["package.json", "apps/frontend/package.json"],
121
+ "cargo": ["apps/frontend/src-tauri/Cargo.toml"],
122
+ "xcodeProjects": ["apps/frontend/ios/App/App.xcodeproj/project.pbxproj"],
123
+ "marketingVersionPlists": ["apps/frontend/ios/App/App/Info.plist"],
124
+ "plists": ["apps/frontend/ios/App/WatchApp/Info.plist"]
125
+ }
126
+ }
127
+ ```
128
+
129
+ Targets in an Xcode project read `$(MARKETING_VERSION)` from the project, so their plists are
130
+ pointed at it rather than at a number — `plists` is for targets wired in by a script, which have no
131
+ such setting and carry the number themselves.
132
+
133
+ `devkit release <prefix>` tags the current commit `<prefix>-v<timestamp>` and pushes the tag, which
134
+ is how a CI release is asked for.
135
+
136
+ ## Simulator
137
+
138
+ `devkit sim` builds an Apple target and launches it on a simulator without opening Xcode. A watch
139
+ app has no sign-in of its own, so `previewEnv` is what lets it run on a simulator with no paired
140
+ phone; `--real` leaves it unset and talks to the real API.
141
+
142
+ ```jsonc
143
+ "devkit": {
144
+ "sim": {
145
+ "project": "apps/frontend/ios/App/App.xcodeproj",
146
+ "scheme": "BalanceWatch",
147
+ "bundleId": "com.example.app.watchkitapp",
148
+ "device": "Apple Watch Series 11 (46mm)",
149
+ "previewEnv": "BALANCE_WATCH_PREVIEW"
150
+ }
151
+ }
152
+ ```
153
+
154
+ `--device`, or `DEVKIT_SIM_DEVICE`, overrides the configured simulator — everyone's list of
155
+ installed ones differs. `sdk` (default `watchsimulator`) and `derivedDataDir` (default `build/sim`)
156
+ are there for a phone target.
82
157
 
83
158
  ## Setting up a machine
84
159
 
@@ -97,7 +172,7 @@ Declare what to sync and what to run:
97
172
 
98
173
  ```jsonc
99
174
  "devkit": {
100
- "apps": [ /* ... */ ],
175
+ "apps": { /* ... */ },
101
176
  "setup": {
102
177
  "secrets": [".env", "infra/terraform.tfvars"],
103
178
  "env": [{ "file": ".env", "example": ".env.example" }],
@@ -136,5 +211,10 @@ Changed a `.env`? Run `devkit secrets push`, or the next machine gets a stale co
136
211
  - `devkit [root] [--open] [--dry] [--version]` — the orchestrator above. `root` is an optional path to the folder holding the `devkit` config (defaults to the current directory); `--dry` prints the resolved commands and URLs without running anything.
137
212
  - `devkit clone <owner/repo> [dir]` — clone, decrypt secrets, run setup.
138
213
  - `devkit setup [root] [--dry]` — validate secrets, install, `terraform init`, run steps.
214
+ - `devkit deploy [targets...] [--dry] [--verbose]` — run the release targets, in parallel.
215
+ - `devkit build` — build the web app and the API into one Vercel output.
216
+ - `devkit sim [--real] [--device <name>]` — build and launch the app on a simulator.
217
+ - `devkit version` — write the source version into every file that declares one.
218
+ - `devkit release <prefix>` — tag this commit `<prefix>-v<timestamp>` and push it.
139
219
  - `devkit secrets push|pull [root]` — sync the encrypted secrets.
140
220
  - `free-port <port>` — kill whatever is listening on a port (handy in a `predev`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elumixor/devkit",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Dev orchestrator for bun monorepos — free ports, run apps side-by-side, open the browser when ready",
5
5
  "author": "elumixor",
6
6
  "license": "ISC",
package/src/bin/devkit.ts CHANGED
@@ -1,20 +1,26 @@
1
1
  #!/usr/bin/env bun
2
- import { parseArgs } from "node:util";
3
2
  import { resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import pkg from "../../package.json" with { type: "json" };
5
+ import { runBuild } from "../build.ts";
6
+ import { runClone } from "../clone.ts";
4
7
  import { loadConfig } from "../config.ts";
5
8
  import { runDeploy } from "../deploy.ts";
6
9
  import { deployFastlaneIos } from "../deploy-targets/fastlane-ios.ts";
7
10
  import { deployTauriMacos } from "../deploy-targets/tauri-macos.ts";
8
11
  import { deployVercel } from "../deploy-targets/vercel.ts";
9
12
  import { runDev } from "../dev.ts";
10
- import { runSetup } from "../setup.ts";
11
- import { runClone } from "../clone.ts";
13
+ import { runRelease } from "../release.ts";
12
14
  import { pullSecrets, pushSecrets } from "../secrets.ts";
13
- import pkg from "../../package.json" with { type: "json" };
15
+ import { runSetup } from "../setup.ts";
16
+ import { runSim } from "../sim.ts";
17
+ import { runVersion } from "../version.ts";
14
18
 
15
19
  const { values, positionals } = parseArgs({
16
20
  options: {
17
21
  open: { type: "boolean", default: false },
22
+ real: { type: "boolean", default: false },
23
+ device: { type: "string" },
18
24
  dry: { type: "boolean", default: false },
19
25
  verbose: { type: "boolean", default: false },
20
26
  version: { type: "boolean", short: "v", default: false },
@@ -32,12 +38,18 @@ const usage = `usage: devkit [root] [--open] [--dry] run the dev processes
32
38
  devkit clone <owner/repo> [dir] clone, decrypt secrets, set up
33
39
  devkit setup [root] [--dry] validate secrets, install, terraform init, run steps
34
40
  devkit deploy [targets...] run the configured deploys, in parallel
41
+ devkit build build the web app and the API into one Vercel output
42
+ devkit sim [--real] [--device n] build and launch the app on a simulator
43
+ devkit version write the source version into every file that declares one
44
+ devkit release <prefix> tag this commit <prefix>-v<timestamp> and push it
35
45
  devkit secrets push|pull [root] sync age-encrypted secrets
36
46
 
37
47
  root path to the folder holding the devkit config (default: cwd)
38
48
  --open open each app's URL in the browser once its port is live
39
49
  --dry print what would run without running it
40
50
  --verbose stream every line instead of drawing the live board (deploy)
51
+ --real run the simulator build against the real API instead of sample data
52
+ --device simulator to run on, overriding the configured one
41
53
  --version print the devkit version`;
42
54
 
43
55
  if (values.help) {
@@ -64,6 +76,22 @@ try {
64
76
  await runSetup(values.dry);
65
77
  break;
66
78
  }
79
+ case "build": {
80
+ await runBuild();
81
+ break;
82
+ }
83
+ case "sim": {
84
+ await runSim({ real: values.real, device: values.device });
85
+ break;
86
+ }
87
+ case "version": {
88
+ await runVersion();
89
+ break;
90
+ }
91
+ case "release": {
92
+ await runRelease(rest[0] ?? "");
93
+ break;
94
+ }
67
95
  case "deploy": {
68
96
  await runDeploy(rest, { dry: values.dry, verbose: values.verbose });
69
97
  break;
@@ -73,7 +101,7 @@ try {
73
101
  case "_deploy-target": {
74
102
  const [name] = rest;
75
103
  const { deploy } = loadConfig();
76
- const target = deploy?.find((t) => t.name === name);
104
+ const target = deploy.find((t) => t.name === name);
77
105
  if (!target?.type) throw new Error(`No deploy target ${name} with a "type"`);
78
106
  if (target.type === "vercel") await deployVercel(target.options);
79
107
  else if (target.type === "tauri-macos") await deployTauriMacos(target.options);
package/src/build.ts ADDED
@@ -0,0 +1,75 @@
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
+ import { loadConfig } from "./config.ts";
6
+
7
+ /**
8
+ * Build a client-rendered web app and a Nitro API into a single Vercel deployment: the app as
9
+ * static files, the API as the one serverless function behind them. Both end up at the same
10
+ * origin, so the web client calls the API without CORS and there is one URL to remember.
11
+ */
12
+ export async function runBuild() {
13
+ const { build } = loadConfig();
14
+ if (!build) throw new Error('No "devkit.build" config in package.json');
15
+
16
+ const root = process.cwd();
17
+ const frontend = resolve(root, build.frontendDir ?? "apps/frontend");
18
+ const backend = resolve(root, build.backendDir ?? "apps/backend");
19
+ const webDir = join(backend, "public");
20
+ const nitroOutput = join(backend, ".vercel/output");
21
+ const finalOutput = join(root, ".vercel/output");
22
+
23
+ // The typed client is generated from the route handlers, so it has to exist before the app
24
+ // compiles — unless a release already did it, in which case regenerating it now would be writing
25
+ // to files a build running alongside is reading.
26
+ if (build.clientCommand && !process.env.SKIP_CLIENT_GEN) await $`sh -c ${build.clientCommand}`.cwd(backend);
27
+
28
+ await $`bun run build`.cwd(frontend);
29
+ await rm(webDir, { recursive: true, force: true });
30
+ await cp(join(frontend, build.webBuildDir ?? "build"), webDir, { recursive: true });
31
+
32
+ // Anything a sibling target staged for the site to hand out — an installer, say — rides along
33
+ // with the web files rather than living in the frontend's static folder, which other builds
34
+ // copy wholesale.
35
+ for (const [from, to] of Object.entries(build.include ?? {})) {
36
+ const staged = resolve(root, from);
37
+ if (!existsSync(staged)) {
38
+ console.log(`Nothing staged at ${from} — the site will serve no ${to}`);
39
+ continue;
40
+ }
41
+ await cp(staged, join(webDir, to), { recursive: true });
42
+ console.log(`Serving ${from} at /${to}`);
43
+ }
44
+
45
+ await rm(nitroOutput, { recursive: true, force: true });
46
+ await $`bunx nitro build --preset vercel`.cwd(backend);
47
+
48
+ await rm(finalOutput, { recursive: true, force: true });
49
+ await rename(nitroOutput, finalOutput);
50
+
51
+ await routeUnmatchedPathsToTheApp(finalOutput, build.apiPrefixes ?? []);
52
+ }
53
+
54
+ /**
55
+ * The app is one client-rendered bundle, so every path it owns has to answer with `index.html`
56
+ * and let the router sort it out. Nitro ends its routes with a catch-all into the function, which
57
+ * would otherwise answer an unknown web path with an API-shaped 404 JSON body.
58
+ */
59
+ async function routeUnmatchedPathsToTheApp(output: string, apiPrefixes: readonly string[]) {
60
+ if (!apiPrefixes.length) throw new Error('"devkit.build.apiPrefixes" must list the paths the API owns');
61
+
62
+ const configPath = join(output, "config.json");
63
+ const config = await Bun.file(configPath).json();
64
+ const staticDir = join(output, "static");
65
+ if (!existsSync(staticDir)) throw new Error(`No static output at ${staticDir} — did the web build land?`);
66
+
67
+ const catchAll = config.routes.findIndex((route: { dest?: string }) => route.dest === "/__fallback");
68
+ config.routes.splice(catchAll < 0 ? config.routes.length : catchAll, 0, {
69
+ src: `/((?!${apiPrefixes.join("|")}).*)`,
70
+ dest: "/index.html",
71
+ });
72
+
73
+ await Bun.write(configPath, JSON.stringify(config, null, 2));
74
+ console.log("Unmatched web paths route to the app shell");
75
+ }
package/src/config.ts CHANGED
@@ -1,11 +1,9 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
 
4
- /** One dev process. Resolved into a shell command by {@link commandFor}. */
4
+ /** One dev process, keyed by its name. Resolved into a shell command by {@link commandFor}. */
5
5
  export interface DevApp {
6
- /** Display name; also the default `bun --filter` target. */
7
- name?: string;
8
- /** Explicit `bun --filter <target>` (defaults to `name`). */
6
+ /** Explicit `bun --filter <target>` (defaults to the name). */
9
7
  filter?: string;
10
8
  /** Run via `bun --cwd <cwd> run <script>` instead of `--filter`. */
11
9
  cwd?: string;
@@ -59,8 +57,6 @@ export interface SetupConfig {
59
57
  * the whole release.
60
58
  */
61
59
  export interface DeployTarget {
62
- /** Display name, and the name used on the command line and in `needs`. */
63
- name: string;
64
60
  /** Shell command that performs this deploy. Omit when `type` names a built-in target instead. */
65
61
  command?: string;
66
62
  /** A built-in deploy target — see `src/deploy-targets/`. `options` is that target's own config. */
@@ -73,19 +69,102 @@ export interface DeployTarget {
73
69
  color?: string;
74
70
  }
75
71
 
72
+ /**
73
+ * `devkit build`: a client-rendered web app and a Nitro API packed into one Vercel deployment.
74
+ */
75
+ export interface BuildConfig {
76
+ /** Web app dir, run with `bun run build` (default `apps/frontend`). */
77
+ frontendDir?: string;
78
+ /** Nitro dir, built with `bunx nitro build --preset vercel` (default `apps/backend`). */
79
+ backendDir?: string;
80
+ /** Where the web build lands inside `frontendDir` (default `build`). */
81
+ webBuildDir?: string;
82
+ /** Path prefixes the API owns; everything else answers with the app shell. */
83
+ apiPrefixes: string[];
84
+ /** Run in `backendDir` before the web build, unless `SKIP_CLIENT_GEN` is set (e.g. `bunx nitro-client`). */
85
+ clientCommand?: string;
86
+ /** Extra staged directories to serve, as `{ "<source dir>": "<path under the site>" }`. */
87
+ include?: Record<string, string>;
88
+ }
89
+
90
+ /** `devkit sim`: an Apple app built and launched on a simulator, without opening Xcode. */
91
+ export interface SimConfig {
92
+ /** Path to the `.xcodeproj`. */
93
+ project: string;
94
+ /** Scheme to build; also the name of the built `.app`. */
95
+ scheme: string;
96
+ /** Bundle id to install and launch. */
97
+ bundleId: string;
98
+ /** Simulator to run on — overridable with `--device` or `DEVKIT_SIM_DEVICE`. */
99
+ device: string;
100
+ /** Simulator SDK the products are built for (default `watchsimulator`). */
101
+ sdk?: string;
102
+ /** Derived data dir (default `build/sim`). */
103
+ derivedDataDir?: string;
104
+ /** Env var the app reads to show sample data; set unless `--real` is passed. */
105
+ previewEnv?: string;
106
+ }
107
+
108
+ /** `devkit version`: one version, declared once and written everywhere else it appears. */
109
+ export interface VersionConfig {
110
+ /** JSON file whose `version` field is the number the rest follow. */
111
+ source: string;
112
+ /** `package.json`-shaped files. */
113
+ packages?: string[];
114
+ /** `Cargo.toml` files. */
115
+ cargo?: string[];
116
+ /** `project.pbxproj` files, whose `MARKETING_VERSION` every target's plist reads. */
117
+ xcodeProjects?: string[];
118
+ /** Plists of targets in those projects — pointed at `$(MARKETING_VERSION)` rather than a number. */
119
+ marketingVersionPlists?: string[];
120
+ /** Plists of targets with no project setting of their own, which carry the number itself. */
121
+ plists?: string[];
122
+ }
123
+
124
+ /** Apps and deploy targets are written as name-keyed maps, so a name is never repeated or missing. */
76
125
  export interface DevkitConfig {
77
- apps: DevApp[];
126
+ apps?: Record<string, DevApp>;
78
127
  setup?: SetupConfig;
79
- deploy?: DeployTarget[];
128
+ deploy?: Record<string, DeployTarget>;
129
+ build?: BuildConfig;
130
+ sim?: SimConfig;
131
+ version?: VersionConfig;
132
+ }
133
+
134
+ /** A config entry with its map key attached — the name every command prints and refers to. */
135
+ export type Named<T> = T & { readonly name: string };
136
+
137
+ /** What the commands read: the same config, with each map flattened into named entries. */
138
+ export interface LoadedConfig {
139
+ apps: Named<DevApp>[];
140
+ setup?: SetupConfig;
141
+ deploy: Named<DeployTarget>[];
142
+ build?: BuildConfig;
143
+ sim?: SimConfig;
144
+ version?: VersionConfig;
80
145
  }
81
146
 
82
147
  /** Read the `devkit` config from the nearest package.json. */
83
- export function loadConfig(dir: string = process.cwd()): DevkitConfig {
148
+ export function loadConfig(dir: string = process.cwd()): LoadedConfig {
84
149
  const pkgPath = resolve(dir, "package.json");
85
150
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { devkit?: DevkitConfig };
86
151
  const cfg = pkg.devkit;
87
152
  // `devkit deploy` is useful in a repo that runs nothing locally, so only the dev command
88
- // insists on apps — see {@link requireApps}.
153
+ // insists on apps.
89
154
  if (!cfg) throw new Error(`No "devkit" config found in ${pkgPath}`);
90
- return cfg;
155
+ return {
156
+ apps: named(cfg.apps, "apps", pkgPath),
157
+ setup: cfg.setup,
158
+ deploy: named(cfg.deploy, "deploy", pkgPath),
159
+ build: cfg.build,
160
+ sim: cfg.sim,
161
+ version: cfg.version,
162
+ };
163
+ }
164
+
165
+ function named<T>(map: Record<string, T> | undefined, key: string, pkgPath: string): Named<T>[] {
166
+ if (map === undefined) return [];
167
+ if (Array.isArray(map))
168
+ throw new Error(`"devkit.${key}" in ${pkgPath} is a list — it is now a map of name to settings`);
169
+ return Object.entries(map).map(([name, entry]) => ({ ...entry, name }));
91
170
  }
package/src/deploy.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { mkdirSync, writeFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { type DeployTarget, loadConfig } from "./config.ts";
4
+ import { type DeployTarget, loadConfig, type Named } from "./config.ts";
5
5
 
6
6
  const PALETTE: readonly string[] = ["magenta", "cyan", "yellow", "green", "blue", "red"];
7
7
  const COLORS: Record<string, string> = {
@@ -27,7 +27,7 @@ type Status = "waiting" | "running" | "done" | "failed" | "skipped";
27
27
 
28
28
  /** One target's progress, and everything the board needs to draw its line. */
29
29
  interface Job {
30
- target: DeployTarget & { command: string };
30
+ target: Named<DeployTarget> & { command: string };
31
31
  label: string;
32
32
  color: string;
33
33
  status: Status;
@@ -49,7 +49,7 @@ interface Job {
49
49
  */
50
50
  export async function runDeploy(only: string[], options: { dry?: boolean; verbose?: boolean } = {}) {
51
51
  const { deploy } = loadConfig();
52
- if (!deploy?.length) throw new Error('No "devkit.deploy" targets in package.json');
52
+ if (!deploy.length) throw new Error('No "devkit.deploy" targets in package.json');
53
53
 
54
54
  const unknown = only.filter((name) => !deploy.some((target) => target.name === name));
55
55
  if (unknown.length) {
@@ -58,7 +58,8 @@ export async function runDeploy(only: string[], options: { dry?: boolean; verbos
58
58
 
59
59
  for (const target of deploy) {
60
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(", ")}`);
61
+ if (missing.length)
62
+ throw new Error(`${target.name} needs unknown target${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}`);
62
63
  if (!target.command && !target.type) throw new Error(`${target.name} needs a "command" or a "type"`);
63
64
  }
64
65
 
@@ -69,7 +70,10 @@ export async function runDeploy(only: string[], options: { dry?: boolean; verbos
69
70
  mkdirSync(logDir, { recursive: true });
70
71
 
71
72
  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
+ bold(`\ndeploying ${jobs.map((job) => job.label).join(", ")}`) +
75
+ dim(live ? ` · logs in ${"./.devkit/deploy"}` : ""),
76
+ );
73
77
  console.log();
74
78
  const board = live ? startBoard(jobs) : null;
75
79
 
@@ -93,7 +97,7 @@ export async function runDeploy(only: string[], options: { dry?: boolean; verbos
93
97
  }
94
98
 
95
99
  /** The targets asked for, plus whatever they depend on — a target can't run without its needs. */
96
- function selected(targets: DeployTarget[], only: string[]) {
100
+ function selected(targets: Named<DeployTarget>[], only: string[]) {
97
101
  if (!only.length) return targets;
98
102
  const wanted = new Set(only);
99
103
  let grew = true;
@@ -112,7 +116,7 @@ function selected(targets: DeployTarget[], only: string[]) {
112
116
  return targets.filter((target) => wanted.has(target.name));
113
117
  }
114
118
 
115
- function toJob(target: DeployTarget, index: number): Job {
119
+ function toJob(target: Named<DeployTarget>, index: number): Job {
116
120
  // A built-in target has no shell command of its own — it runs through `devkit _deploy-target`,
117
121
  // which looks its options back up from this same config by name.
118
122
  const command = target.command ?? `devkit _deploy-target ${JSON.stringify(target.name)}`;
package/src/dev.ts CHANGED
@@ -1,49 +1,45 @@
1
1
  import concurrently from "concurrently";
2
- import { type DevApp, loadConfig } from "./config.ts";
2
+ import { type DevApp, loadConfig, type Named } 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
8
  /** Turn an app entry into the shell command that runs it. */
9
- function commandFor(app: DevApp): string {
9
+ function commandFor(app: Named<DevApp>): string {
10
10
  if (app.command) return app.command;
11
11
  const script = app.script ?? "dev";
12
12
  if (app.cwd) return `bun run --cwd ${app.cwd} ${script}`;
13
13
  return `bun --filter ${app.filter ?? app.name} ${script}`;
14
14
  }
15
15
 
16
- function labelFor(app: DevApp, index: number): string {
17
- return app.name ?? app.filter ?? app.cwd ?? `app${index}`;
18
- }
19
-
20
16
  /** Free ports, print URLs, run every app side-by-side, optionally open the browser. */
21
17
  export async function runDev(open: boolean, dry = false): Promise<void> {
22
18
  const { apps } = loadConfig();
23
- if (!apps?.length) throw new Error('No "devkit.apps" to run');
19
+ if (!apps.length) throw new Error('No "devkit.apps" to run');
24
20
  const withPort = apps.filter((app) => app.port != null);
25
21
 
26
22
  if (dry) {
27
23
  console.log("devkit (dry run):");
28
- apps.forEach((app, i) => {
24
+ for (const app of apps) {
29
25
  const url = app.port != null ? ` → http://localhost:${app.port}${app.open ? " (open)" : ""}` : "";
30
- console.log(` [${labelFor(app, i)}] ${commandFor(app)}${url}`);
31
- });
26
+ console.log(` [${app.name}] ${commandFor(app)}${url}`);
27
+ }
32
28
  return;
33
29
  }
34
30
 
35
31
  await Promise.all(withPort.map((app) => freePort(app.port as number)));
36
32
 
37
33
  if (withPort.length > 0) {
38
- const width = Math.max(...withPort.map((app, i) => labelFor(app, i).length));
39
- const lines = withPort.map((app, i) => `${labelFor(app, i).padEnd(width)} http://localhost:${app.port}`);
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}`);
40
36
  console.log(`\n${lines.join("\n")}\n`);
41
37
  }
42
38
 
43
39
  const { result } = concurrently(
44
40
  apps.map((app, i) => ({
45
41
  command: commandFor(app),
46
- name: labelFor(app, i),
42
+ name: app.name,
47
43
  prefixColor: app.color ?? PALETTE[i % PALETTE.length],
48
44
  })),
49
45
  { prefix: "name", killOthersOn: ["failure", "success"] },
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
+ }
package/src/sim.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { resolve } from "node:path";
2
+ import { $ } from "bun";
3
+ import { loadConfig } from "./config.ts";
4
+
5
+ /**
6
+ * Build an Apple app and run it on a simulator, without going through Xcode.
7
+ *
8
+ * A watch app usually has no sign-in of its own, so on a simulator with no paired phone it can
9
+ * only show its signed-out screen. `preview` launches it with the app's own preview flag set
10
+ * instead, which is the point of running it here at all: gestures have to be felt.
11
+ */
12
+ export async function runSim(options: { real?: boolean; device?: string } = {}) {
13
+ const { sim } = loadConfig();
14
+ if (!sim) throw new Error('No "devkit.sim" config in package.json');
15
+
16
+ const project = resolve(process.cwd(), sim.project);
17
+ const derived = resolve(process.cwd(), sim.derivedDataDir ?? "build/sim");
18
+ const sdk = sim.sdk ?? "watchsimulator";
19
+ const deviceName = options.device ?? process.env.DEVKIT_SIM_DEVICE ?? sim.device;
20
+ const preview = !options.real;
21
+
22
+ const udid = await boot(deviceName);
23
+
24
+ await $`xcodebuild -project ${project} -scheme ${sim.scheme} -configuration Debug \
25
+ -destination id=${udid} -derivedDataPath ${derived} build`.quiet();
26
+
27
+ await $`xcrun simctl install ${udid} ${derived}/Build/Products/Debug-${sdk}/${sim.scheme}.app`;
28
+ await $`xcrun simctl terminate ${udid} ${sim.bundleId}`.nothrow().quiet();
29
+ // `SIMCTL_CHILD_` is how simctl passes an environment on to the app it launches.
30
+ await $`xcrun simctl launch ${udid} ${sim.bundleId}`.env({
31
+ ...process.env,
32
+ ...(preview && sim.previewEnv ? { [`SIMCTL_CHILD_${sim.previewEnv}`]: "1" } : {}),
33
+ });
34
+
35
+ console.log(`${sim.scheme} running on ${deviceName}${preview && sim.previewEnv ? " with sample data" : ""}`);
36
+ }
37
+
38
+ /** Boots the simulator if it isn't already up, and returns its device id. */
39
+ async function boot(deviceName: string) {
40
+ const { devices } = await $`xcrun simctl list devices available -j`.quiet().json();
41
+ // The same model exists once per installed runtime; the newest one is the one to use.
42
+ const runtimes = Object.keys(devices).sort().reverse();
43
+ const match = runtimes
44
+ .flatMap((runtime) => devices[runtime] as { name: string; udid: string; state: string }[])
45
+ .find((device) => device.name === deviceName);
46
+
47
+ if (!match) throw new Error(`No simulator called "${deviceName}" — see \`xcrun simctl list devices available\``);
48
+ if (match.state !== "Booted") await $`xcrun simctl boot ${match.udid}`;
49
+ await $`open -a Simulator`;
50
+ return match.udid;
51
+ }
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
+ }