healkite 0.1.1 → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Healkite
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -16,3 +16,7 @@ npx healkite release -c <channel-key> -p android -r 1.0 --sign healkite-signing.
16
16
  | `stats`, `device` | Health and per-device timelines |
17
17
 
18
18
  Run `npx healkite <command> --help` for options. AI assistants: see `healkite-mcp`.
19
+
20
+ ## License
21
+
22
+ MIT
package/dist/healkite.mjs CHANGED
@@ -8,6 +8,7 @@ var __export = (target, all) => {
8
8
  };
9
9
 
10
10
  // src/main.ts
11
+ import { existsSync as existsSync3 } from "node:fs";
11
12
  import { readFile as readFile5 } from "node:fs/promises";
12
13
  import { join as join5, resolve as resolve2 } from "node:path";
13
14
 
@@ -19930,6 +19931,34 @@ function patchSigningMessage(fromSha256, toSha256, patchSha256) {
19930
19931
  }
19931
19932
  return new TextEncoder().encode(`healkite-patch:v1:${fromSha256}:${toSha256}:${patchSha256}`);
19932
19933
  }
19934
+ function fromBase64(b64) {
19935
+ const bin = atob(b64);
19936
+ const out = new Uint8Array(bin.length);
19937
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
19938
+ return out;
19939
+ }
19940
+ async function importPublicKey(spkiBase64) {
19941
+ return crypto.subtle.importKey("spki", fromBase64(spkiBase64), { name: "ECDSA", namedCurve: "P-256" }, false, [
19942
+ "verify"
19943
+ ]);
19944
+ }
19945
+ async function verifyMessage(publicKeySpkiBase64, message, signatureBase64) {
19946
+ try {
19947
+ const key = await importPublicKey(publicKeySpkiBase64);
19948
+ const sig = fromBase64(signatureBase64);
19949
+ if (sig.byteLength !== 64) return false;
19950
+ return await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, sig, message);
19951
+ } catch {
19952
+ return false;
19953
+ }
19954
+ }
19955
+ async function verifyManifestSignature(publicKeySpkiBase64, payload, signatureBase64) {
19956
+ try {
19957
+ return await verifyMessage(publicKeySpkiBase64, new TextEncoder().encode(payload), signatureBase64);
19958
+ } catch {
19959
+ return false;
19960
+ }
19961
+ }
19933
19962
 
19934
19963
  // ../protocol/src/hkp.ts
19935
19964
  var HKP_MAGIC = "HKP1";
@@ -19961,6 +19990,94 @@ function validateHkpHeader(value) {
19961
19990
  return h;
19962
19991
  }
19963
19992
 
