@elumixor/devkit 0.4.1 → 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/README.md +40 -0
- package/package.json +1 -1
- package/src/bin/devkit.ts +25 -0
- package/src/config.ts +24 -3
- package/src/deploy-targets/fastlane-ios.ts +91 -0
- package/src/deploy-targets/tauri-macos.ts +130 -0
- package/src/deploy-targets/vercel.ts +34 -0
- package/src/deploy.ts +258 -0
- package/src/dev.ts +1 -0
package/README.md
CHANGED
|
@@ -40,6 +40,46 @@ Each app runs `bun --filter <name> dev` by default. Override with:
|
|
|
40
40
|
| `color` | prefix color (blue, magenta, green, yellow, cyan, red) |
|
|
41
41
|
| `open` | with `--open`, open this app's URL when its port comes up |
|
|
42
42
|
|
|
43
|
+
## Deploy
|
|
44
|
+
|
|
45
|
+
`devkit deploy` runs the release steps of a repo the same way `devkit` runs its dev processes:
|
|
46
|
+
side by side, with one line each.
|
|
47
|
+
|
|
48
|
+
```jsonc
|
|
49
|
+
{
|
|
50
|
+
"scripts": { "deploy": "devkit deploy" },
|
|
51
|
+
"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
|
+
]
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
bun run deploy # every target
|
|
63
|
+
bun run deploy ios # one target, plus whatever it needs
|
|
64
|
+
devkit deploy --dry # print the plan
|
|
65
|
+
devkit deploy --verbose # stream every line instead of the live board
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Targets with no `needs` start together; one with `needs` waits for those, so a build that another
|
|
69
|
+
target packages up can run first without serialising the whole release.
|
|
70
|
+
|
|
71
|
+
Each target shows a spinner, how long it has been running and the last line it printed. The full
|
|
72
|
+
output goes to `.devkit/deploy/<name>.log`, and the tail of whichever target failed is printed at
|
|
73
|
+
the end — a release prints tens of thousands of lines, and interleaving all of them is unreadable.
|
|
74
|
+
Piped output (CI, a log file) gets prefixed streaming lines instead of the board.
|
|
75
|
+
|
|
76
|
+
| field | meaning |
|
|
77
|
+
| --------- | -------------------------------------------------- |
|
|
78
|
+
| `name` | display name, and how it's named on the command line |
|
|
79
|
+
| `command` | shell command that performs this deploy |
|
|
80
|
+
| `needs` | targets that must finish first |
|
|
81
|
+
| `color` | colour of this target's line |
|
|
82
|
+
|
|
43
83
|
## Setting up a machine
|
|
44
84
|
|
|
45
85
|
A repo usually needs a couple of gitignored files before it will run — `.env`, `infra/terraform.tfvars` — and those cannot be fetched back from a host. Vercel, for one, stores Terraform-managed variables write-only and hands them back from `vercel env pull` as *empty strings*, which looks like it worked and quietly leaves you with a `.env` full of blanks.
|
package/package.json
CHANGED
package/src/bin/devkit.ts
CHANGED
|
@@ -1,6 +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";
|
|
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";
|
|
4
9
|
import { runDev } from "../dev.ts";
|
|
5
10
|
import { runSetup } from "../setup.ts";
|
|
6
11
|
import { runClone } from "../clone.ts";
|
|
@@ -11,6 +16,7 @@ const { values, positionals } = parseArgs({
|
|
|
11
16
|
options: {
|
|
12
17
|
open: { type: "boolean", default: false },
|
|
13
18
|
dry: { type: "boolean", default: false },
|
|
19
|
+
verbose: { type: "boolean", default: false },
|
|
14
20
|
version: { type: "boolean", short: "v", default: false },
|
|
15
21
|
help: { type: "boolean", short: "h", default: false },
|
|
16
22
|
},
|
|
@@ -25,11 +31,13 @@ if (values.version) {
|
|
|
25
31
|
const usage = `usage: devkit [root] [--open] [--dry] run the dev processes (default)
|
|
26
32
|
devkit clone <owner/repo> [dir] clone, decrypt secrets, set up
|
|
27
33
|
devkit setup [root] [--dry] validate secrets, install, terraform init, run steps
|
|
34
|
+
devkit deploy [targets...] run the configured deploys, in parallel
|
|
28
35
|
devkit secrets push|pull [root] sync age-encrypted secrets
|
|
29
36
|
|
|
30
37
|
root path to the folder holding the devkit config (default: cwd)
|
|
31
38
|
--open open each app's URL in the browser once its port is live
|
|
32
39
|
--dry print what would run without running it
|
|
40
|
+
--verbose stream every line instead of drawing the live board (deploy)
|
|
33
41
|
--version print the devkit version`;
|
|
34
42
|
|
|
35
43
|
if (values.help) {
|
|
@@ -56,6 +64,23 @@ try {
|
|
|
56
64
|
await runSetup(values.dry);
|
|
57
65
|
break;
|
|
58
66
|
}
|
|
67
|
+
case "deploy": {
|
|
68
|
+
await runDeploy(rest, { dry: values.dry, verbose: values.verbose });
|
|
69
|
+
break;
|
|
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
|
+
}
|
|
59
84
|
case "secrets": {
|
|
60
85
|
const [action, dir] = rest;
|
|
61
86
|
chdirTo(dir);
|
package/src/config.ts
CHANGED
|
@@ -53,9 +53,30 @@ export interface SetupConfig {
|
|
|
53
53
|
steps?: string[];
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
/**
|
|
57
|
+
* One deploy step. Targets with no `needs` all start at once; a target with `needs` waits for
|
|
58
|
+
* those, which is what lets a build that another one packages up run first without serialising
|
|
59
|
+
* the whole release.
|
|
60
|
+
*/
|
|
61
|
+
export interface DeployTarget {
|
|
62
|
+
/** Display name, and the name used on the command line and in `needs`. */
|
|
63
|
+
name: 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;
|
|
70
|
+
/** Targets that must finish first. */
|
|
71
|
+
needs?: string[];
|
|
72
|
+
/** Colour for this target's line on the board. */
|
|
73
|
+
color?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
56
76
|
export interface DevkitConfig {
|
|
57
77
|
apps: DevApp[];
|
|
58
78
|
setup?: SetupConfig;
|
|
79
|
+
deploy?: DeployTarget[];
|
|
59
80
|
}
|
|
60
81
|
|
|
61
82
|
/** Read the `devkit` config from the nearest package.json. */
|
|
@@ -63,8 +84,8 @@ export function loadConfig(dir: string = process.cwd()): DevkitConfig {
|
|
|
63
84
|
const pkgPath = resolve(dir, "package.json");
|
|
64
85
|
const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { devkit?: DevkitConfig };
|
|
65
86
|
const cfg = pkg.devkit;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
}
|
|
87
|
+
// `devkit deploy` is useful in a repo that runs nothing locally, so only the dev command
|
|
88
|
+
// insists on apps — see {@link requireApps}.
|
|
89
|
+
if (!cfg) throw new Error(`No "devkit" config found in ${pkgPath}`);
|
|
69
90
|
return cfg;
|
|
70
91
|
}
|
|
@@ -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
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 { type DeployTarget, loadConfig } from "./config.ts";
|
|
5
|
+
|
|
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: 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: 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));
|
|
113
|
+
}
|
|
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)}`;
|
|
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)}…`);
|
package/src/dev.ts
CHANGED
|
@@ -20,6 +20,7 @@ function labelFor(app: DevApp, index: number): string {
|
|
|
20
20
|
/** Free ports, print URLs, run every app side-by-side, optionally open the browser. */
|
|
21
21
|
export async function runDev(open: boolean, dry = false): Promise<void> {
|
|
22
22
|
const { apps } = loadConfig();
|
|
23
|
+
if (!apps?.length) throw new Error('No "devkit.apps" to run');
|
|
23
24
|
const withPort = apps.filter((app) => app.port != null);
|
|
24
25
|
|
|
25
26
|
if (dry) {
|