@elumixor/devkit 0.5.0 → 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elumixor/devkit",
3
- "version": "0.5.0",
3
+ "version": "0.7.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,7 +1,11 @@
1
1
  #!/usr/bin/env bun
2
2
  import { parseArgs } from "node:util";
3
3
  import { resolve } from "node:path";
4
+ import { loadConfig } from "../config.ts";
4
5
  import { runDeploy } from "../deploy.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";
5
9
  import { runDev } from "../dev.ts";
6
10
  import { runSetup } from "../setup.ts";
7
11
  import { runClone } from "../clone.ts";
@@ -64,6 +68,19 @@ try {
64
68
  await runDeploy(rest, { dry: values.dry, verbose: values.verbose });
65
69
  break;
66
70
  }
71
+ // Internal: how a built-in `type`d deploy target actually runs — spawned as its own process
72
+ // by `runDeploy` so it gets the same line-capture and log file as a hand-written `command`.
73
+ case "_deploy-target": {
74
+ const [name] = rest;
75
+ const { deploy } = loadConfig();
76
+ const target = deploy?.find((t) => t.name === name);
77
+ if (!target?.type) throw new Error(`No deploy target ${name} with a "type"`);
78
+ if (target.type === "vercel") await deployVercel(target.options);
79
+ else if (target.type === "tauri-macos") await deployTauriMacos(target.options);
80
+ else if (target.type === "fastlane-ios") await deployFastlaneIos(target.options);
81
+ else throw new Error(`Unknown deploy target type: ${target.type}`);
82
+ break;
83
+ }
67
84
  case "secrets": {
68
85
  const [action, dir] = rest;
69
86
  chdirTo(dir);
package/src/config.ts CHANGED
@@ -61,8 +61,12 @@ export interface SetupConfig {
61
61
  export interface DeployTarget {
62
62
  /** Display name, and the name used on the command line and in `needs`. */
63
63
  name: string;
64
- /** Shell command that performs this deploy. */
65
- command: string;
64
+ /** Shell command that performs this deploy. Omit when `type` names a built-in target instead. */
65
+ command?: string;
66
+ /** A built-in deploy target — see `src/deploy-targets/`. `options` is that target's own config. */
67
+ type?: "vercel" | "tauri-macos" | "fastlane-ios";
68
+ // biome-ignore lint/suspicious/noExplicitAny: each `type` has its own options shape
69
+ options?: any;
66
70
  /** Targets that must finish first. */
67
71
  needs?: string[];
68
72
  /** Colour for this target's line on the board. */
@@ -0,0 +1,91 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { $ } from "bun";
5
+
6
+ export interface FastlaneIosTargetOptions {
7
+ /** Capacitor/frontend dir (default `apps/frontend`). */
8
+ frontendDir?: string;
9
+ /** Backend dir to generate a typed API client from before building, if any. */
10
+ backendDir?: string;
11
+ /** iOS project dir (default `<frontendDir>/ios`). */
12
+ iosDir?: string;
13
+ /** Fastlane lane to run (default `beta`). */
14
+ lane?: string;
15
+ /** API base URL the build embeds, unless `apiBaseUrlEnv` is already set. */
16
+ defaultApiBaseUrl: string;
17
+ /** Env var an override is read from, and passed to the build as `VITE_API_BASE_URL` (default `DEPLOY_API_BASE_URL`). */
18
+ apiBaseUrlEnv?: string;
19
+ keyIdEnv?: string;
20
+ issuerIdEnv?: string;
21
+ keyPathEnv?: string;
22
+ }
23
+
24
+ /**
25
+ * Builds the web bundle against the deployed API, syncs it into the Xcode project and hands the
26
+ * archive to fastlane, which signs the app, the watch app and the widget and uploads to
27
+ * TestFlight.
28
+ */
29
+ export async function deployFastlaneIos(options: FastlaneIosTargetOptions) {
30
+ const frontendDir = options.frontendDir ?? "apps/frontend";
31
+ const iosDir = options.iosDir ?? join(frontendDir, "ios");
32
+ const lane = options.lane ?? "beta";
33
+ const apiBaseUrlEnv = options.apiBaseUrlEnv ?? "DEPLOY_API_BASE_URL";
34
+ const apiBaseUrl = process.env[apiBaseUrlEnv] ?? options.defaultApiBaseUrl;
35
+
36
+ const keyIdEnv = options.keyIdEnv ?? "APP_STORE_CONNECT_API_KEY_ID";
37
+ const issuerIdEnv = options.issuerIdEnv ?? "APP_STORE_CONNECT_API_KEY_ISSUER_ID";
38
+ const keyPathEnvName = options.keyPathEnv ?? "APP_STORE_CONNECT_API_KEY_PATH";
39
+
40
+ // fastlane needs a modern Ruby; macOS still ships 2.6, which its gems no longer install against.
41
+ // `bundle` is called by full path because Bun's shell resolves a command against its own PATH
42
+ // before the env below is applied, and would find /usr/bin/bundle — the system Ruby's.
43
+ const rubyBin = "/opt/homebrew/opt/ruby/bin";
44
+ const bundle = join(rubyBin, "bundle");
45
+ if (!existsSync(bundle)) throw new Error("No Homebrew Ruby at /opt/homebrew/opt/ruby — `brew install ruby`");
46
+
47
+ const keyPath = process.env[keyPathEnvName] ?? join(homedir(), ".appstoreconnect/private_keys", `AuthKey_${required(keyIdEnv)}.p8`);
48
+ const env = {
49
+ ...process.env,
50
+ PATH: `${rubyBin}:${process.env.PATH}`,
51
+ [keyIdEnv]: required(keyIdEnv),
52
+ [issuerIdEnv]: required(issuerIdEnv),
53
+ [keyPathEnvName]: keyPath,
54
+ FASTLANE_SKIP_UPDATE_CHECK: "1",
55
+ FASTLANE_HIDE_CHANGELOG: "1",
56
+ };
57
+ if (!existsSync(keyPath)) throw new Error(`No App Store Connect key at ${keyPath}`);
58
+
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
+ // The web build a release ships to Vercel is happening in the next directory over, against the
65
+ // same sources — this one gets its own output, cache and Capacitor web root so neither sees half
66
+ // 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
+ };
74
+ await $`bun run build`.cwd(frontendDir).env(buildEnv);
75
+ await $`bunx cap sync ios`.cwd(frontendDir).env(buildEnv);
76
+
77
+ // `cap sync` reports a failed copy and still exits 0, which would archive whatever web assets the
78
+ // project happened to be carrying from a previous build.
79
+ const bundled = join(iosDir, "App/App/public/index.html");
80
+ if (!existsSync(bundled)) throw new Error(`cap sync didn't copy the web build — no ${bundled}`);
81
+
82
+ const installed = await $`${bundle} check`.cwd(iosDir).env(env).nothrow().quiet();
83
+ if (installed.exitCode !== 0) await $`${bundle} install`.cwd(iosDir).env(env);
84
+ await $`${bundle} exec fastlane ${lane}`.cwd(iosDir).env(env);
85
+ }
86
+
87
+ function required(name: string) {
88
+ const value = process.env[name];
89
+ if (!value) throw new Error(`${name} is missing — put it in the repo's .env`);
90
+ return value;
91
+ }
@@ -0,0 +1,130 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { $ } from "bun";
6
+
7
+ export interface TauriMacosTargetOptions {
8
+ /** Tauri project dir, holding `src-tauri` (default `apps/frontend`). */
9
+ frontendDir?: string;
10
+ /** Where the DMG and its manifest are staged for a web deploy to serve (default `dist/download`). */
11
+ stageDir?: string;
12
+ /** Reinstall to `/Applications/<name>.app` after building, if it's already there (default true). */
13
+ installIfPresent?: boolean;
14
+ /** App Store Connect key env vars, for notarization (defaults match the iOS release). */
15
+ keyIdEnv?: string;
16
+ issuerIdEnv?: string;
17
+ keyPathEnv?: string;
18
+ }
19
+
20
+ /**
21
+ * Builds the macOS app, signs and notarizes it if this machine has a Developer ID certificate,
22
+ * and stages the DMG (plus a manifest describing it) for the web deploy to hand out. Refreshes
23
+ * the local install too, if this machine already has one.
24
+ */
25
+ export async function deployTauriMacos(options: TauriMacosTargetOptions = {}) {
26
+ const frontendDir = options.frontendDir ?? "apps/frontend";
27
+ const stageDir = options.stageDir ?? "dist/download";
28
+ const bundleDir = join(frontendDir, "src-tauri/target/release/bundle/dmg");
29
+ const appDir = join(frontendDir, "src-tauri/target/release/bundle/macos");
30
+
31
+ const conf = (await Bun.file(join(frontendDir, "src-tauri/tauri.conf.json")).json()) as {
32
+ version: string;
33
+ productName: string;
34
+ };
35
+ const { version, productName } = conf;
36
+ const installed = join("/Applications", `${productName}.app`);
37
+
38
+ // macOS refuses a downloaded app that carries no signature at all — "App is damaged and can't
39
+ // be opened" — so the bundle is always signed with something. A Developer ID certificate in the
40
+ // keychain also buys notarization, which is the only thing that makes the app open on a click;
41
+ // an ad-hoc signature just moves the refusal to a dialog the user can override in Settings.
42
+ const identity = await developerId();
43
+ if (identity) console.log(`Signing as ${identity}, and notarizing`);
44
+ else console.log("No Developer ID certificate — signing ad-hoc, so the app needs Open Anyway once");
45
+
46
+ const keyIdEnv = options.keyIdEnv ?? "APP_STORE_CONNECT_API_KEY_ID";
47
+ const issuerIdEnv = options.issuerIdEnv ?? "APP_STORE_CONNECT_API_KEY_ISSUER_ID";
48
+ const keyPathEnvName = options.keyPathEnv ?? "APP_STORE_CONNECT_API_KEY_PATH";
49
+
50
+ // Bundling a DMG consumes the .app it packages, deleting it once the DMG exists — so the .app
51
+ // has to be requested as its own bundle target too, or there's nothing left to reinstall from.
52
+ const reinstall = (options.installIfPresent ?? true) && existsSync(installed);
53
+ await $`bunx tauri build --bundles ${reinstall ? "dmg,app" : "dmg"}`.cwd(frontendDir).env({
54
+ ...process.env,
55
+ APPLE_SIGNING_IDENTITY: identity ?? "-",
56
+ ...(identity
57
+ ? {
58
+ APPLE_API_KEY: required(keyIdEnv),
59
+ APPLE_API_ISSUER: required(issuerIdEnv),
60
+ APPLE_API_KEY_PATH: keyPath(keyIdEnv, keyPathEnvName),
61
+ }
62
+ : {}),
63
+ });
64
+
65
+ const dmg = (await readdir(bundleDir)).find((name) => name.endsWith(".dmg"));
66
+ if (!dmg) throw new Error(`No .dmg in ${bundleDir}`);
67
+
68
+ // Tauri notarizes and staples the app, then signs the DMG around it — leaving the DMG itself
69
+ // unnotarized, which is what Gatekeeper judges when someone opens the file they downloaded.
70
+ if (identity) await notarize(join(bundleDir, dmg), keyIdEnv, issuerIdEnv, keyPathEnvName);
71
+
72
+ await rm(stageDir, { recursive: true, force: true });
73
+ await mkdir(stageDir, { recursive: true });
74
+ const stagedDmg = join(stageDir, `${productName}.dmg`);
75
+ await $`cp ${join(bundleDir, dmg)} ${stagedDmg}`;
76
+
77
+ // What a settings panel prints next to the download button. The app can't read the file's own
78
+ // size or age once it's behind a CDN, and a button that says nothing about what it is asking you
79
+ // to install is a worse button.
80
+ const { size } = await stat(stagedDmg);
81
+ await Bun.write(
82
+ join(stageDir, "desktop.json"),
83
+ `${JSON.stringify(
84
+ { version, bytes: size, builtAt: new Date().toISOString(), arch: "Apple Silicon", notarized: Boolean(identity) },
85
+ null,
86
+ 2,
87
+ )}\n`,
88
+ );
89
+ console.log(`Staged ${dmg} (${(size / 1e6).toFixed(1)} MB) for the web deployment`);
90
+
91
+ // "Configured" means this machine already has the app installed — a fresh checkout building for
92
+ // the web deploy shouldn't plant a copy nobody asked for.
93
+ if (reinstall) {
94
+ const appBundle = join(appDir, `${productName}.app`);
95
+ if (!existsSync(appBundle)) throw new Error(`Requested "app" alongside "dmg" but there's no bundle at ${appBundle}`);
96
+ await $`osascript -e ${`quit app "${productName}"`}`.nothrow().quiet();
97
+ await $`rm -rf ${installed}`;
98
+ await $`cp -R ${appBundle} ${installed}`;
99
+ await $`xattr -cr ${installed}`.nothrow().quiet();
100
+ console.log(`Reinstalled ${installed}`);
101
+ }
102
+
103
+ /** Sends the disk image to Apple and staples their answer into it, so it opens offline too. */
104
+ async function notarize(path: string, keyIdEnv: string, issuerIdEnv: string, keyPathEnvName: string) {
105
+ const key = ["--key", keyPath(keyIdEnv, keyPathEnvName), "--key-id", required(keyIdEnv), "--issuer", required(issuerIdEnv)];
106
+ await $`xcrun notarytool submit ${path} ${key} --wait`;
107
+ await $`xcrun stapler staple ${path}`;
108
+ }
109
+ }
110
+
111
+ /** The Developer ID identity in this machine's keychain, if the account has one yet. */
112
+ async function developerId() {
113
+ const found = await $`security find-identity -v -p codesigning`.quiet().nothrow();
114
+ const line = found.stdout
115
+ .toString()
116
+ .split("\n")
117
+ .find((row) => row.includes("Developer ID Application"));
118
+ return line?.match(/"([^"]+)"/)?.[1];
119
+ }
120
+
121
+ function required(name: string) {
122
+ const value = process.env[name];
123
+ if (!value) throw new Error(`${name} is missing — put it in the repo's .env`);
124
+ return value;
125
+ }
126
+
127
+ /** Notarization takes the same App Store Connect key an iOS release uses. */
128
+ function keyPath(keyIdEnv: string, keyPathEnvName: string) {
129
+ return process.env[keyPathEnvName] ?? join(homedir(), ".appstoreconnect/private_keys", `AuthKey_${required(keyIdEnv)}.p8`);
130
+ }
@@ -0,0 +1,34 @@
1
+ import { resolve } from "node:path";
2
+ import { $ } from "bun";
3
+
4
+ export interface VercelTargetOptions {
5
+ /** Project root, relative to the config's directory (default `.`). */
6
+ cwd?: string;
7
+ }
8
+
9
+ /**
10
+ * Builds here and uploads the finished output, rather than handing Vercel the repo and waiting
11
+ * for it to build the same thing again.
12
+ */
13
+ export async function deployVercel(options: VercelTargetOptions = {}) {
14
+ // Bun's `$` resolves a "." cwd wrong (chases a literal "undefined" path segment) — pass it an
15
+ // absolute path instead.
16
+ const cwd = resolve(options.cwd ?? ".");
17
+ await $`bunx vercel build --prod --yes`.cwd(cwd);
18
+
19
+ // The upload is the one part of a release that a flaky minute of home internet can end — the
20
+ // CLI waits on the deployment over the network and gives up when the connection does, whatever
21
+ // the deployment itself went on to do.
22
+ await retry(() => $`bunx vercel deploy --prebuilt --prod --yes`.cwd(cwd));
23
+ }
24
+
25
+ async function retry<T>(attempt: () => Promise<T>, times = 3): Promise<T> {
26
+ for (let remaining = times - 1; ; remaining--) {
27
+ try {
28
+ return await attempt();
29
+ } catch (error) {
30
+ if (remaining <= 0) throw error;
31
+ console.log(`Deploy failed, retrying (${remaining} left)`);
32
+ }
33
+ }
34
+ }
package/src/deploy.ts CHANGED
@@ -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;
30
+ target: DeployTarget & { command: string };
31
31
  label: string;
32
32
  color: string;
33
33
  status: Status;
@@ -59,6 +59,7 @@ export async function runDeploy(only: string[], options: { dry?: boolean; verbos
59
59
  for (const target of deploy) {
60
60
  const missing = (target.needs ?? []).filter((need) => !deploy.some((other) => other.name === need));
61
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"`);
62
63
  }
63
64
 
64
65
  const jobs = selected(deploy, only).map(toJob);
@@ -112,8 +113,11 @@ function selected(targets: DeployTarget[], only: string[]) {
112
113
  }
113
114
 
114
115
  function toJob(target: 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)}`;
115
119
  return {
116
- target,
120
+ target: { ...target, command },
117
121
  label: target.name,
118
122
  color: target.color ?? (PALETTE[index % PALETTE.length] as string),
119
123
  status: "waiting",