19993
+ // ../protocol/src/debug.ts
19994
+ var Logpoint = external_exports.object({
19995
+ id: external_exports.string().regex(/^lp[0-9]{1,3}$/),
19996
+ /** Path from the project root, e.g. src/screens/CartScreen.tsx */
19997
+ file: external_exports.string().min(1).max(300).regex(/^[A-Za-z0-9_@+\-./ ]+$/).refine((f) => !f.split("/").includes("..") && !f.startsWith("/"), "file must be a path inside the project"),
19998
+ line: external_exports.number().int().min(1).max(1e6),
19999
+ /** JavaScript expressions evaluated at that line, e.g. cart.items.length */
20000
+ expressions: external_exports.array(external_exports.string().min(1).max(200).regex(/^[^\n\r]+$/)).min(1).max(10)
20001
+ });
20002
+ var DebugLogBatch = external_exports.object({
20003
+ channel: external_exports.string().max(128),
20004
+ deviceId: external_exports.string().max(128),
20005
+ sessionId: external_exports.string().max(64),
20006
+ logs: external_exports.array(
20007
+ external_exports.object({
20008
+ t: external_exports.number().int(),
20009
+ lp: external_exports.string().max(16),
20010
+ data: external_exports.record(external_exports.string(), external_exports.unknown())
20011
+ })
20012
+ ).min(1).max(50)
20013
+ });
20014
+ var MAX_DEBUG_LOG_BYTES = 64 * 1024;
20015
+ var ReleaseChange = external_exports.object({
20016
+ sha: external_exports.string().regex(/^[0-9a-f]{40}$/),
20017
+ pr: external_exports.number().int().positive().nullable(),
20018
+ title: external_exports.string().max(300),
20019
+ author: external_exports.string().max(100).nullable().optional(),
20020
+ /** Merge commits are reverted against their first parent. */
20021
+ merge: external_exports.boolean().optional(),
20022
+ files: external_exports.array(external_exports.string().max(300)).max(500),
20023
+ /** For merge commits: the pull request's own commits (blame hits on these belong to the PR). */
20024
+ commits: external_exports.array(external_exports.string().regex(/^[0-9a-f]{40}$/)).max(500).optional()
20025
+ });
20026
+ var ReleaseSource = external_exports.object({
20027
+ commit: external_exports.string().regex(/^[0-9a-f]{40}$/),
20028
+ baseCommit: external_exports.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
20029
+ branch: external_exports.string().max(200).nullable().optional(),
20030
+ /** owner/name on GitHub, when known. */
20031
+ repo: external_exports.string().max(200).nullable().optional(),
20032
+ changes: external_exports.array(ReleaseChange).max(300)
20033
+ });
20034
+ var Suspect = external_exports.object({
20035
+ sha: external_exports.string().regex(/^[0-9a-f]{40}$/),
20036
+ pr: external_exports.number().int().positive().nullable(),
20037
+ title: external_exports.string().max(300),
20038
+ /** Share of the weighted evidence (0..1). */
20039
+ share: external_exports.number().min(0).max(1),
20040
+ evidence: external_exports.array(
20041
+ external_exports.object({
20042
+ file: external_exports.string().max(300),
20043
+ line: external_exports.number().int().nonnegative(),
20044
+ message: external_exports.string().max(300),
20045
+ count: external_exports.number().int().nonnegative(),
20046
+ /** blame: the failing line was changed by this commit; file: the commit changed a file in the stack. */
20047
+ how: external_exports.enum(["blame", "file"])
20048
+ })
20049
+ ).max(20)
20050
+ });
20051
+ function parseStack(stack) {
20052
+ const frames = [];
20053
+ for (const raw of stack.split("\n")) {
20054
+ const l = raw.trim();
20055
+ if (!l) continue;
20056
+ let m = /^at (?:(.+?) )?\(?(?:address at )?(.+?):(\d+):(\d+)\)?$/.exec(l);
20057
+ if (m) {
20058
+ frames.push({ fn: m[1] && m[1] !== "anonymous" ? m[1] : null, file: m[2], line: Number(m[3]), column: Number(m[4]) });
20059
+ continue;
20060
+ }
20061
+ m = /^(?:(.*?)@)?(.+?):(\d+):(\d+)$/.exec(l);
20062
+ if (m && !l.startsWith("at ")) frames.push({ fn: m[1] || null, file: m[2], line: Number(m[3]), column: Number(m[4]) });
20063
+ }
20064
+ return frames;
20065
+ }
20066
+
20067
+ // ../protocol/src/provenance.ts
20068
+ var PROVENANCE_AUDIENCE = "healkite";
20069
+ var ProvenancePolicy = external_exports.object({
20070
+ required: external_exports.boolean(),
20071
+ /** owner/name */
20072
+ repo: external_exports.string().regex(/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/),
20073
+ /** Workflow files allowed to publish, e.g. [".github/workflows/release.yml"]. Empty = any in the repo. */
20074
+ workflows: external_exports.array(external_exports.string().regex(/^\.github\/workflows\/[A-Za-z0-9_.-]+\.ya?ml$/)).max(10).default([]),
20075
+ /** Git refs allowed to publish, e.g. ["refs/heads/main"]. Empty = any. */
20076
+ refs: external_exports.array(external_exports.string().regex(/^refs\/(heads|tags)\/[A-Za-z0-9_./*-]{1,200}$/)).max(10).default([]),
20077
+ /** Approvals (other than the author) the commit's pull request needs. 0 = not checked. */
20078
+ minApprovals: external_exports.number().int().min(0).max(5).default(0)
20079
+ });
20080
+
19964
20081
  // ../core/src/publish-release.ts
19965
20082
  async function publishRelease(deps, input2) {
19966
20083
  const clock = deps.clock ?? systemClock;
@@ -23611,6 +23728,12 @@ async function buildBundle(opts) {
23611
23728
  await mkdir3(opts.outDir, { recursive: true });
23612
23729
  const entry = ENTRY_NAME[opts.platform];
23613
23730
  const bundlePath = join3(opts.outDir, entry);
23731
+ const mapsDir = `${opts.outDir}.maps`;
23732
+ const metroMap = join3(mapsDir, `${entry}.metro.map`);
23733
+ if (opts.sourcemap) {
23734
+ await rm2(mapsDir, { recursive: true, force: true });
23735
+ await mkdir3(mapsDir, { recursive: true });
23736
+ }
23614
23737
  const expo = isExpoProject(opts.projectDir);
23615
23738
  const entryArgs = expo && !existsSync(join3(opts.projectDir, opts.entryFile)) ? [] : ["--entry-file", opts.entryFile];
23616
23739
  opts.log(`Bundling ${opts.platform} JS with ${expo ? "Expo (export:embed)" : "Metro"}\u2026`);
@@ -23629,18 +23752,37 @@ async function buildBundle(opts) {
23629
23752
  bundlePath,
23630
23753
  "--assets-dest",
23631
23754
  opts.outDir,
23632
- "--reset-cache"
23755
+ "--reset-cache",
23756
+ ...opts.sourcemap ? ["--sourcemap-output", metroMap] : []
23633
23757
  ],
23634
- opts.projectDir
23758
+ opts.projectDir,
23759
+ opts.env
23635
23760
  );
23636
23761
  if (opts.hermes) {
23637
23762
  const hermesc = findHermesc(opts.projectDir);
23638
23763
  opts.log(`Compiling to Hermes bytecode (${hermesc})\u2026`);
23639
23764
  const hbc = `${bundlePath}.hbc`;
23640
- await run(hermesc, ["-emit-binary", "-O", "-max-diagnostic-width=80", "-out", hbc, bundlePath], opts.projectDir);
23765
+ await run(hermesc, ["-emit-binary", "-O", "-max-diagnostic-width=80", ...opts.sourcemap ? ["-output-source-map"] : [], "-out", hbc, bundlePath], opts.projectDir);
23641
23766
  await rename2(hbc, bundlePath);
23767
+ if (opts.sourcemap) {
23768
+ const hbcMap = `${hbc}.map`;
23769
+ const composed = join3(mapsDir, `${entry}.map`);
23770
+ const composer = findComposer(opts.projectDir);
23771
+ if (composer && existsSync(hbcMap)) {
23772
+ await run("node", [composer, metroMap, hbcMap, "-o", composed], opts.projectDir);
23773
+ await rm2(hbcMap, { force: true });
23774
+ return { dir: opts.outDir, entry, sourcemap: composed };
23775
+ }
23776
+ await rm2(hbcMap, { force: true });
23777
+ opts.log("Couldn't compose the Hermes source map (react-native/scripts/compose-source-maps.js not found); using function names only.");
23778
+ return { dir: opts.outDir, entry };
23779
+ }
23642
23780
  }
23643
- return { dir: opts.outDir, entry };
23781
+ return { dir: opts.outDir, entry, ...opts.sourcemap ? { sourcemap: metroMap } : {} };
23782
+ }
23783
+ function findComposer(projectDir) {
23784
+ const roots = [projectDir, join3(projectDir, ".."), join3(projectDir, "../..")];
23785
+ return roots.map((r) => join3(r, "node_modules/react-native/scripts/compose-source-maps.js")).find((p) => existsSync(p)) ?? null;
23644
23786
  }
23645
23787
  function findHermesc(projectDir) {
23646
23788
  const os = process.platform === "darwin" ? "osx-bin" : process.platform === "win32" ? "win64-bin" : "linux64-bin";
@@ -23658,9 +23800,9 @@ Pass --no-hermes for JSC apps.`);
23658
23800
  }
23659
23801
  return found;
23660
23802
  }
23661
- function run(cmd, args, cwd) {
23803
+ function run(cmd, args, cwd, env) {
23662
23804
  return new Promise((resolve3, reject) => {
23663
- const child = spawn(cmd, args, { cwd, stdio: "inherit", env: process.env });
23805
+ const child = spawn(cmd, args, { cwd, stdio: "inherit", env: env ? { ...process.env, ...env } : process.env });
23664
23806
  child.on("error", reject);
23665
23807
  child.on(
23666
23808
  "exit",
@@ -24152,6 +24294,264 @@ async function buildPatches(opts) {
24152
24294
  return out;
24153
24295
  }
24154
24296
 
24297
+ // src/lib/sourcemap.ts
24298
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
24299
+ var B64_INDEX = new Map([...B64].map((c, i) => [c, i]));
24300
+ function decodeVlq(segment) {
24301
+ const out = [];
24302
+ let value = 0;
24303
+ let shift = 0;
24304
+ for (const ch of segment) {
24305
+ const digit = B64_INDEX.get(ch);
24306
+ if (digit === void 0) throw new Error(`invalid base64 VLQ character ${ch}`);
24307
+ value += (digit & 31) << shift;
24308
+ if (digit & 32) shift += 5;
24309
+ else {
24310
+ out.push(value & 1 ? -(value >>> 1) : value >>> 1);
24311
+ value = 0;
24312
+ shift = 0;
24313
+ }
24314
+ }
24315
+ return out;
24316
+ }
24317
+ var SourceMap = class _SourceMap {
24318
+ lines = [];
24319
+ sources;
24320
+ sections = null;
24321
+ constructor(raw) {
24322
+ const map2 = typeof raw === "string" ? JSON.parse(raw) : raw;
24323
+ if (map2.sections) {
24324
+ this.sources = [];
24325
+ this.sections = map2.sections.map((s) => ({ line: s.offset.line, column: s.offset.column, map: new _SourceMap(s.map) }));
24326
+ return;
24327
+ }
24328
+ const root = map2.sourceRoot ? map2.sourceRoot.replace(/\/?$/, "/") : "";
24329
+ this.sources = map2.sources.map((s) => root && !/^([a-z]+:|\/)/.test(s) ? root + s : s);
24330
+ let source = 0;
24331
+ let origLine = 0;
24332
+ let origCol = 0;
24333
+ const mappings = map2.mappings ?? "";
24334
+ for (const lineText of mappings.split(";")) {
24335
+ const segs = [];
24336
+ let col = 0;
24337
+ if (lineText) {
24338
+ for (const segText of lineText.split(",")) {
24339
+ const f = decodeVlq(segText);
24340
+ col += f[0] ?? 0;
24341
+ if (f.length >= 4) {
24342
+ source += f[1];
24343
+ origLine += f[2];
24344
+ origCol += f[3];
24345
+ segs.push({ col, source, line: origLine });
24346
+ }
24347
+ }
24348
+ }
24349
+ this.lines.push(segs);
24350
+ }
24351
+ }
24352
+ /** line is 1-based, column 0-based (as in stack traces from Hermes: "1:20481" means bytecode offset 20481). */
24353
+ lookup(line, column) {
24354
+ if (this.sections) {
24355
+ let hit = null;
24356
+ for (const s2 of this.sections) {
24357
+ if (s2.line + 1 < line || s2.line + 1 === line && s2.column <= column) hit = s2;
24358
+ }
24359
+ if (!hit) return null;
24360
+ return hit.map.lookup(line - hit.line, line - 1 === hit.line ? column - hit.column : column);
24361
+ }
24362
+ const segs = this.lines[line - 1];
24363
+ if (!segs?.length) return null;
24364
+ let lo = 0;
24365
+ let hi = segs.length - 1;
24366
+ let best = -1;
24367
+ while (lo <= hi) {
24368
+ const mid = lo + hi >> 1;
24369
+ if (segs[mid].col <= column) {
24370
+ best = mid;
24371
+ lo = mid + 1;
24372
+ } else hi = mid - 1;
24373
+ }
24374
+ if (best < 0) return null;
24375
+ const s = segs[best];
24376
+ const source = this.sources[s.source];
24377
+ return source === void 0 ? null : { source, line: s.line + 1 };
24378
+ }
24379
+ };
24380
+ function projectRelative(source, projectDir) {
24381
+ let s = source.replace(/^webpack:\/\/\/?|^file:\/\//, "");
24382
+ const root = projectDir.replace(/\/+$/, "");
24383
+ if (s.startsWith(`${root}/`)) s = s.slice(root.length + 1);
24384
+ s = s.replace(/^(\.\/)+/, "");
24385
+ if (s.startsWith("/") || s.startsWith("..") || s.includes("node_modules/") || s.startsWith("__prelude__") || s.includes("\0")) return null;
24386
+ return s;
24387
+ }
24388
+
24389
+ // src/lib/blame.ts
24390
+ var FRAMES = 8;
24391
+ var FILE_WEIGHT = 0.3;
24392
+ var NAME_WEIGHT = 0.15;
24393
+ async function findSuspects(errors, changes, deps) {
24394
+ const owner = /* @__PURE__ */ new Map();
24395
+ for (const c of changes) {
24396
+ owner.set(c.sha, c);
24397
+ for (const sha of c.commits ?? []) owner.set(sha, c);
24398
+ }
24399
+ const score = /* @__PURE__ */ new Map();
24400
+ const evidence = /* @__PURE__ */ new Map();
24401
+ const add = (c, w, e) => {
24402
+ score.set(c.sha, (score.get(c.sha) ?? 0) + w);
24403
+ const list = evidence.get(c.sha) ?? [];
24404
+ const same = list.find((x) => x.file === e.file && x.line === e.line && x.message === e.message);
24405
+ if (same) same.count = Math.max(same.count, e.count);
24406
+ else if (list.length < 20) list.push(e);
24407
+ evidence.set(c.sha, list);
24408
+ };
24409
+ const blameCache = /* @__PURE__ */ new Map();
24410
+ let mapped = 0;
24411
+ for (const err of errors) {
24412
+ if (!err.stack) continue;
24413
+ const errWeight = err.count * (err.isNew ? 1 : 0.25);
24414
+ const frames = parseStack(err.stack).slice(0, FRAMES);
24415
+ for (const [i, f] of frames.entries()) {
24416
+ const w = errWeight / (i + 1) ** 2;
24417
+ let file2 = null;
24418
+ let line = 0;
24419
+ const pos = deps.map?.lookup(f.line, f.column) ?? null;
24420
+ if (pos) {
24421
+ file2 = projectRelative(pos.source, deps.projectDir);
24422
+ line = pos.line;
24423
+ } else if (!/\.(jsbundle|bundle)$/.test(f.file)) {
24424
+ file2 = projectRelative(f.file, deps.projectDir);
24425
+ line = f.line;
24426
+ }
24427
+ const message = err.message.slice(0, 300);
24428
+ if (file2) {
24429
+ mapped++;
24430
+ const key = `${file2}:${line}`;
24431
+ if (!blameCache.has(key)) blameCache.set(key, deps.blame(file2, line));
24432
+ const sha = await blameCache.get(key);
24433
+ const blamed = sha ? owner.get(sha) : void 0;
24434
+ if (blamed) {
24435
+ add(blamed, w, { file: file2, line, message, count: err.count, how: "blame" });
24436
+ continue;
24437
+ }
24438
+ for (const c of changes) if (c.files.includes(file2)) add(c, w * FILE_WEIGHT, { file: file2, line, message, count: err.count, how: "file" });
24439
+ } else if (f.fn && /^[A-Za-z_$][\w$]{2,}$/.test(f.fn)) {
24440
+ const fn = f.fn;
24441
+ for (const c of changes) {
24442
+ const hit = c.files.find((p) => (p.split("/").pop() ?? "").replace(/\.[jt]sx?$/, "") === fn);
24443
+ if (hit) add(c, w * NAME_WEIGHT, { file: hit, line: 0, message, count: err.count, how: "file" });
24444
+ }
24445
+ }
24446
+ }
24447
+ }
24448
+ const total = [...score.values()].reduce((a, b) => a + b, 0);
24449
+ const suspects = [...score.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([sha, s]) => {
24450
+ const c = owner.get(sha);
24451
+ return { sha, pr: c.pr, title: c.title, share: total ? Math.round(s / total * 100) / 100 : 0, evidence: (evidence.get(sha) ?? []).sort((a, b) => b.count - a.count) };
24452
+ });
24453
+ return { suspects, summary: summarize(suspects, errors), mapped };
24454
+ }
24455
+ function summarize(suspects, errors) {
24456
+ const fresh = errors.filter((e2) => e2.isNew);
24457
+ if (!fresh.length) return "No new errors on this release. If it was stopped by a business metric (for example checkouts), review the changes below.";
24458
+ const top = suspects[0];
24459
+ if (!top) return `${fresh.length} new error${fresh.length === 1 ? "" : "s"}, but none point at code changed in this release. The cause may be data, a dependency or native code.`;
24460
+ const name = top.pr ? `PR #${top.pr} \u201C${top.title}\u201D` : `Commit ${top.sha.slice(0, 7)} \u201C${top.title}\u201D`;
24461
+ const e = top.evidence[0];
24462
+ const where = e ? e.how === "blame" ? `changed ${e.file}:${e.line}, where` : `touched ${e.file}, which appears in the stack of` : "matches";
24463
+ const n = e?.count ?? 0;
24464
+ return `${name} ${where} ${n} crash${n === 1 ? "" : "es"} ${e ? `(${e.message.slice(0, 120)})` : ""} happen${n === 1 ? "s" : ""}. ${Math.round(top.share * 100)}% of the evidence points at it.`.replace(/\s+/g, " ").trim();
24465
+ }
24466
+
24467
+ // src/lib/git.ts
24468
+ import { execFile } from "node:child_process";
24469
+ import { promisify } from "node:util";
24470
+ var exec = promisify(execFile);
24471
+ async function git(cwd, args, opts = {}) {
24472
+ try {
24473
+ const { stdout } = await exec("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 });
24474
+ return stdout;
24475
+ } catch (e) {
24476
+ if (opts.allowFail) return "";
24477
+ const err = e;
24478
+ throw new Error(`git ${args[0]} failed: ${(err.stderr || err.message).trim().split("\n").slice(-3).join(" ")}`);
24479
+ }
24480
+ }
24481
+ async function gitOk(cwd, args) {
24482
+ return exec("git", args, { cwd }).then(
24483
+ () => true,
24484
+ () => false
24485
+ );
24486
+ }
24487
+ async function isGitRepo(cwd) {
24488
+ return (await git(cwd, ["rev-parse", "--is-inside-work-tree"], { allowFail: true })).trim() === "true";
24489
+ }
24490
+ async function headCommit(cwd) {
24491
+ return (await git(cwd, ["rev-parse", "HEAD"])).trim();
24492
+ }
24493
+ async function hasCommit(cwd, sha) {
24494
+ return (await git(cwd, ["cat-file", "-t", sha], { allowFail: true })).trim() === "commit";
24495
+ }
24496
+ async function githubRepo(cwd) {
24497
+ const url2 = (await git(cwd, ["remote", "get-url", "origin"], { allowFail: true })).trim();
24498
+ const m = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url2);
24499
+ return m ? m[1] : null;
24500
+ }
24501
+ function prNumber(subject) {
24502
+ const m = /^Merge pull request #(\d+)/.exec(subject) ?? /\(#(\d+)\)\s*$/.exec(subject);
24503
+ return m ? Number(m[1]) : null;
24504
+ }
24505
+ async function releaseSource(cwd, baseCommit, log2) {
24506
+ if (!await isGitRepo(cwd)) return null;
24507
+ const commit = await headCommit(cwd);
24508
+ const branch = (await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"], { allowFail: true })).trim() || null;
24509
+ const repo = await githubRepo(cwd);
24510
+ let base = baseCommit;
24511
+ if (base && !await hasCommit(cwd, base)) {
24512
+ log2(`The previous release's commit ${base.slice(0, 8)} isn't in this clone (shallow checkout?). Use fetch-depth: 0 in CI so Healkite can list this release's changes.`);
24513
+ base = null;
24514
+ }
24515
+ let changes = [];
24516
+ if (base && base !== commit) {
24517
+ const ancestor = await exec("git", ["merge-base", "--is-ancestor", base, commit], { cwd }).then(
24518
+ () => true,
24519
+ () => false
24520
+ );
24521
+ if (!ancestor) log2(`The previous release (${base.slice(0, 8)}) isn't an ancestor of HEAD; listing changes since the branches split.`);
24522
+ const from = ancestor ? base : (await git(cwd, ["merge-base", base, commit])).trim();
24523
+ changes = await changesBetween(cwd, from, commit);
24524
+ }
24525
+ return { commit, baseCommit: base, branch: branch === "HEAD" ? null : branch, repo, changes };
24526
+ }
24527
+ async function changesBetween(cwd, from, to) {
24528
+ const SEP = "";
24529
+ const END = "";
24530
+ const out = await git(cwd, ["log", "--first-parent", `--format=%H${SEP}%P${SEP}%an${SEP}%s${SEP}%b${END}`, "-n", "300", `${from}..${to}`]);
24531
+ const changes = [];
24532
+ for (const rec of out.split(END)) {
24533
+ const t = rec.replace(/^\n+/, "");
24534
+ if (!t.trim()) continue;
24535
+ const [sha, parents, author, subject, body] = t.split(SEP);
24536
+ const ps = parents.trim().split(" ").filter(Boolean);
24537
+ const merge2 = ps.length > 1;
24538
+ const pr = prNumber(subject);
24539
+ const title = (merge2 && pr ? body.trim().split("\n")[0] : subject) || subject;
24540
+ const files = ps[0] ? (await git(cwd, ["diff", "--name-only", ps[0], sha])).split("\n").filter(Boolean).slice(0, 500) : [];
24541
+ const commits = merge2 && ps[1] ? (await git(cwd, ["rev-list", "-n", "500", `${ps[0]}..${ps[1]}`])).split("\n").filter(Boolean) : void 0;
24542
+ changes.push({ sha, pr, title: title.slice(0, 300), author: author.slice(0, 100) || null, merge: merge2 || void 0, files, ...commits ? { commits } : {} });
24543
+ }
24544
+ return changes;
24545
+ }
24546
+ async function blameLine(cwd, commit, file2, line) {
24547
+ const out = await git(cwd, ["blame", "-L", `${line},${line}`, "--porcelain", commit, "--", file2], { allowFail: true });
24548
+ const sha = out.split(" ")[0] ?? "";
24549
+ return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
24550
+ }
24551
+ async function isClean(cwd) {
24552
+ return (await git(cwd, ["status", "--porcelain", "--untracked-files=no"])).trim() === "";
24553
+ }
24554
+
24155
24555
  // ../../node_modules/aws4fetch/dist/aws4fetch.esm.mjs
24156
24556
  /**
24157
24557
  * @license MIT <https://opensource.org/licenses/MIT>
@@ -24594,7 +24994,7 @@ async function api() {
24594
24994
  if (!config2) throw new Error("Not logged in. Run `healkite login --api-url <url> --token <hk_\u2026>` or set HEALKITE_API_URL/HEALKITE_TOKEN.");
24595
24995
  return new ApiClient(config2);
24596
24996
  }
24597
- var program2 = new Command().name("healkite").description("Self-healing over-the-air updates for React Native").version("0.1.1");
24997
+ var program2 = new Command().name("healkite").description("Self-healing over-the-air updates for React Native").version("0.2.0");
24598
24998
  program2.command("login").description("Save API credentials to ~/.healkite/config.json").requiredOption("--api-url <url>", "Healkite API URL, e.g. https://api.healkite.com").requiredOption("--token <token>", "access key (hk_\u2026)").action(async (o) => {
24599
24999
  const client = new ApiClient({ apiUrl: o.apiUrl, token: o.token });
24600
25000
  await client.request("GET", "/v1/apps");
@@ -24696,7 +25096,7 @@ channels.command("create").argument("<name>").requiredOption("--app <appId>").ac
24696
25096
  log(`Created channel ${name}. Put this key in your app config (HealkiteChannel / healkite_channel):`);
24697
25097
  console.log(ch.key);
24698
25098
  });
24699
- program2.command("release").description("Bundle the app's JS + assets and publish it to a channel").addOption(platformOption()).requiredOption("-c, --channel <key>", "channel key").requiredOption("-r, --runtime-version <version>", "binary/runtime version this bundle targets").option("--project <dir>", "React Native project directory", ".").option("--entry-file <file>", "JS entry file", "index.js").option("--no-hermes", "skip Hermes bytecode compilation (JSC apps)").option("--rollout <pct>", "percentage of devices (1-100)", pct).option("--mandatory", "mark the update as mandatory", false).option("-d, --description <text>", "release notes").option("--sign <pem>", "sign with this private key (or set HEALKITE_SIGNING_KEY / HEALKITE_SIGNING_KEY_PATH)").option("--patch-from <n>", "diff against the last N distinct bundles on this target (0 disables)", "3").option("--guarded", "Guarded Release: start small, auto-advance when healthy, auto-halt on crashes").option("--guard-steps <list>", "rollout steps, e.g. 1,10,50,100").option("--guard-soak <duration>", "time per step, e.g. 30m, 2h, 0s").option("--guard-min-installs <n>", "installs needed per step before advancing").option("--guard-metric <event:maxDropPct...>", "halt if trackEvent(event) per session drops > maxDropPct % vs previous release, e.g. checkout_success:20").option("--at <time>", 'go live later: +2h, "2026-11-20 00:00" (local time) or an ISO time').option("--until <time>", "campaign end: the release turns itself off and devices go back to the previous one").option("--device <id...>", "only these devices get it (support fixes, testers); everyone else is untouched").option("--hotfix", "instant hotfix: mandatory + silent push so devices update now (needs Firebase connected)").option("--push", "silent push so devices check now (not mandatory)").option("--experiment <name>", "A/B experiment: compare this release (--rollout %) with what everyone else runs").option("--metric <event...>", "with --experiment: trackEvent names to compare per session (first = primary)").option("--max-size <size>", "fail before uploading if the bundle is bigger, e.g. 2MB").option("--max-growth <pct>", "fail before uploading if the bundle grew more than this % vs the previous release").option("--out <dir>", "local mode: write to a CDN directory instead of the API").action(async (o) => void await releaseAction(o));
25099
+ program2.command("release").description("Bundle the app's JS + assets and publish it to a channel").addOption(platformOption()).requiredOption("-c, --channel <key>", "channel key").requiredOption("-r, --runtime-version <version>", "binary/runtime version this bundle targets").option("--project <dir>", "React Native project directory", ".").option("--entry-file <file>", "JS entry file", "index.js").option("--no-hermes", "skip Hermes bytecode compilation (JSC apps)").option("--rollout <pct>", "percentage of devices (1-100)", pct).option("--mandatory", "mark the update as mandatory", false).option("-d, --description <text>", "release notes").option("--sign <pem>", "sign with this private key (or set HEALKITE_SIGNING_KEY / HEALKITE_SIGNING_KEY_PATH)").option("--patch-from <n>", "diff against the last N distinct bundles on this target (0 disables)", "3").option("--guarded", "Guarded Release: start small, auto-advance when healthy, auto-halt on crashes").option("--guard-steps <list>", "rollout steps, e.g. 1,10,50,100").option("--guard-soak <duration>", "time per step, e.g. 30m, 2h, 0s").option("--guard-min-installs <n>", "installs needed per step before advancing").option("--guard-metric <event:maxDropPct...>", "halt if trackEvent(event) per session drops > maxDropPct % vs previous release, e.g. checkout_success:20").option("--at <time>", 'go live later: +2h, "2026-11-20 00:00" (local time) or an ISO time').option("--until <time>", "campaign end: the release turns itself off and devices go back to the previous one").option("--device <id...>", "only these devices get it (support fixes, testers); everyone else is untouched").option("--hotfix", "instant hotfix: mandatory + silent push so devices update now (needs Firebase connected)").option("--live", "live patch: like --hotfix, and apps reload at a safe moment keeping the state they registered (screen, cart, forms)").option("--push", "silent push so devices check now (not mandatory)").option("--experiment <name>", "A/B experiment: compare this release (--rollout %) with what everyone else runs").option("--metric <event...>", "with --experiment: trackEvent names to compare per session (first = primary)").option("--max-size <size>", "fail before uploading if the bundle is bigger, e.g. 2MB").option("--max-growth <pct>", "fail before uploading if the bundle grew more than this % vs the previous release").option("--out <dir>", "local mode: write to a CDN directory instead of the API").action(async (o) => void await releaseAction(o));
24700
25100
  var codepush = program2.command("codepush").description("CodePush / App Center-compatible commands for migrating scripts and CI (a deployment is a Healkite channel)");
24701
25101
  async function cpApp(nameOrId) {
24702
25102
  const { apps: apps2 } = await (await api()).request("GET", "/v1/summary");
@@ -25044,6 +25444,225 @@ program2.command("inspect").description("Verify and list the contents of an .hkb
25044
25444
  }
25045
25445
  log(`${files.size} files verified`);
25046
25446
  });
25447
+ var debugCmd = program2.command("debug").description("Production debugging: logpoint builds for chosen devices");
25448
+ debugCmd.command("build").description("Build the release those devices run with the session's logpoints and send it to them only (run in CI or locally)").argument("<session>", "debug session id (dbg_\u2026), from the dashboard").option("--project <dir>", "React Native project directory", ".").option("--entry-file <file>", "JS entry file", "index.js").option("--no-hermes", "skip Hermes bytecode compilation (JSC apps)").option("--sign <pem>", "sign with this private key (or HEALKITE_SIGNING_KEY)").action(async (sessionId, o) => {
25449
+ const client = await api();
25450
+ const projectDir = resolve2(o.project);
25451
+ const spec = await client.request("GET", `/v1/debug-sessions/${sessionId}/spec`);
25452
+ const fail = async (message) => {
25453
+ await client.request("POST", `/v1/debug-sessions/${sessionId}/status`, { status: "failed", error: message }).catch(() => {
25454
+ });
25455
+ throw new Error(message);
25456
+ };
25457
+ if (!await hasLogpointPlugin(projectDir)) {
25458
+ await fail('Add the Healkite Babel plugin once: in babel.config.js, plugins: ["react-native-healkite/babel"]. It does nothing in normal builds.');
25459
+ }
25460
+ if (spec.baseCommit && await isGitRepo(projectDir)) {
25461
+ const head = await headCommit(projectDir);
25462
+ if (head !== spec.baseCommit) log(`Note: building ${head.slice(0, 8)}, but the devices run ${spec.baseCommit.slice(0, 8)}. Check out that commit so line numbers match.`);
25463
+ }
25464
+ for (const lp of spec.logpoints) {
25465
+ if (!existsSync3(join5(projectDir, lp.file))) await fail(`${lp.file} doesn't exist in this checkout`);
25466
+ }
25467
+ await client.request("POST", `/v1/debug-sessions/${sessionId}/status`, { status: "building" });
25468
+ log(`Debug session ${sessionId}: ${spec.logpoints.length} logpoint(s) for ${spec.devices.length} device(s)`);
25469
+ try {
25470
+ const rel = await releaseAction({
25471
+ platform: spec.platform,
25472
+ channel: spec.channelKey,
25473
+ runtimeVersion: spec.runtimeVersion,
25474
+ project: o.project,
25475
+ entryFile: o.entryFile,
25476
+ hermes: o.hermes,
25477
+ sign: o.sign,
25478
+ patchFrom: "3",
25479
+ device: spec.devices,
25480
+ until: new Date(spec.expiresAt).toISOString(),
25481
+ description: `Debug session ${sessionId} (${spec.logpoints.map((l) => `${l.file}:${l.line}`).join(", ")})`.slice(0, 2e3),
25482
+ skipSource: true,
25483
+ buildEnv: { HEALKITE_LOGPOINTS: JSON.stringify({ sessionId, logpoints: spec.logpoints }), HEALKITE_PROJECT_ROOT: projectDir }
25484
+ });
25485
+ if (!rel) throw new Error("nothing was published");
25486
+ await client.request("POST", `/v1/debug-sessions/${sessionId}/attach`, { releaseId: rel.id });
25487
+ log(`Live. The devices get it on their next launch; values appear in the dashboard and with \`healkite debug logs ${sessionId} --follow\`.`);
25488
+ log(`It turns itself off at ${new Date(spec.expiresAt).toLocaleString()} (or when you end the session).`);
25489
+ } catch (e) {
25490
+ await fail(e.message.slice(0, 400));
25491
+ }
25492
+ });
25493
+ debugCmd.command("logs").description("Print the values captured by a debug session").argument("<session>", "debug session id").option("-f, --follow", "keep printing new values").action(async (sessionId, o) => {
25494
+ const client = await api();
25495
+ let after = null;
25496
+ for (; ; ) {
25497
+ const r = await client.request(
25498
+ "GET",
25499
+ `/v1/debug-sessions/${sessionId}${after ? `?after=${after}` : ""}`
25500
+ );
25501
+ const where = new Map(r.session.logpoints.map((l) => [l.id, `${l.file}:${l.line}`]));
25502
+ for (const l of r.logs) {
25503
+ console.log(`${new Date(l.ts).toLocaleTimeString()} ${l.deviceId.slice(0, 8)} ${where.get(l.logpointId) ?? l.logpointId} ${l.data}`);
25504
+ after = l.id;
25505
+ }
25506
+ if (!o.follow || r.session.status === "ended" || r.session.status === "failed") break;
25507
+ await new Promise((res) => setTimeout(res, 3e3));
25508
+ }
25509
+ });
25510
+ async function hasLogpointPlugin(projectDir) {
25511
+ for (const f of ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", ".babelrc", ".babelrc.js", "package.json"]) {
25512
+ const p = join5(projectDir, f);
25513
+ if (existsSync3(p) && (await readFile5(p, "utf8")).includes("react-native-healkite/babel")) return true;
25514
+ }
25515
+ return false;
25516
+ }
25517
+ program2.command("blame").description("Find the change that broke a release: symbolicate its new errors and git-blame the failing lines (run at the release's commit)").argument("<release>", "release id").option("--project <dir>", "React Native project directory", ".").option("--entry-file <file>", "JS entry file", "index.js").option("--no-hermes", "skip Hermes bytecode compilation (JSC apps)").option("--sourcemap <file>", "use this source map instead of rebuilding the release").option("--no-build", "don't rebuild for a source map (match function names only)").option("--json", "print the result as JSON").action(async (releaseId, o) => {
25518
+ const client = await api();
25519
+ const projectDir = resolve2(o.project);
25520
+ const report = (body) => client.request("POST", `/v1/releases/${releaseId}/culprit`, body);
25521
+ try {
25522
+ const [{ source }, { release, errors }] = await Promise.all([
25523
+ client.request("GET", `/v1/releases/${releaseId}/source`),
25524
+ client.request(
25525
+ "GET",
25526
+ `/v1/releases/${releaseId}/errors`
25527
+ )
25528
+ ]);
25529
+ if (!source) throw new Error("this release has no git source; publish releases with the Healkite CLI from a git checkout");
25530
+ if (!await isGitRepo(projectDir)) throw new Error("run this inside the app's git checkout");
25531
+ const head = await headCommit(projectDir);
25532
+ if (head !== source.commit) log(`Note: HEAD is ${head.slice(0, 8)}; the release was built from ${source.commit.slice(0, 8)}. Line numbers are blamed at the release commit.`);
25533
+ let map2 = null;
25534
+ if (o.sourcemap) map2 = new SourceMap(await readFile5(o.sourcemap, "utf8"));
25535
+ else if (o.build && errors.some((e) => e.stack)) {
25536
+ log("Rebuilding the release with a source map\u2026");
25537
+ const built = await buildBundle({
25538
+ projectDir,
25539
+ platform: release.platform,
25540
+ entryFile: o.entryFile,
25541
+ outDir: join5(projectDir, ".healkite/blame", release.platform),
25542
+ hermes: o.hermes,
25543
+ sourcemap: true,
25544
+ log
25545
+ });
25546
+ const packed = await packDirectory(built);
25547
+ if (packed.sha256 !== release.bundleSha256) log("The rebuilt bundle differs from the released one (different dependencies or build settings); mapping may be approximate.");
25548
+ if (built.sourcemap) map2 = new SourceMap(await readFile5(built.sourcemap, "utf8"));
25549
+ }
25550
+ const result = await findSuspects(errors, source.changes, {
25551
+ map: map2,
25552
+ projectDir,
25553
+ blame: (file2, line) => blameLine(projectDir, source.commit, file2, line)
25554
+ });
25555
+ await report({ suspects: result.suspects, summary: result.summary });
25556
+ if (o.json) console.log(JSON.stringify(result));
25557
+ else {
25558
+ log(result.summary);
25559
+ for (const s of result.suspects) log(` ${Math.round(s.share * 100)}% ${s.pr ? `#${s.pr}` : s.sha.slice(0, 7)} ${s.title}`);
25560
+ }
25561
+ } catch (e) {
25562
+ await report({ error: e.message }).catch(() => {
25563
+ });
25564
+ throw e;
25565
+ }
25566
+ });
25567
+ var jobOptions = (cmd) => cmd.option("--project <dir>", "React Native project directory", ".").option("--entry-file <file>", "JS entry file", "index.js").option("--no-hermes", "skip Hermes bytecode compilation (JSC apps)").option("--sign <pem>", "sign with this private key (or HEALKITE_SIGNING_KEY)").option("--no-push", "don't push the branch (or open a pull request)");
25568
+ jobOptions(
25569
+ program2.command("revert").description("Roll back one change of a release: revert it at the release's commit, publish a guarded release, push a branch").argument("<job>", "rollback job id (rvt_\u2026), from the dashboard")
25570
+ ).action((jobId, o) => runChangeJob(jobId, o));
25571
+ jobOptions(
25572
+ program2.command("backport").description("Apply one change to an older app version still in use: cherry-pick it onto that version's release and publish it guarded").argument("<job>", "backport job id (bpt_\u2026), from the dashboard")
25573
+ ).action((jobId, o) => runChangeJob(jobId, o));
25574
+ async function runChangeJob(jobId, o) {
25575
+ const client = await api();
25576
+ const projectDir = resolve2(o.project);
25577
+ const spec = await client.request("GET", `/v1/reverts/${jobId}`);
25578
+ const update = (body) => client.request("PATCH", `/v1/reverts/${jobId}`, body);
25579
+ const backport = spec.job.kind === "backport";
25580
+ try {
25581
+ if (!spec.commit || !spec.change) throw new Error(backport ? "the older version's release has no git source" : "the release's git source is missing");
25582
+ if (!await isGitRepo(projectDir)) throw new Error("run this inside the app's git checkout");
25583
+ if (!await isClean(projectDir)) throw new Error("the working tree has uncommitted changes");
25584
+ await update({ status: "building" });
25585
+ const name = spec.change.pr ? `PR #${spec.change.pr}` : `commit ${spec.change.sha.slice(0, 7)}`;
25586
+ log(
25587
+ backport ? `Backporting ${name} (\u201C${spec.change.title}\u201D) to app version ${spec.release.runtimeVersion} (${spec.release.label})` : `Rolling back ${name} (\u201C${spec.change.title}\u201D) from ${spec.release.label}`
25588
+ );
25589
+ await git(projectDir, ["checkout", "--detach", spec.commit]);
25590
+ const hasIdentity = (await git(projectDir, ["config", "user.email"], { allowFail: true })).trim() !== "";
25591
+ const ident = hasIdentity ? [] : ["-c", "user.name=Healkite", "-c", "user.email=bot@healkite.com"];
25592
+ const pick2 = backport ? ["cherry-pick", "-x"] : ["revert", "--no-edit"];
25593
+ try {
25594
+ await git(projectDir, [...ident, ...pick2, ...spec.change.merge ? ["-m", "1"] : [], spec.change.sha]);
25595
+ } catch {
25596
+ const conflicted = (await git(projectDir, ["diff", "--name-only", "--diff-filter=U"], { allowFail: true })).split("\n").filter(Boolean);
25597
+ await git(projectDir, [backport ? "cherry-pick" : "revert", "--abort"], { allowFail: true });
25598
+ throw new Error(
25599
+ backport ? `${name} doesn't apply cleanly to app version ${spec.release.runtimeVersion}: that code has changed since (${conflicted.slice(0, 5).join(", ") || "conflict"}). Fix that version by hand.` : `${name} can't be reverted cleanly: later changes in ${spec.release.label} touch the same lines (${conflicted.slice(0, 5).join(", ") || "conflict"}). Roll back the whole release instead.`
25600
+ );
25601
+ }
25602
+ const rel = await releaseAction({
25603
+ platform: spec.release.platform,
25604
+ channel: spec.release.channelKey,
25605
+ runtimeVersion: spec.release.runtimeVersion,
25606
+ project: o.project,
25607
+ entryFile: o.entryFile,
25608
+ hermes: o.hermes,
25609
+ sign: o.sign,
25610
+ patchFrom: "3",
25611
+ guarded: true,
25612
+ // Same guard (steps and business metrics) as the release the change came from.
25613
+ guardConfig: spec.guard ?? void 0,
25614
+ description: (backport ? `${spec.release.label} + ${name} from ${spec.from?.label ?? "a newer release"}: ${spec.change.title}` : `${spec.release.label} without ${name}: ${spec.change.title}`).slice(0, 2e3)
25615
+ });
25616
+ if (!rel) throw new Error("nothing was published");
25617
+ let branch;
25618
+ let pullRequestUrl;
25619
+ if (o.push) {
25620
+ const what = spec.change.pr ? `pr-${spec.change.pr}` : spec.change.sha.slice(0, 7);
25621
+ branch = backport ? `healkite/backport-${what}-to-${spec.release.runtimeVersion}-${jobId.slice(-6)}` : `healkite/revert-${what}-${jobId.slice(-6)}`;
25622
+ if (await gitOk(projectDir, ["push", "origin", `HEAD:refs/heads/${branch}`])) {
25623
+ log(`Pushed ${branch}`);
25624
+ if (!backport) {
25625
+ pullRequestUrl = await openPullRequest(projectDir, branch, `Revert ${name}: ${spec.change.title}`, `Healkite rolled back ${name} from ${spec.release.label} and shipped the rest as ${rel.label} (guarded).
25626
+
25627
+ Merge this so the next release doesn't bring it back.`) ?? void 0;
25628
+ if (pullRequestUrl) log(`Pull request: ${pullRequestUrl}`);
25629
+ }
25630
+ }
25631
+ }
25632
+ await update({ status: "published", newReleaseId: rel.id, branch, pullRequestUrl });
25633
+ log(backport ? `Published ${rel.label} to app version ${spec.release.runtimeVersion}, guarded.` : `Published ${rel.label}: ${spec.release.label} without ${name}, as a guarded release.`);
25634
+ } catch (e) {
25635
+ await update({ status: "failed", error: e.message.slice(0, 450) }).catch(() => {
25636
+ });
25637
+ throw e;
25638
+ }
25639
+ }
25640
+ program2.command("provenance").description("Show and verify where a release was built (repository, commit, CI run, PR approvals)").argument("<release>", "release id").option("--json", "print the signed statement and signature").action(async (releaseId, o) => {
25641
+ const client = await api();
25642
+ const { provenance: p } = await client.request(
25643
+ "GET",
25644
+ `/v1/releases/${releaseId}/provenance`
25645
+ );
25646
+ if (!p) throw new Error("this release has no build provenance (it wasn't published from GitHub Actions with id-token: write)");
25647
+ const { manifestPublicKey } = await client.request("GET", "/v1/config");
25648
+ const ok = !!(p.signature && manifestPublicKey && await verifyManifestSignature(manifestPublicKey, p.raw, p.signature));
25649
+ if (o.json) return console.log(JSON.stringify({ statement: JSON.parse(p.raw), signature: p.signature, publicKey: manifestPublicKey, verified: ok }, null, 2));
25650
+ const s = JSON.parse(p.raw);
25651
+ log(`${ok ? "\u2714 Signature valid" : "\u2718 Signature NOT valid"} (server key ${manifestPublicKey?.slice(-12) ?? "missing"})`);
25652
+ log(`${s.release.label} \xB7 bundle ${s.bundle.sha256.slice(0, 12)}\u2026`);
25653
+ log(`Built from ${s.source.repo}@${s.source.commit.slice(0, 8)} (${s.source.ref}) by ${s.build.workflow}, run ${s.build.runUrl}`);
25654
+ log(s.review ? `PR #${s.review.pr}, approved by ${s.review.approvedBy.join(", ") || "nobody"}${s.review.mergedBy ? `, merged by ${s.review.mergedBy}` : ""}` : "No pull request review recorded");
25655
+ if (!ok) process.exitCode = 1;
25656
+ });
25657
+ async function openPullRequest(cwd, branch, title, body) {
25658
+ const { execFile: execFile2 } = await import("node:child_process");
25659
+ return new Promise((res) => {
25660
+ execFile2("gh", ["pr", "create", "--head", branch, "--title", title, "--body", body], { cwd }, (err, stdout) => {
25661
+ const url2 = stdout?.trim().split("\n").pop() ?? "";
25662
+ res(!err && /^https:\/\/github\.com\//.test(url2) ? url2 : null);
25663
+ });
25664
+ });
25665
+ }
25047
25666
  program2.parseAsync().catch((err) => {
25048
25667
  console.error(`\x1B[31mhealkite\x1B[0m ${err instanceof Error ? err.message : String(err)}`);
25049
25668
  process.exit(1);
@@ -25062,14 +25681,15 @@ async function releaseAction(o) {
25062
25681
  entryFile: o.entryFile,
25063
25682
  outDir: join5(projectDir, ".healkite/build", o.platform),
25064
25683
  hermes: o.hermes,
25065
- log
25684
+ log,
25685
+ env: o.buildEnv
25066
25686
  });
25067
25687
  const packed = await packDirectory(built);
25068
25688
  log(`Packed ${packed.index.files.length} files \u2192 ${(packed.hkb.byteLength / 1024).toFixed(1)} KB (sha256 ${packed.sha256.slice(0, 12)}\u2026)`);
25069
25689
  const signature = signingKey ? signBundle(signingKey, packed.sha256) : void 0;
25070
25690
  if (signature) log("Signed bundle (ECDSA P-256)");
25071
25691
  const patchFrom = Math.max(0, Number(o.patchFrom) || 0);
25072
- const guard = guardOptions(o);
25692
+ const guard = o.guardConfig ?? guardOptions(o);
25073
25693
  if (guard && o.out) throw new Error("--guarded needs the API (it is driven by the server)");
25074
25694
  if (guard && o.rollout !== void 0) throw new Error("use either --rollout or --guarded");
25075
25695
  if (o.out) {
@@ -25146,16 +25766,30 @@ async function releaseAction(o) {
25146
25766
  });
25147
25767
  for (const p of patchList) await client.uploadBlob(p.hkp, p.sha256, "patch");
25148
25768
  }
25769
+ let source = null;
25770
+ if (!o.skipSource) {
25771
+ try {
25772
+ const prev = latest ? (await client.request("GET", `/v1/releases/${latest.id}/source`).catch(() => ({ source: null }))).source : null;
25773
+ source = await releaseSource(projectDir, prev?.commit ?? null, log);
25774
+ if (source) log(`Source: ${source.commit.slice(0, 8)}${source.changes.length ? `, ${source.changes.length} change${source.changes.length === 1 ? "" : "s"} since ${latest?.label}` : ""}`);
25775
+ } catch (e) {
25776
+ log(`Couldn't read git history (${e.message}); publishing without it.`);
25777
+ }
25778
+ }
25779
+ const githubOidcToken = await githubOidc();
25780
+ if (githubOidcToken) log("Build provenance: GitHub Actions identity attached");
25149
25781
  const release = await client.request("POST", "/v1/releases", {
25782
+ provenance: githubOidcToken ? { githubOidcToken } : void 0,
25783
+ source: source ?? void 0,
25150
25784
  channelKey: o.channel,
25151
25785
  platform: o.platform,
25152
25786
  runtimeVersion: o.runtimeVersion,
25153
25787
  sha256: packed.sha256,
25154
25788
  size: packed.hkb.byteLength,
25155
25789
  description: o.description,
25156
- mandatory: o.mandatory || o.hotfix,
25790
+ mandatory: o.mandatory || o.hotfix || o.live,
25157
25791
  rolloutPct: o.rollout,
25158
- push: o.hotfix || o.push || void 0,
25792
+ push: o.hotfix || o.live || o.push || void 0,
25159
25793
  signature,
25160
25794
  patches: patchList.map(({ fromSha256, sha256, size, signature: patchSig }) => ({ fromSha256, sha256, size, signature: patchSig })),
25161
25795
  guard,
@@ -25175,3 +25809,15 @@ async function releaseAction(o) {
25175
25809
  if (guard) log(`Guarded: it will advance on its own when healthy and roll back on crashes. Watch with \`healkite guard ${release.id}\``);
25176
25810
  return { id: release.id, label: release.label };
25177
25811
  }
25812
+ async function githubOidc() {
25813
+ const url2 = process.env.ACTIONS_ID_TOKEN_REQUEST_URL;
25814
+ const token = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
25815
+ if (!url2 || !token) return null;
25816
+ try {
25817
+ const res = await fetch(`${url2}${url2.includes("?") ? "&" : "?"}audience=${PROVENANCE_AUDIENCE}`, { headers: { authorization: `Bearer ${token}` } });
25818
+ if (!res.ok) return null;
25819
+ return (await res.json()).value ?? null;
25820
+ } catch {
25821
+ return null;
25822
+ }
25823
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "healkite",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Healkite CLI — release, promote and roll back over-the-air React Native updates.",
5
- "license": "UNLICENSED",
5
+ "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "healkite": "./bin/healkite.mjs"
@@ -14,10 +14,10 @@
14
14
  "typescript": "~6.0.3",
15
15
  "vitest": "^5.1.0",
16
16
  "@healkite/adapter-blob-fs": "0.0.0",
17
- "@healkite/adapter-cdn-cloudflare": "0.0.0",
18
17
  "@healkite/adapter-blob-s3": "0.0.0",
18
+ "@healkite/adapter-cdn-cloudflare": "0.0.0",
19
19
  "@healkite/core": "0.0.0",
20
- "healkite-protocol": "0.1.0"
20
+ "healkite-protocol": "0.2.0"
21
21
  },
22
22
  "author": "Healkite",
23
23
  "homepage": "https://healkite.com",
@@ -30,7 +30,8 @@
30
30
  "files": [
31
31
  "bin",
32
32
  "dist",
33
- "README.md"
33
+ "README.md",
34
+ "LICENSE"
34
35
  ],
35
36
  "keywords": [
36
37
  "react-native",