@pmate/cli 0.49.3 → 0.49.5

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/dist/index.js CHANGED
@@ -8897,6 +8897,9 @@ function serviceHelp(argv) {
8897
8897
  pmate service update NS:SERVICE --file FILE [--json]
8898
8898
  pmate service deploy NS:SERVICE [--env prod] [--dry-run] [--json]
8899
8899
  pmate service log NS:SERVICE [--env prod] [--since-ms MS] [--page N] [--follow] [--json]
8900
+ pmate service testflight groups NS:SERVICE [--json]
8901
+ pmate service testflight status NS:SERVICE --version VERSION --build BUILD [--json]
8902
+ pmate service testflight distribute NS:SERVICE --version VERSION --build BUILD --group NAME_OR_ID --notes-file FILE [--locale zh-Hans] [--submit-review] [--json]
8900
8903
  pmate service stop NS:SERVICE [--json]
8901
8904
  Registry commands support --base-url URL. IDs identify Services, not Apps.
8902
8905
  Deploy uses the registered release configuration; read the current Service before mutations.
@@ -8930,8 +8933,8 @@ function sessionCommand(args) {
8930
8933
  }
8931
8934
 
8932
8935
  // src/index.ts
8933
- var import_node_fs32 = require("fs");
8934
- var import_node_path37 = __toESM(require("path"));
8936
+ var import_node_fs33 = require("fs");
8937
+ var import_node_path38 = __toESM(require("path"));
8935
8938
 
8936
8939
  // src/services/PackageInstaller.ts
8937
8940
  var import_node_child_process = require("child_process");
@@ -18726,28 +18729,168 @@ function readNamespaceFromPayload(payload) {
18726
18729
  }
18727
18730
 
18728
18731
  // src/commands/ServiceCommandHandler.ts
18729
- var import_node_fs28 = require("fs");
18732
+ var import_node_fs29 = require("fs");
18730
18733
  var import_promises5 = require("fs/promises");
18731
- var import_node_path33 = __toESM(require("path"));
18734
+ var import_node_path34 = __toESM(require("path"));
18732
18735
  var import_node_child_process16 = require("child_process");
18733
18736
  var import_promises6 = require("readline/promises");
18734
18737
 
18738
+ // src/services/TestFlightService.ts
18739
+ var import_node_crypto6 = require("crypto");
18740
+ var import_node_fs21 = require("fs");
18741
+ var import_node_os11 = require("os");
18742
+ var import_node_path26 = require("path");
18743
+ var list = (value) => !value?.data ? [] : Array.isArray(value.data) ? value.data : [value.data];
18744
+ var TestFlightService = class {
18745
+ constructor(deps = {}) {
18746
+ this.deps = deps;
18747
+ }
18748
+ async execute(service, options) {
18749
+ if (!("type" in service) || service.type !== "ios" || !service.mobile || !("bundleId" in service.mobile) || !service.mobile.bundleId) throw Error("TestFlight requires a registered iOS service with mobile.bundleId");
18750
+ const bundleId = service.mobile.bundleId;
18751
+ const operationId = (0, import_node_crypto6.randomUUID)();
18752
+ const log = this.deps.log ?? writeDiagnostic;
18753
+ const emit = (event, data = {}) => log({ time: (/* @__PURE__ */ new Date()).toISOString(), event, operationId, serviceId: service.id, version: options.version, build: options.build, ...data });
18754
+ const api = this.deps.api ?? createAppleApi();
18755
+ const read = async (path37, init) => {
18756
+ const start = Date.now();
18757
+ try {
18758
+ const result2 = await api(path37, init);
18759
+ emit("testflight.request.complete", { method: init?.method ?? "GET", resource: path37.split("?")[0], durationMs: Date.now() - start });
18760
+ return result2;
18761
+ } catch (error) {
18762
+ emit("testflight.request.failed", { method: init?.method ?? "GET", resource: path37.split("?")[0], durationMs: Date.now() - start, error: error instanceof Error ? error.message : "Unknown Apple error" });
18763
+ throw error;
18764
+ }
18765
+ };
18766
+ const all = async (path37) => {
18767
+ const resources = [], seen = /* @__PURE__ */ new Set();
18768
+ let next = path37;
18769
+ while (next) {
18770
+ if (seen.has(next) || seen.size >= 100) throw Error("Invalid Apple pagination");
18771
+ seen.add(next);
18772
+ const page = await read(next);
18773
+ resources.push(...list(page));
18774
+ next = page?.links?.next;
18775
+ }
18776
+ return resources;
18777
+ };
18778
+ const apps = list(await read(`apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=2`));
18779
+ if (apps.length !== 1) throw Error("Apple app identity is missing or ambiguous");
18780
+ const app = apps[0];
18781
+ const groups = async () => all(`apps/${encodeURIComponent(app.id)}/betaGroups?limit=200`);
18782
+ if (options.testflightAction === "groups") return { serviceId: service.id, bundleId, groups: (await groups()).map((g) => ({ id: g.id, name: g.attributes?.name, isInternalGroup: g.attributes?.isInternalGroup, publicLinkEnabled: g.attributes?.publicLinkEnabled })) };
18783
+ if (!options.version || !options.build) throw Error("Exact --version and --build required");
18784
+ const response = await read(`builds?filter[app]=${encodeURIComponent(app.id)}&filter[version]=${encodeURIComponent(options.build)}&include=preReleaseVersion,buildBetaDetail&limit=200`);
18785
+ const matches = list(response).filter((b) => b.attributes?.version === options.build && response?.included?.some((v) => v.type === "preReleaseVersions" && v.id === b.relationships?.preReleaseVersion?.data?.id && v.attributes?.version === options.version));
18786
+ if (matches.length !== 1) throw Error("Exact Apple version/build is missing or ambiguous; no changes made");
18787
+ const build = matches[0], id = encodeURIComponent(build.id);
18788
+ const state = async () => {
18789
+ const detail2 = list(await read(`builds/${id}/buildBetaDetail`))[0];
18790
+ const attrs = build.attributes ?? {}, beta = detail2?.attributes ?? {};
18791
+ const states = [beta.internalBuildState, beta.externalBuildState];
18792
+ const status2 = ["FAILED", "INVALID"].includes(attrs.processingState) ? "failed" : attrs.expired ? "expired" : states.includes("MISSING_EXPORT_COMPLIANCE") ? "missing-export-compliance" : attrs.processingState !== "VALID" ? "processing" : "processed";
18793
+ return { serviceId: service.id, bundleId, version: options.version, build: options.build, buildId: build.id, status: status2, processingState: attrs.processingState, internalBuildState: beta.internalBuildState, externalBuildState: beta.externalBuildState };
18794
+ };
18795
+ const assignedGroups = async () => {
18796
+ const found = [];
18797
+ for (const group2 of await groups()) if ((await all(`betaGroups/${encodeURIComponent(group2.id)}/builds?limit=200`)).some((b) => b.id === build.id)) found.push(group2);
18798
+ return found;
18799
+ };
18800
+ let result = await state();
18801
+ if (options.testflightAction === "status") return { ...result, groups: (await assignedGroups()).map((g) => ({ id: g.id, name: g.attributes?.name, isInternalGroup: g.attributes?.isInternalGroup })), localizations: (await all(`builds/${id}/betaBuildLocalizations?limit=200`)).map((v) => ({ locale: v.attributes?.locale, whatsNew: v.attributes?.whatsNew })) };
18802
+ if (!options.group || !options.notesFile) throw Error("--group and --notes-file required");
18803
+ const locale = options.locale ?? "zh-Hans";
18804
+ if (!/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(locale)) throw Error("Invalid locale");
18805
+ const notes = (this.deps.readNotes ?? ((p) => (0, import_node_fs21.readFileSync)(p, "utf8")))(options.notesFile).trim();
18806
+ if (!notes || notes.length > 4e3) throw Error("TestFlight notes must contain 1\u20134000 characters");
18807
+ const targets = (await groups()).filter((g) => g.id === options.group || g.attributes?.name === options.group);
18808
+ if (targets.length !== 1) throw Error("Beta group is missing or ambiguous; use its exact ID");
18809
+ const group = targets[0];
18810
+ if (typeof group.attributes?.isInternalGroup !== "boolean") throw Error("Apple group type is unknown");
18811
+ if (result.status !== "processed") {
18812
+ emit("testflight.blocked", { status: result.status });
18813
+ return result;
18814
+ }
18815
+ const localizations = await all(`builds/${id}/betaBuildLocalizations?limit=200`);
18816
+ const localized = localizations.filter((v) => v.attributes?.locale === locale);
18817
+ if (localized.length > 1) throw Error("Ambiguous build localization");
18818
+ if (!localized.length) await read("betaBuildLocalizations", { method: "POST", body: JSON.stringify({ data: { type: "betaBuildLocalizations", attributes: { locale, whatsNew: notes }, relationships: { build: { data: { type: "builds", id: build.id } } } } }) });
18819
+ else if (localized[0].attributes?.whatsNew !== notes) await read(`betaBuildLocalizations/${encodeURIComponent(localized[0].id)}`, { method: "PATCH", body: JSON.stringify({ data: { type: "betaBuildLocalizations", id: localized[0].id, attributes: { whatsNew: notes } } }) });
18820
+ const assigned = await all(`betaGroups/${encodeURIComponent(group.id)}/builds?limit=200`);
18821
+ if (!assigned.some((b) => b.id === build.id)) await read(`betaGroups/${encodeURIComponent(group.id)}/relationships/builds`, { method: "POST", body: JSON.stringify({ data: [{ type: "builds", id: build.id }] }) });
18822
+ result = await state();
18823
+ const external = !group.attributes.isInternalGroup;
18824
+ let reviewRequested = false;
18825
+ if (external && options.submitReview && result.externalBuildState === "READY_FOR_BETA_SUBMISSION") {
18826
+ const submission = await read(`builds/${id}/betaAppReviewSubmission`);
18827
+ if (!list(submission).length) {
18828
+ await read("betaAppReviewSubmissions", { method: "POST", body: JSON.stringify({ data: { type: "betaAppReviewSubmissions", relationships: { build: { data: { type: "builds", id: build.id } } } } }) });
18829
+ reviewRequested = true;
18830
+ }
18831
+ }
18832
+ const verifiedGroups = await all(`betaGroups/${encodeURIComponent(group.id)}/builds?limit=200`);
18833
+ const verifiedNotes = await all(`builds/${id}/betaBuildLocalizations?limit=200`);
18834
+ const detail = await state();
18835
+ const groupAssigned = verifiedGroups.some((b) => b.id === build.id);
18836
+ const notesWritten = verifiedNotes.some((n) => n.attributes?.locale === locale && n.attributes?.whatsNew === notes);
18837
+ const audienceState = external ? detail.externalBuildState : detail.internalBuildState;
18838
+ const status = !groupAssigned || !notesWritten ? "pending-verification" : audienceState === "IN_BETA_TESTING" ? "available" : reviewRequested || ["WAITING_FOR_REVIEW", "IN_REVIEW"].includes(audienceState) ? "awaiting-review" : !external ? "pending-testing" : audienceState === "BETA_REJECTED" ? "review-rejected" : "requires-review";
18839
+ emit("testflight.distribution.result", { status, groupId: group.id, groupAssigned, notesWritten, reviewRequested });
18840
+ return { ...detail, status, group: { id: group.id, name: group.attributes?.name, isInternalGroup: !external }, groupAssigned, notesWritten, reviewRequested, locale };
18841
+ }
18842
+ };
18843
+ function createAppleApi() {
18844
+ const file = (0, import_node_path26.join)((0, import_node_os11.homedir)(), ".pmate/ios/app-store-connect.json");
18845
+ const config = process.env.BURGESS_ASC_ISSUER_ID && process.env.BURGESS_ASC_KEY_ID && process.env.BURGESS_ASC_PRIVATE_KEY_FILE ? {} : JSON.parse((0, import_node_fs21.readFileSync)(file, "utf8"));
18846
+ const issuerId = process.env.BURGESS_ASC_ISSUER_ID ?? config.issuerId;
18847
+ const keyId = process.env.BURGESS_ASC_KEY_ID ?? config.keyId;
18848
+ const privateKeyFile = process.env.BURGESS_ASC_PRIVATE_KEY_FILE ?? config.privateKeyPath;
18849
+ if (!issuerId || !keyId || !privateKeyFile) throw Error("Missing App Store Connect credentials");
18850
+ const key = (0, import_node_crypto6.createPrivateKey)((0, import_node_fs21.readFileSync)(privateKeyFile));
18851
+ return async (path37, init = {}) => {
18852
+ const url = new URL(path37, "https://api.appstoreconnect.apple.com/v1/");
18853
+ if (url.origin !== "https://api.appstoreconnect.apple.com" || !url.pathname.startsWith("/v1/")) throw Error("Invalid Apple API URL");
18854
+ const now = Math.floor(Date.now() / 1e3);
18855
+ const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
18856
+ const unsigned = `${b64({ alg: "ES256", kid: keyId, typ: "JWT" })}.${b64({ iss: issuerId, iat: now, exp: now + 300, aud: "appstoreconnect-v1" })}`;
18857
+ const token = `${unsigned}.${(0, import_node_crypto6.sign)("sha256", Buffer.from(unsigned), { key, dsaEncoding: "ieee-p1363" }).toString("base64url")}`;
18858
+ const response = await fetch(url, { ...init, headers: { authorization: `Bearer ${token}`, ...init.body ? { "content-type": "application/json" } : {} }, signal: AbortSignal.timeout(3e4) });
18859
+ if (response.status === 404 && url.pathname.endsWith("/betaAppReviewSubmission") && !init.method) return void 0;
18860
+ if (!response.ok) {
18861
+ const problem = await response.json().catch(() => ({}));
18862
+ throw Error(`Apple API ${init.method ?? "GET"} ${url.pathname}: HTTP ${response.status} ${problem.errors?.map((e) => e.code).join(",") ?? ""}`);
18863
+ }
18864
+ if (response.status === 204) return void 0;
18865
+ return response.json();
18866
+ };
18867
+ }
18868
+ function writeDiagnostic(event) {
18869
+ try {
18870
+ const root = (0, import_node_path26.join)((0, import_node_os11.homedir)(), ".pmate/logs/testflight");
18871
+ (0, import_node_fs21.mkdirSync)(root, { recursive: true, mode: 448 });
18872
+ (0, import_node_fs21.appendFileSync)((0, import_node_path26.join)(root, `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.jsonl`), JSON.stringify(event) + "\n", { mode: 384 });
18873
+ } catch {
18874
+ console.error("TestFlight diagnostic log could not be written");
18875
+ }
18876
+ }
18877
+
18735
18878
  // src/services/NativeServiceDeploy.ts
18736
- var import_node_path31 = __toESM(require("path"));
18737
- var import_node_fs26 = require("fs");
18879
+ var import_node_path32 = __toESM(require("path"));
18880
+ var import_node_fs27 = require("fs");
18738
18881
 
18739
18882
  // src/electronBuild.ts
18740
18883
  var import_node_child_process10 = require("child_process");
18741
- var import_node_fs22 = require("fs");
18742
- var import_node_os11 = require("os");
18743
- var import_node_path27 = __toESM(require("path"));
18884
+ var import_node_fs23 = require("fs");
18885
+ var import_node_os12 = require("os");
18886
+ var import_node_path28 = __toESM(require("path"));
18744
18887
  var import_sharp2 = __toESM(require("sharp"));
18745
18888
 
18746
18889
  // src/desktopRelease.ts
18747
18890
  init_sessionStore();
18748
- var import_node_crypto6 = require("crypto");
18749
- var import_node_fs21 = require("fs");
18750
- var import_node_path26 = __toESM(require("path"));
18891
+ var import_node_crypto7 = require("crypto");
18892
+ var import_node_fs22 = require("fs");
18893
+ var import_node_path27 = __toESM(require("path"));
18751
18894
  async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18752
18895
  const segments = [...app.split(":"), version, platform, arch];
18753
18896
  if (app.split(":").length !== 2 || segments.some((s) => !/^[\w.-]+$/.test(s) || s === "." || s === "..")) throw new Error("Invalid desktop release identity");
@@ -18756,17 +18899,17 @@ async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18756
18899
  const bucket2 = "parrot-static";
18757
18900
  const prefix = `desktop/${segments.join("/")}/`;
18758
18901
  const url = (key) => `https://parrot-static.pmate.chat/${key.split("/").map(encodeURIComponent).join("/")}`;
18759
- const artifacts = (0, import_node_fs21.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && (platform === "mac" ? /(?:\.(dmg|zip|blockmap)$|^latest-mac\.yml$)/i : /(?:\.(exe|zip|blockmap)$|^latest\.yml$)/i).test(entry.name)).sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
18760
- const bytes = (0, import_node_fs21.readFileSync)(import_node_path26.default.join(directory, entry.name));
18902
+ const artifacts = (0, import_node_fs22.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && (platform === "mac" ? /(?:\.(dmg|zip|blockmap)$|^latest-mac\.yml$)/i : /(?:\.(exe|zip|blockmap)$|^latest\.yml$)/i).test(entry.name)).sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
18903
+ const bytes = (0, import_node_fs22.readFileSync)(import_node_path27.default.join(directory, entry.name));
18761
18904
  const objectKey = prefix + entry.name;
18762
- return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto6.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18905
+ return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto7.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18763
18906
  });
18764
18907
  if (!artifacts.length) throw new Error("No desktop installers found to publish");
18765
18908
  const manifestKey = prefix + "release.json";
18766
18909
  const existing = await AliyunService.readJsonObject(bucket2, manifestKey);
18767
18910
  const release = { schemaVersion: 1, app, version, platform, arch, artifacts };
18768
18911
  if (existing !== null && JSON.stringify(existing) !== JSON.stringify(release)) throw new Error("Desktop release already exists with different artifacts; bump the app version");
18769
- for (const artifact of artifacts) await AliyunService.uploadFile(import_node_path26.default.join(directory, artifact.name), bucket2, artifact.objectKey);
18912
+ for (const artifact of artifacts) await AliyunService.uploadFile(import_node_path27.default.join(directory, artifact.name), bucket2, artifact.objectKey);
18770
18913
  await AliyunService.uploadJsonObject(bucket2, manifestKey, release);
18771
18914
  const base = (process.env.PMATE_APPS_API_BASE_URL || "https://apps-api.pmate.chat").replace(/\/+$/, "");
18772
18915
  const response = await fetch(`${base}/versions/${encodeURIComponent(app)}`, {
@@ -18785,7 +18928,7 @@ async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18785
18928
  var ELECTRON_VERSION = "44.5.1";
18786
18929
  var BUILDER_VERSION = "26.15.3";
18787
18930
  function readDesktopConfig(file, appId) {
18788
- const c = JSON.parse((0, import_node_fs22.readFileSync)(file, "utf8"));
18931
+ const c = JSON.parse((0, import_node_fs23.readFileSync)(file, "utf8"));
18789
18932
  if (c.schemaVersion !== 2 || c.app !== appId) throw new Error("Desktop config schemaVersion/app mismatch");
18790
18933
  for (const key of ["productName", "bundleId", "version", "icon"]) {
18791
18934
  if (typeof c[key] !== "string" || !c[key].trim()) throw new Error(`Missing desktop ${key}`);
@@ -18811,10 +18954,10 @@ function readDesktopConfig(file, appId) {
18811
18954
  return c;
18812
18955
  }
18813
18956
  function repositoryRoot(cwd) {
18814
- let dir = import_node_path27.default.resolve(cwd);
18957
+ let dir = import_node_path28.default.resolve(cwd);
18815
18958
  while (true) {
18816
- if ((0, import_node_fs22.existsSync)(import_node_path27.default.join(dir, ".git"))) return dir;
18817
- const parent = import_node_path27.default.dirname(dir);
18959
+ if ((0, import_node_fs23.existsSync)(import_node_path28.default.join(dir, ".git"))) return dir;
18960
+ const parent = import_node_path28.default.dirname(dir);
18818
18961
  if (parent === dir) return void 0;
18819
18962
  dir = parent;
18820
18963
  }
@@ -18822,24 +18965,24 @@ function repositoryRoot(cwd) {
18822
18965
  function resolveDesktopPaths(args, cwd = process.cwd()) {
18823
18966
  const root = repositoryRoot(cwd);
18824
18967
  const name = args.id.split(":")[1];
18825
- let file = args.config ? import_node_path27.default.resolve(cwd, args.config) : void 0;
18968
+ let file = args.config ? import_node_path28.default.resolve(cwd, args.config) : void 0;
18826
18969
  if (!file) {
18827
- let dir = import_node_path27.default.resolve(cwd);
18970
+ let dir = import_node_path28.default.resolve(cwd);
18828
18971
  while (true) {
18829
- const candidates = [.../* @__PURE__ */ new Set([import_node_path27.default.join(dir, "desktop.config.json"), import_node_path27.default.join(dir, "apps", name, "desktop.config.json")])];
18830
- const matches = candidates.filter((candidate) => (0, import_node_fs22.existsSync)(candidate) && JSON.parse((0, import_node_fs22.readFileSync)(candidate, "utf8")).app === args.id);
18972
+ const candidates = [.../* @__PURE__ */ new Set([import_node_path28.default.join(dir, "desktop.config.json"), import_node_path28.default.join(dir, "apps", name, "desktop.config.json")])];
18973
+ const matches = candidates.filter((candidate) => (0, import_node_fs23.existsSync)(candidate) && JSON.parse((0, import_node_fs23.readFileSync)(candidate, "utf8")).app === args.id);
18831
18974
  if (matches.length > 1) throw new Error("Ambiguous desktop config; specify --config");
18832
18975
  if (matches.length === 1) {
18833
18976
  file = matches[0];
18834
18977
  break;
18835
18978
  }
18836
- const parent = import_node_path27.default.dirname(dir);
18979
+ const parent = import_node_path28.default.dirname(dir);
18837
18980
  if (dir === root || parent === dir) break;
18838
18981
  dir = parent;
18839
18982
  }
18840
18983
  }
18841
18984
  if (!file) throw new Error(`No desktop config for ${args.id}; specify --config`);
18842
- return { file, output: args.outDir ? import_node_path27.default.resolve(cwd, args.outDir) : import_node_path27.default.join(root ?? import_node_path27.default.dirname(file), "release", name) };
18985
+ return { file, output: args.outDir ? import_node_path28.default.resolve(cwd, args.outDir) : import_node_path28.default.join(root ?? import_node_path28.default.dirname(file), "release", name) };
18843
18986
  }
18844
18987
  function desktopBuildEnvironment(config, env = process.env) {
18845
18988
  return { ...env, ...env.APPLE_KEYCHAIN_PROFILE ? {} : config.notaryProfile ? { APPLE_KEYCHAIN_PROFILE: config.notaryProfile } : {} };
@@ -18862,7 +19005,7 @@ async function publishVerifiedDesktop(args, artifacts, config, verify = verifyMa
18862
19005
  return upload(artifacts, config.app, config.version, args.platform, args.arch);
18863
19006
  }
18864
19007
  async function verifyMacRelease(artifacts, run2 = runBuildCommand, inspect = (app) => (0, import_node_child_process10.spawnSync)("codesign", ["-dv", "--verbose=4", app], { encoding: "utf8" })) {
18865
- const apps = (0, import_node_fs22.readdirSync)(artifacts, { recursive: true, withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.endsWith(".app")).map((entry) => import_node_path27.default.join(entry.parentPath, entry.name)).filter((file) => !file.slice(0, -4).includes(".app/"));
19008
+ const apps = (0, import_node_fs23.readdirSync)(artifacts, { recursive: true, withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.endsWith(".app")).map((entry) => import_node_path28.default.join(entry.parentPath, entry.name)).filter((file) => !file.slice(0, -4).includes(".app/"));
18866
19009
  if (!apps.length) throw new Error("No packaged macOS app found; refusing publication");
18867
19010
  for (const app of apps) {
18868
19011
  await run2(["codesign", "--verify", "--deep", "--strict", app], artifacts);
@@ -18883,19 +19026,19 @@ async function renderTrayIcons(source, output) {
18883
19026
  const idle = await (0, import_sharp2.default)(source).resize(36, 36, { fit: "contain" }).png().toBuffer();
18884
19027
  const gap = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="7" fill="#000"/></svg>');
18885
19028
  const dot = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="5" fill="#000"/></svg>');
18886
- await (0, import_sharp2.default)(idle).toFile(import_node_path27.default.join(output, "trayTemplate.png"));
18887
- await (0, import_sharp2.default)(idle).composite([{ input: gap, blend: "dest-out" }, { input: dot }]).png().toFile(import_node_path27.default.join(output, "trayUnreadTemplate.png"));
19029
+ await (0, import_sharp2.default)(idle).toFile(import_node_path28.default.join(output, "trayTemplate.png"));
19030
+ await (0, import_sharp2.default)(idle).composite([{ input: gap, blend: "dest-out" }, { input: dot }]).png().toFile(import_node_path28.default.join(output, "trayUnreadTemplate.png"));
18888
19031
  }
18889
19032
  async function buildDesktop(args) {
18890
19033
  const { file, output } = resolveDesktopPaths(args);
18891
19034
  const c = readDesktopConfig(file, args.id);
18892
- const base = import_node_path27.default.dirname(file);
18893
- const icon = import_node_path27.default.resolve(base, c.icon);
19035
+ const base = import_node_path28.default.dirname(file);
19036
+ const icon = import_node_path28.default.resolve(base, c.icon);
18894
19037
  const tray = c.tray && (!c.tray.platforms || c.tray.platforms.includes(args.platform)) ? c.tray : void 0;
18895
- const trayIcon = tray ? import_node_path27.default.resolve(base, tray.icon) : void 0;
19038
+ const trayIcon = tray ? import_node_path28.default.resolve(base, tray.icon) : void 0;
18896
19039
  const env = desktopBuildEnvironment(c);
18897
- if (!(0, import_node_fs22.existsSync)(icon) || !(0, import_node_fs22.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
18898
- if (trayIcon && (!(0, import_node_fs22.existsSync)(trayIcon) || !(0, import_node_fs22.statSync)(trayIcon).isFile())) throw new Error(`Desktop tray icon not found: ${trayIcon}`);
19040
+ if (!(0, import_node_fs23.existsSync)(icon) || !(0, import_node_fs23.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
19041
+ if (trayIcon && (!(0, import_node_fs23.existsSync)(trayIcon) || !(0, import_node_fs23.statSync)(trayIcon).isFile())) throw new Error(`Desktop tray icon not found: ${trayIcon}`);
18899
19042
  if (!["mac", "win"].includes(args.platform) || !["arm64", "x64"].includes(args.arch)) throw new Error("Supported target: mac|win --arch arm64|x64");
18900
19043
  if (args.platform === "mac" && process.platform !== "darwin") throw new Error("macOS desktop packaging requires a macOS build host");
18901
19044
  const plan = { config: file, notaryProfile: env.APPLE_KEYCHAIN_PROFILE, app: c.app, productName: c.productName, version: c.version, target: "electron", platform: args.platform, arch: args.arch, contentSource: "remote", origin: c.origin, tray: !!tray, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
@@ -18905,30 +19048,30 @@ async function buildDesktop(args) {
18905
19048
  requireNotaryCredentials(env);
18906
19049
  requireSigningIdentity(env);
18907
19050
  }
18908
- (0, import_node_fs22.mkdirSync)(output, { recursive: true });
18909
- const staging = (0, import_node_fs22.mkdtempSync)(import_node_path27.default.join(output, ".desktop-build-"));
18910
- const appDir = import_node_path27.default.join(staging, "app");
18911
- (0, import_node_fs22.mkdirSync)(appDir);
18912
- const templateDir = import_node_path27.default.join(__dirname, "templates", "electron");
18913
- (0, import_node_fs22.cpSync)(templateDir, appDir, { recursive: true });
19051
+ (0, import_node_fs23.mkdirSync)(output, { recursive: true });
19052
+ const staging = (0, import_node_fs23.mkdtempSync)(import_node_path28.default.join(output, ".desktop-build-"));
19053
+ const appDir = import_node_path28.default.join(staging, "app");
19054
+ (0, import_node_fs23.mkdirSync)(appDir);
19055
+ const templateDir = import_node_path28.default.join(__dirname, "templates", "electron");
19056
+ (0, import_node_fs23.cpSync)(templateDir, appDir, { recursive: true });
18914
19057
  if (trayIcon) await renderTrayIcons(trayIcon, appDir);
18915
- (0, import_node_fs22.writeFileSync)(import_node_path27.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId, ...tray ? { tray: { closeToTray: tray.closeToTray !== false } } : {} }));
18916
- (0, import_node_fs22.writeFileSync)(import_node_path27.default.join(appDir, "package.json"), JSON.stringify({ name: c.bundleId.replace(/\./g, "-"), version: c.version, description: `${c.productName} desktop application`, author: "PMate", main: "main.cjs", dependencies: { "@pmate/chat-sdk": "0.11.7", "electron-updater": "6.8.3" } }));
19058
+ (0, import_node_fs23.writeFileSync)(import_node_path28.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId, ...tray ? { tray: { closeToTray: tray.closeToTray !== false } } : {} }));
19059
+ (0, import_node_fs23.writeFileSync)(import_node_path28.default.join(appDir, "package.json"), JSON.stringify({ name: c.bundleId.replace(/\./g, "-"), version: c.version, description: `${c.productName} desktop application`, author: "PMate", main: "main.cjs", dependencies: { "@pmate/chat-sdk": "0.11.7", "electron-updater": "6.8.3" } }));
18917
19060
  await runBuildCommand(["npm", "install", "--omit=dev", "--no-audit", "--no-fund"], appDir);
18918
- const cache = import_node_path27.default.join((0, import_node_os11.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
18919
- (0, import_node_fs22.mkdirSync)(cache, { recursive: true });
19061
+ const cache = import_node_path28.default.join((0, import_node_os12.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
19062
+ (0, import_node_fs23.mkdirSync)(cache, { recursive: true });
18920
19063
  const toolPackage = { name: "pmate-desktop-toolchain", private: true, dependencies: { electron: ELECTRON_VERSION, "electron-builder": BUILDER_VERSION } };
18921
- if (!(0, import_node_fs22.existsSync)(import_node_path27.default.join(cache, "node_modules", "electron", "dist", "Electron.app")) || !(0, import_node_fs22.existsSync)(import_node_path27.default.join(cache, "node_modules", "electron-builder", "cli.js"))) {
18922
- (0, import_node_fs22.writeFileSync)(import_node_path27.default.join(cache, "package.json"), JSON.stringify(toolPackage));
18923
- await runBuildCommand(["npm", (0, import_node_fs22.existsSync)(import_node_path27.default.join(cache, "package-lock.json")) ? "ci" : "install", "--no-audit", "--no-fund"], cache);
19064
+ if (!(0, import_node_fs23.existsSync)(import_node_path28.default.join(cache, "node_modules", "electron", "dist", "Electron.app")) || !(0, import_node_fs23.existsSync)(import_node_path28.default.join(cache, "node_modules", "electron-builder", "cli.js"))) {
19065
+ (0, import_node_fs23.writeFileSync)(import_node_path28.default.join(cache, "package.json"), JSON.stringify(toolPackage));
19066
+ await runBuildCommand(["npm", (0, import_node_fs23.existsSync)(import_node_path28.default.join(cache, "package-lock.json")) ? "ci" : "install", "--no-audit", "--no-fund"], cache);
18924
19067
  }
18925
- const entitlements = import_node_path27.default.join(staging, "entitlements.mac.plist");
18926
- (0, import_node_fs22.writeFileSync)(entitlements, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>com.apple.security.cs.allow-jit</key><true/><key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/><key>com.apple.security.cs.disable-library-validation</key><true/><key>com.apple.security.device.audio-input</key><true/></dict></plist>`);
19068
+ const entitlements = import_node_path28.default.join(staging, "entitlements.mac.plist");
19069
+ (0, import_node_fs23.writeFileSync)(entitlements, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>com.apple.security.cs.allow-jit</key><true/><key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/><key>com.apple.security.cs.disable-library-validation</key><true/><key>com.apple.security.device.audio-input</key><true/></dict></plist>`);
18927
19070
  const builderConfig = {
18928
19071
  appId: c.bundleId,
18929
19072
  productName: c.productName,
18930
19073
  electronVersion: ELECTRON_VERSION,
18931
- directories: { app: appDir, output: import_node_path27.default.join(staging, "artifacts") },
19074
+ directories: { app: appDir, output: import_node_path28.default.join(staging, "artifacts") },
18932
19075
  files: ["**/*"],
18933
19076
  asar: true,
18934
19077
  artifactName: "${productName}-${version}-${arch}.${ext}",
@@ -18937,14 +19080,14 @@ async function buildDesktop(args) {
18937
19080
  win: { icon, target: args.dir ? ["dir"] : ["nsis", "zip"], ...args.signed ? {} : { signExecutable: false } },
18938
19081
  forceCodeSigning: args.signed
18939
19082
  };
18940
- const configPath = import_node_path27.default.join(staging, "builder.json");
18941
- (0, import_node_fs22.writeFileSync)(configPath, JSON.stringify(builderConfig));
18942
- await runBuildCommand([process.execPath, import_node_path27.default.join(cache, "node_modules", "electron-builder", "cli.js"), "--config", configPath, args.platform === "mac" ? "--mac" : "--win", `--${args.arch}`, "--publish", "never"], appDir, { ...env, ...args.signed ? {} : { CSC_IDENTITY_AUTO_DISCOVERY: "false" } });
18943
- const result = { ...plan, signature: args.signed ? args.platform === "mac" ? "Developer ID signed; notarization and Gatekeeper required before publication" : "configured-signing-required; verify Authenticode before distribution" : args.platform === "mac" ? "ad-hoc; local development" : "unsigned; local development", artifacts: import_node_path27.default.join(staging, "artifacts") };
18944
- (0, import_node_fs22.writeFileSync)(import_node_path27.default.join(staging, "build-report.json"), JSON.stringify(result, null, 2));
19083
+ const configPath = import_node_path28.default.join(staging, "builder.json");
19084
+ (0, import_node_fs23.writeFileSync)(configPath, JSON.stringify(builderConfig));
19085
+ await runBuildCommand([process.execPath, import_node_path28.default.join(cache, "node_modules", "electron-builder", "cli.js"), "--config", configPath, args.platform === "mac" ? "--mac" : "--win", `--${args.arch}`, "--publish", "never"], appDir, { ...env, ...args.signed ? {} : { CSC_IDENTITY_AUTO_DISCOVERY: "false" } });
19086
+ const result = { ...plan, signature: args.signed ? args.platform === "mac" ? "Developer ID signed; notarization and Gatekeeper required before publication" : "configured-signing-required; verify Authenticode before distribution" : args.platform === "mac" ? "ad-hoc; local development" : "unsigned; local development", artifacts: import_node_path28.default.join(staging, "artifacts") };
19087
+ (0, import_node_fs23.writeFileSync)(import_node_path28.default.join(staging, "build-report.json"), JSON.stringify(result, null, 2));
18945
19088
  const publication = await publishVerifiedDesktop(args, result.artifacts, c);
18946
- (0, import_node_fs22.writeFileSync)(import_node_path27.default.join(staging, "build-report.json"), JSON.stringify({ ...result, publication }, null, 2));
18947
- console.log(JSON.stringify({ phase: "complete", report: import_node_path27.default.join(staging, "build-report.json"), artifacts: result.artifacts, signature: result.signature, publication }, null, 2));
19089
+ (0, import_node_fs23.writeFileSync)(import_node_path28.default.join(staging, "build-report.json"), JSON.stringify({ ...result, publication }, null, 2));
19090
+ console.log(JSON.stringify({ phase: "complete", report: import_node_path28.default.join(staging, "build-report.json"), artifacts: result.artifacts, signature: result.signature, publication }, null, 2));
18948
19091
  }
18949
19092
 
18950
19093
  // src/services/CurrentRepositoryRoot.ts
@@ -18963,10 +19106,10 @@ function currentRepositoryRoot(repository, cwd = process.cwd()) {
18963
19106
 
18964
19107
  // src/services/AndroidApkReleaseService.ts
18965
19108
  var import_node_child_process12 = require("child_process");
18966
- var import_node_crypto7 = require("crypto");
18967
- var import_node_fs23 = require("fs");
18968
- var import_node_os12 = __toESM(require("os"));
18969
- var import_node_path28 = __toESM(require("path"));
19109
+ var import_node_crypto8 = require("crypto");
19110
+ var import_node_fs24 = require("fs");
19111
+ var import_node_os13 = __toESM(require("os"));
19112
+ var import_node_path29 = __toESM(require("path"));
18970
19113
  var ANDROID_APK_BUCKET = "parrot-static";
18971
19114
  var ANDROID_APK_PUBLIC_BASE_URL = "https://parrot-static.pmate.chat";
18972
19115
  var ANDROID_SIGNING_ENV_KEYS = ["ANDROID_KEYSTORE_BASE64", "ANDROID_KEYSTORE_PASSWORD", "ANDROID_KEY_ALIAS", "ANDROID_KEY_PASSWORD", "ANDROID_SIGNING_CERT_SHA256"];
@@ -18986,9 +19129,9 @@ function verifyAndroidSigningCertificate(output, expected) {
18986
19129
  async function signAndroidApk(apkPath, signing) {
18987
19130
  const tool = findAndroidSdkTool("apksigner");
18988
19131
  if (!tool) throw new Error("Android SDK tool not found: apksigner");
18989
- const tempDir = (0, import_node_fs23.mkdtempSync)(import_node_path28.default.join(import_node_os12.default.tmpdir(), "pmate-apk-signing-"));
18990
- const keystorePath = import_node_path28.default.join(tempDir, "signing.keystore");
18991
- const cleanup = () => (0, import_node_fs23.rmSync)(tempDir, { recursive: true, force: true });
19132
+ const tempDir = (0, import_node_fs24.mkdtempSync)(import_node_path29.default.join(import_node_os13.default.tmpdir(), "pmate-apk-signing-"));
19133
+ const keystorePath = import_node_path29.default.join(tempDir, "signing.keystore");
19134
+ const cleanup = () => (0, import_node_fs24.rmSync)(tempDir, { recursive: true, force: true });
18992
19135
  const interrupted = () => {
18993
19136
  cleanup();
18994
19137
  process.exit(130);
@@ -18996,7 +19139,7 @@ async function signAndroidApk(apkPath, signing) {
18996
19139
  process.once("SIGINT", interrupted);
18997
19140
  process.once("SIGTERM", interrupted);
18998
19141
  try {
18999
- (0, import_node_fs23.writeFileSync)(keystorePath, signing.keystore, { mode: 384 });
19142
+ (0, import_node_fs24.writeFileSync)(keystorePath, signing.keystore, { mode: 384 });
19000
19143
  await new Promise((resolve, reject) => {
19001
19144
  const child = (0, import_node_child_process12.spawn)(tool, ["sign", "--ks", keystorePath, "--ks-key-alias", signing.alias, "--ks-pass", "env:PMATE_APK_STORE_PASSWORD", "--key-pass", "env:PMATE_APK_KEY_PASSWORD", apkPath], {
19002
19145
  env: { ...process.env, PMATE_APK_STORE_PASSWORD: signing.storePassword, PMATE_APK_KEY_PASSWORD: signing.keyPassword },
@@ -19047,7 +19190,7 @@ var AndroidApkReleaseService = class {
19047
19190
  }
19048
19191
  const bump = planAndroidProjectVersion(appDir, options.bump, publishedFloor);
19049
19192
  const signing = options.variant.toLowerCase() === "release" ? await this.loadSigning(service.id, options.env) : void 0;
19050
- (0, import_node_fs23.writeFileSync)(bump.filePath, bump.source);
19193
+ (0, import_node_fs24.writeFileSync)(bump.filePath, bump.source);
19051
19194
  ui.info("Bumped Android version", {
19052
19195
  file: bump.filePath,
19053
19196
  from: `${bump.previousVersionName} (${bump.previousVersionCode})`,
@@ -19072,7 +19215,7 @@ var AndroidApkReleaseService = class {
19072
19215
  ui.warn("Overwriting existing APK object", { objectKey, etag: existing.etag, size: existing.size });
19073
19216
  }
19074
19217
  const sha256 = await sha256File(apkPath);
19075
- const size = (0, import_node_fs23.statSync)(apkPath).size;
19218
+ const size = (0, import_node_fs24.statSync)(apkPath).size;
19076
19219
  const artifact = {
19077
19220
  serviceId: service.id,
19078
19221
  env: options.env,
@@ -19122,17 +19265,17 @@ var AndroidApkReleaseService = class {
19122
19265
  minimumVersionCode: options.minimumVersionCode
19123
19266
  });
19124
19267
  const objectKeys = androidUpdateManifestKeys(service);
19125
- const tempDir = (0, import_node_fs23.mkdtempSync)(import_node_path28.default.join(import_node_os12.default.tmpdir(), "pmate-apk-latest-"));
19126
- const manifestPath = import_node_path28.default.join(tempDir, "latest.json");
19268
+ const tempDir = (0, import_node_fs24.mkdtempSync)(import_node_path29.default.join(import_node_os13.default.tmpdir(), "pmate-apk-latest-"));
19269
+ const manifestPath = import_node_path29.default.join(tempDir, "latest.json");
19127
19270
  try {
19128
- (0, import_node_fs23.writeFileSync)(manifestPath, `${JSON.stringify(manifest, null, 2)}
19271
+ (0, import_node_fs24.writeFileSync)(manifestPath, `${JSON.stringify(manifest, null, 2)}
19129
19272
  `);
19130
19273
  for (const objectKey of objectKeys) {
19131
19274
  await AliyunService.uploadFile(manifestPath, ANDROID_APK_BUCKET, objectKey);
19132
19275
  ui.success(`Published Android update manifest ${ANDROID_APK_PUBLIC_BASE_URL}/${objectKey}`);
19133
19276
  }
19134
19277
  } finally {
19135
- (0, import_node_fs23.rmSync)(tempDir, { recursive: true, force: true });
19278
+ (0, import_node_fs24.rmSync)(tempDir, { recursive: true, force: true });
19136
19279
  }
19137
19280
  }
19138
19281
  async list(service, options) {
@@ -19149,7 +19292,7 @@ var AndroidApkReleaseService = class {
19149
19292
  const prefix = `apks/${identity.namespace}/${identity.name}`;
19150
19293
  const objects = await AliyunService.listObjects(ANDROID_APK_BUCKET, prefix);
19151
19294
  return objects.filter((item) => item.name.endsWith(".apk")).map((item) => {
19152
- const versionName = import_node_path28.default.basename(item.name, ".apk");
19295
+ const versionName = import_node_path29.default.basename(item.name, ".apk");
19153
19296
  return {
19154
19297
  serviceId,
19155
19298
  env: options.env ?? "unknown",
@@ -19172,7 +19315,7 @@ var AndroidApkReleaseService = class {
19172
19315
  }
19173
19316
  }
19174
19317
  resolveRepoRoot(service, cwd) {
19175
- if (cwd) return import_node_path28.default.resolve(process.cwd(), cwd);
19318
+ if (cwd) return import_node_path29.default.resolve(process.cwd(), cwd);
19176
19319
  const repository = this.getRepository(service);
19177
19320
  if (repository) {
19178
19321
  return resolveRepositoryLocalRoot(repository);
@@ -19184,8 +19327,8 @@ var AndroidApkReleaseService = class {
19184
19327
  if (!dir) {
19185
19328
  throw new Error(`Missing dir for android service ${service.id}`);
19186
19329
  }
19187
- const appDir = import_node_path28.default.resolve(repoRoot, dir);
19188
- if (!(0, import_node_fs23.existsSync)(appDir)) {
19330
+ const appDir = import_node_path29.default.resolve(repoRoot, dir);
19331
+ if (!(0, import_node_fs24.existsSync)(appDir)) {
19189
19332
  throw new Error(`Android app dir not found: ${appDir}`);
19190
19333
  }
19191
19334
  return appDir;
@@ -19201,11 +19344,11 @@ var AndroidApkReleaseService = class {
19201
19344
  return void 0;
19202
19345
  }
19203
19346
  async runGradleAssembleAndFindApk(repoRoot, appDir, variant) {
19204
- const gradlew = [import_node_path28.default.join(appDir, "gradlew"), import_node_path28.default.join(repoRoot, "gradlew")].find((candidate) => (0, import_node_fs23.existsSync)(candidate));
19347
+ const gradlew = [import_node_path29.default.join(appDir, "gradlew"), import_node_path29.default.join(repoRoot, "gradlew")].find((candidate) => (0, import_node_fs24.existsSync)(candidate));
19205
19348
  if (!gradlew) {
19206
19349
  throw new Error(`Gradle wrapper not found in ${appDir} or ${repoRoot}`);
19207
19350
  }
19208
- const gradleCwd = import_node_path28.default.dirname(gradlew);
19351
+ const gradleCwd = import_node_path29.default.dirname(gradlew);
19209
19352
  const normalizedVariant = variant.toLowerCase();
19210
19353
  const taskSuffix = `assemble${capitalize(normalizedVariant)}`;
19211
19354
  const tasks = [`:app:${taskSuffix}`, taskSuffix];
@@ -19321,7 +19464,7 @@ function resolveRepositoryLocalRoot(repository) {
19321
19464
  if (!repoName) {
19322
19465
  throw new Error(`Invalid repository: ${repository}`);
19323
19466
  }
19324
- return import_node_path28.default.join(import_node_os12.default.homedir(), "dev", "pmate", repoName);
19467
+ return import_node_path29.default.join(import_node_os13.default.homedir(), "dev", "pmate", repoName);
19325
19468
  }
19326
19469
  function bumpAndroidGradleVersionText(source, bump) {
19327
19470
  const versionNameMatch = source.match(/(^\s*versionName\s+["'])([^"']+)(["']\s*$)/m) ?? source.match(/(^\s*versionName\s*=\s*["'])([^"']+)(["']\s*$)/m);
@@ -19377,14 +19520,14 @@ function parseGradleOutputMetadata(source, apkFileName) {
19377
19520
  }
19378
19521
  function planAndroidProjectVersion(appDir, bump, publishedFloor = 0) {
19379
19522
  const candidates = [
19380
- import_node_path28.default.join(appDir, "app", "build.gradle.kts"),
19381
- import_node_path28.default.join(appDir, "app", "build.gradle"),
19382
- import_node_path28.default.join(appDir, "build.gradle.kts"),
19383
- import_node_path28.default.join(appDir, "build.gradle")
19523
+ import_node_path29.default.join(appDir, "app", "build.gradle.kts"),
19524
+ import_node_path29.default.join(appDir, "app", "build.gradle"),
19525
+ import_node_path29.default.join(appDir, "build.gradle.kts"),
19526
+ import_node_path29.default.join(appDir, "build.gradle")
19384
19527
  ];
19385
19528
  for (const candidate of candidates) {
19386
- if (!(0, import_node_fs23.existsSync)(candidate)) continue;
19387
- const result = bumpAndroidGradleVersionText((0, import_node_fs23.readFileSync)(candidate, "utf8"), bump);
19529
+ if (!(0, import_node_fs24.existsSync)(candidate)) continue;
19530
+ const result = bumpAndroidGradleVersionText((0, import_node_fs24.readFileSync)(candidate, "utf8"), bump);
19388
19531
  if (!Number.isSafeInteger(result.versionCode) || result.versionCode <= publishedFloor) throw new Error(`Android source is behind published versionCode ${publishedFloor}; update the checkout before releasing`);
19389
19532
  return { filePath: candidate, ...result };
19390
19533
  }
@@ -19392,27 +19535,27 @@ function planAndroidProjectVersion(appDir, bump, publishedFloor = 0) {
19392
19535
  }
19393
19536
  function findLatestApk(repoRoot, appDir, variant) {
19394
19537
  const dirs = [
19395
- import_node_path28.default.join(appDir, "app", "build", "outputs", "apk", variant),
19396
- import_node_path28.default.join(appDir, "build", "outputs", "apk", variant),
19397
- import_node_path28.default.join(repoRoot, "app", "build", "outputs", "apk", variant)
19538
+ import_node_path29.default.join(appDir, "app", "build", "outputs", "apk", variant),
19539
+ import_node_path29.default.join(appDir, "build", "outputs", "apk", variant),
19540
+ import_node_path29.default.join(repoRoot, "app", "build", "outputs", "apk", variant)
19398
19541
  ];
19399
19542
  const files = dirs.flatMap((dir) => listApks(dir));
19400
19543
  if (files.length === 0) {
19401
19544
  throw new Error(`Cannot find APK output for variant ${variant}`);
19402
19545
  }
19403
- files.sort((a, b) => (0, import_node_fs23.statSync)(b).mtimeMs - (0, import_node_fs23.statSync)(a).mtimeMs);
19546
+ files.sort((a, b) => (0, import_node_fs24.statSync)(b).mtimeMs - (0, import_node_fs24.statSync)(a).mtimeMs);
19404
19547
  return files[0];
19405
19548
  }
19406
19549
  function readGradleOutputMetadata(apkPath) {
19407
- const metadataPath = import_node_path28.default.join(import_node_path28.default.dirname(apkPath), "output-metadata.json");
19408
- if (!(0, import_node_fs23.existsSync)(metadataPath)) {
19550
+ const metadataPath = import_node_path29.default.join(import_node_path29.default.dirname(apkPath), "output-metadata.json");
19551
+ if (!(0, import_node_fs24.existsSync)(metadataPath)) {
19409
19552
  throw new Error(`Gradle output metadata not found: ${metadataPath}`);
19410
19553
  }
19411
- return parseGradleOutputMetadata((0, import_node_fs23.readFileSync)(metadataPath, "utf8"), import_node_path28.default.basename(apkPath));
19554
+ return parseGradleOutputMetadata((0, import_node_fs24.readFileSync)(metadataPath, "utf8"), import_node_path29.default.basename(apkPath));
19412
19555
  }
19413
19556
  function listApks(dir) {
19414
- if (!(0, import_node_fs23.existsSync)(dir)) return [];
19415
- return (0, import_node_fs23.readdirSync)(dir).filter((entry) => entry.endsWith(".apk")).map((entry) => import_node_path28.default.join(dir, entry)).filter((entry) => (0, import_node_fs23.statSync)(entry).isFile());
19557
+ if (!(0, import_node_fs24.existsSync)(dir)) return [];
19558
+ return (0, import_node_fs24.readdirSync)(dir).filter((entry) => entry.endsWith(".apk")).map((entry) => import_node_path29.default.join(dir, entry)).filter((entry) => (0, import_node_fs24.statSync)(entry).isFile());
19416
19559
  }
19417
19560
  function runCommand(command, args, cwd) {
19418
19561
  return new Promise((resolve, reject) => {
@@ -19446,26 +19589,26 @@ async function runAndroidSdkToolCapture(toolName, args) {
19446
19589
  return runCommandCapture(toolPath, args);
19447
19590
  }
19448
19591
  function findAndroidSdkTool(toolName) {
19449
- const sdkRoots = [process.env.ANDROID_HOME, process.env.ANDROID_SDK_ROOT].filter((item) => Boolean(item)).map((item) => import_node_path28.default.resolve(item));
19592
+ const sdkRoots = [process.env.ANDROID_HOME, process.env.ANDROID_SDK_ROOT].filter((item) => Boolean(item)).map((item) => import_node_path29.default.resolve(item));
19450
19593
  for (const sdkRoot of sdkRoots) {
19451
- const candidates = toolName === "aapt" || toolName === "apksigner" ? listVersionedToolCandidates(import_node_path28.default.join(sdkRoot, "build-tools"), toolName) : [
19452
- import_node_path28.default.join(sdkRoot, "cmdline-tools", "latest", "bin", toolName),
19453
- ...listVersionedToolCandidates(import_node_path28.default.join(sdkRoot, "cmdline-tools"), import_node_path28.default.join("bin", toolName)),
19454
- import_node_path28.default.join(sdkRoot, "tools", "bin", toolName)
19594
+ const candidates = toolName === "aapt" || toolName === "apksigner" ? listVersionedToolCandidates(import_node_path29.default.join(sdkRoot, "build-tools"), toolName) : [
19595
+ import_node_path29.default.join(sdkRoot, "cmdline-tools", "latest", "bin", toolName),
19596
+ ...listVersionedToolCandidates(import_node_path29.default.join(sdkRoot, "cmdline-tools"), import_node_path29.default.join("bin", toolName)),
19597
+ import_node_path29.default.join(sdkRoot, "tools", "bin", toolName)
19455
19598
  ];
19456
- const match = candidates.find((candidate) => (0, import_node_fs23.existsSync)(candidate));
19599
+ const match = candidates.find((candidate) => (0, import_node_fs24.existsSync)(candidate));
19457
19600
  if (match) return match;
19458
19601
  }
19459
19602
  return void 0;
19460
19603
  }
19461
19604
  function listVersionedToolCandidates(parentDir, relativeToolPath) {
19462
- if (!(0, import_node_fs23.existsSync)(parentDir)) return [];
19463
- return (0, import_node_fs23.readdirSync)(parentDir).map((entry) => import_node_path28.default.join(parentDir, entry)).filter((entry) => (0, import_node_fs23.statSync)(entry).isDirectory()).sort((a, b) => import_node_path28.default.basename(b).localeCompare(import_node_path28.default.basename(a), void 0, { numeric: true })).map((entry) => import_node_path28.default.join(entry, relativeToolPath));
19605
+ if (!(0, import_node_fs24.existsSync)(parentDir)) return [];
19606
+ return (0, import_node_fs24.readdirSync)(parentDir).map((entry) => import_node_path29.default.join(parentDir, entry)).filter((entry) => (0, import_node_fs24.statSync)(entry).isDirectory()).sort((a, b) => import_node_path29.default.basename(b).localeCompare(import_node_path29.default.basename(a), void 0, { numeric: true })).map((entry) => import_node_path29.default.join(entry, relativeToolPath));
19464
19607
  }
19465
19608
  function sha256File(filePath) {
19466
19609
  return new Promise((resolve, reject) => {
19467
- const hash = (0, import_node_crypto7.createHash)("sha256");
19468
- const stream = (0, import_node_fs23.createReadStream)(filePath);
19610
+ const hash = (0, import_node_crypto8.createHash)("sha256");
19611
+ const stream = (0, import_node_fs24.createReadStream)(filePath);
19469
19612
  stream.on("data", (chunk) => hash.update(chunk));
19470
19613
  stream.on("error", reject);
19471
19614
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -19483,21 +19626,21 @@ function capitalize(value) {
19483
19626
 
19484
19627
  // src/services/HarmonyReleaseService.ts
19485
19628
  var import_node_child_process13 = require("child_process");
19486
- var import_node_crypto8 = require("crypto");
19487
- var import_node_fs24 = require("fs");
19488
- var import_node_os13 = __toESM(require("os"));
19489
- var import_node_path29 = __toESM(require("path"));
19629
+ var import_node_crypto9 = require("crypto");
19630
+ var import_node_fs25 = require("fs");
19631
+ var import_node_os14 = __toESM(require("os"));
19632
+ var import_node_path30 = __toESM(require("path"));
19490
19633
  var import_json5 = __toESM(require("json5"));
19491
19634
  var HARMONY_SIGNING_KEYS = ["HARMONY_KEYSTORE_BASE64", "HARMONY_CERTIFICATE_BASE64", "HARMONY_PROFILE_BASE64", "HARMONY_STORE_PASSWORD", "HARMONY_KEY_ALIAS", "HARMONY_KEY_PASSWORD"];
19492
19635
  var bucket = "parrot-static";
19493
19636
  var baseUrl = "https://parrot-static.pmate.chat";
19494
19637
  var inside = (parent, child) => {
19495
- const rel = import_node_path29.default.relative(parent, child);
19496
- return !rel || !rel.startsWith(`..${import_node_path29.default.sep}`) && rel !== ".." && !import_node_path29.default.isAbsolute(rel);
19638
+ const rel = import_node_path30.default.relative(parent, child);
19639
+ return !rel || !rel.startsWith(`..${import_node_path30.default.sep}`) && rel !== ".." && !import_node_path30.default.isAbsolute(rel);
19497
19640
  };
19498
- var readJson5 = (file) => import_json5.default.parse((0, import_node_fs24.readFileSync)(file, "utf8"));
19641
+ var readJson5 = (file) => import_json5.default.parse((0, import_node_fs25.readFileSync)(file, "utf8"));
19499
19642
  function readHarmonyVersion(appDir, expected) {
19500
- const app = readJson5(import_node_path29.default.join(appDir, "AppScope/app.json5")).app;
19643
+ const app = readJson5(import_node_path30.default.join(appDir, "AppScope/app.json5")).app;
19501
19644
  if (!app || app.bundleName !== expected) throw new Error("HarmonyOS bundleName does not match service.mobile.bundleName");
19502
19645
  if (!/^\d+\.\d+\.\d+$/.test(app.versionName ?? "") || !Number.isSafeInteger(app.versionCode) || app.versionCode <= 0) throw new Error("HarmonyOS source requires a stable versionName and positive integer versionCode");
19503
19646
  return { bundleName: app.bundleName, versionName: app.versionName, versionCode: app.versionCode };
@@ -19508,25 +19651,25 @@ function stageHarmonySources(repoRoot, appDir, target) {
19508
19651
  const copy = (source) => {
19509
19652
  if (!inside(repoRoot, source)) throw new Error("HarmonyOS local dependencies must stay inside the repository");
19510
19653
  if (copied.some((dir) => inside(dir, source))) return;
19511
- if (!(0, import_node_fs24.existsSync)(source) || !(0, import_node_fs24.lstatSync)(source).isDirectory() || (0, import_node_fs24.lstatSync)(source).isSymbolicLink()) throw new Error("Invalid HarmonyOS source dependency");
19512
- if (!inside((0, import_node_fs24.realpathSync)(repoRoot), (0, import_node_fs24.realpathSync)(source))) throw new Error("HarmonyOS local dependencies must stay inside the repository");
19513
- const dest = import_node_path29.default.join(target, import_node_path29.default.relative(repoRoot, source));
19514
- (0, import_node_fs24.cpSync)(source, dest, { recursive: true, filter: (file) => {
19515
- if ((0, import_node_fs24.lstatSync)(file).isSymbolicLink()) throw new Error("HarmonyOS source symlinks are not supported");
19516
- const name = import_node_path29.default.basename(file);
19654
+ if (!(0, import_node_fs25.existsSync)(source) || !(0, import_node_fs25.lstatSync)(source).isDirectory() || (0, import_node_fs25.lstatSync)(source).isSymbolicLink()) throw new Error("Invalid HarmonyOS source dependency");
19655
+ if (!inside((0, import_node_fs25.realpathSync)(repoRoot), (0, import_node_fs25.realpathSync)(source))) throw new Error("HarmonyOS local dependencies must stay inside the repository");
19656
+ const dest = import_node_path30.default.join(target, import_node_path30.default.relative(repoRoot, source));
19657
+ (0, import_node_fs25.cpSync)(source, dest, { recursive: true, filter: (file) => {
19658
+ if ((0, import_node_fs25.lstatSync)(file).isSymbolicLink()) throw new Error("HarmonyOS source symlinks are not supported");
19659
+ const name = import_node_path30.default.basename(file);
19517
19660
  return !excluded.has(name) && !name.startsWith(".env") && !/\.(p12|pfx|p7b|keystore|jks|key|pem|cer)$/i.test(name);
19518
19661
  } });
19519
19662
  copied.push(source);
19520
19663
  const inspect = (dir) => {
19521
- for (const entry of (0, import_node_fs24.readdirSync)(dir, { withFileTypes: true })) {
19522
- const file = import_node_path29.default.join(dir, entry.name);
19664
+ for (const entry of (0, import_node_fs25.readdirSync)(dir, { withFileTypes: true })) {
19665
+ const file = import_node_path30.default.join(dir, entry.name);
19523
19666
  if (entry.isDirectory()) inspect(file);
19524
19667
  else if (entry.name === "oh-package.json5") {
19525
19668
  const manifest = readJson5(file);
19526
19669
  for (const value of Object.values({ ...manifest.dependencies, ...manifest.devDependencies })) {
19527
19670
  if (typeof value !== "string" || !value.startsWith("file:")) continue;
19528
- const original = import_node_path29.default.join(repoRoot, import_node_path29.default.relative(target, import_node_path29.default.dirname(file)));
19529
- copy(import_node_path29.default.resolve(original, value.slice(5)));
19671
+ const original = import_node_path30.default.join(repoRoot, import_node_path30.default.relative(target, import_node_path30.default.dirname(file)));
19672
+ copy(import_node_path30.default.resolve(original, value.slice(5)));
19530
19673
  }
19531
19674
  }
19532
19675
  }
@@ -19534,19 +19677,19 @@ function stageHarmonySources(repoRoot, appDir, target) {
19534
19677
  inspect(dest);
19535
19678
  };
19536
19679
  copy(appDir);
19537
- const profile = readJson5(import_node_path29.default.join(appDir, "build-profile.json5"));
19680
+ const profile = readJson5(import_node_path30.default.join(appDir, "build-profile.json5"));
19538
19681
  for (const module2 of profile.modules ?? []) {
19539
19682
  if (typeof module2.srcPath !== "string") throw new Error("Invalid HarmonyOS module srcPath");
19540
- copy(import_node_path29.default.resolve(appDir, module2.srcPath));
19683
+ copy(import_node_path30.default.resolve(appDir, module2.srcPath));
19541
19684
  }
19542
- return import_node_path29.default.join(target, import_node_path29.default.relative(repoRoot, appDir));
19685
+ return import_node_path30.default.join(target, import_node_path30.default.relative(repoRoot, appDir));
19543
19686
  }
19544
19687
  function executable(value) {
19545
- const candidates = value.includes(import_node_path29.default.sep) ? [import_node_path29.default.resolve(value)] : (process.env.PATH ?? "").split(import_node_path29.default.delimiter).map((dir) => import_node_path29.default.join(dir, value));
19688
+ const candidates = value.includes(import_node_path30.default.sep) ? [import_node_path30.default.resolve(value)] : (process.env.PATH ?? "").split(import_node_path30.default.delimiter).map((dir) => import_node_path30.default.join(dir, value));
19546
19689
  for (const file of candidates) {
19547
19690
  try {
19548
- (0, import_node_fs24.accessSync)(file, import_node_fs24.constants.X_OK);
19549
- if ((0, import_node_fs24.lstatSync)(file).isFile() || (0, import_node_fs24.lstatSync)(file).isSymbolicLink()) return file;
19691
+ (0, import_node_fs25.accessSync)(file, import_node_fs25.constants.X_OK);
19692
+ if ((0, import_node_fs25.lstatSync)(file).isFile() || (0, import_node_fs25.lstatSync)(file).isSymbolicLink()) return file;
19550
19693
  } catch {
19551
19694
  }
19552
19695
  }
@@ -19555,14 +19698,14 @@ function executable(value) {
19555
19698
  function findHarmonyTools() {
19556
19699
  if (!["darwin", "linux"].includes(process.platform)) throw new Error("HarmonyOS release scripts require macOS or Linux");
19557
19700
  const home = "/Applications/DevEco-Studio.app/Contents";
19558
- const sdk = import_node_path29.default.resolve(process.env.DEVECO_SDK_HOME ?? `${home}/sdk`);
19559
- if (!(0, import_node_fs24.existsSync)(sdk)) throw new Error("HarmonyOS SDK not found; install DevEco Studio or set DEVECO_SDK_HOME");
19701
+ const sdk = import_node_path30.default.resolve(process.env.DEVECO_SDK_HOME ?? `${home}/sdk`);
19702
+ if (!(0, import_node_fs25.existsSync)(sdk)) throw new Error("HarmonyOS SDK not found; install DevEco Studio or set DEVECO_SDK_HOME");
19560
19703
  const tools = { sdk, ohpm: executable(process.env.OHPM_BIN ?? `${home}/tools/ohpm/bin/ohpm`), hvigor: executable(process.env.HVIGORW_BIN ?? `${home}/tools/hvigor/bin/hvigorw`), node: executable(process.env.NODE_BIN ?? process.execPath), java: executable(process.env.JAVA_BIN ?? "java"), signer: process.env.HAP_SIGN_TOOL ?? "" };
19561
19704
  if (!tools.signer) {
19562
19705
  const jars = [];
19563
19706
  const scan = (dir) => {
19564
- for (const entry of (0, import_node_fs24.readdirSync)(dir, { withFileTypes: true })) {
19565
- const file = import_node_path29.default.join(dir, entry.name);
19707
+ for (const entry of (0, import_node_fs25.readdirSync)(dir, { withFileTypes: true })) {
19708
+ const file = import_node_path30.default.join(dir, entry.name);
19566
19709
  if (entry.isDirectory()) scan(file);
19567
19710
  else if (entry.isFile() && entry.name === "hap-sign-tool.jar") jars.push(file);
19568
19711
  }
@@ -19571,15 +19714,15 @@ function findHarmonyTools() {
19571
19714
  if (jars.length !== 1) throw new Error("Set HAP_SIGN_TOOL to the intended hap-sign-tool.jar");
19572
19715
  tools.signer = jars[0];
19573
19716
  }
19574
- tools.signer = import_node_path29.default.resolve(tools.signer);
19575
- if (!(0, import_node_fs24.existsSync)(tools.signer)) throw new Error("HAP_SIGN_TOOL does not exist");
19717
+ tools.signer = import_node_path30.default.resolve(tools.signer);
19718
+ if (!(0, import_node_fs25.existsSync)(tools.signer)) throw new Error("HAP_SIGN_TOOL does not exist");
19576
19719
  executable("bash");
19577
19720
  executable("unzip");
19578
19721
  return tools;
19579
19722
  }
19580
19723
  var runHarmonyCommand = async (command, args, options) => {
19581
- const log = (0, import_node_fs24.openSync)(options.log, "a", 384);
19582
- const output = options.output ? (0, import_node_fs24.openSync)(options.output, "w", 384) : void 0;
19724
+ const log = (0, import_node_fs25.openSync)(options.log, "a", 384);
19725
+ const output = options.output ? (0, import_node_fs25.openSync)(options.output, "w", 384) : void 0;
19583
19726
  try {
19584
19727
  return await new Promise((resolve, reject) => {
19585
19728
  const child = (0, import_node_child_process13.spawn)(command, args, { cwd: options.cwd, env: options.env, detached: process.platform !== "win32", stdio: ["ignore", output ?? (options.capture ? "pipe" : log), log] });
@@ -19605,16 +19748,16 @@ var runHarmonyCommand = async (command, args, options) => {
19605
19748
  };
19606
19749
  child.once("error", () => {
19607
19750
  clean();
19608
- reject(new Error(`Cannot run ${import_node_path29.default.basename(command)}; see ${options.log}`));
19751
+ reject(new Error(`Cannot run ${import_node_path30.default.basename(command)}; see ${options.log}`));
19609
19752
  });
19610
19753
  child.once("close", (code) => {
19611
19754
  clean();
19612
- code === 0 && !oversized ? resolve(text) : reject(new Error(`HarmonyOS ${import_node_path29.default.basename(command)} failed (${code}); see ${options.log}`));
19755
+ code === 0 && !oversized ? resolve(text) : reject(new Error(`HarmonyOS ${import_node_path30.default.basename(command)} failed (${code}); see ${options.log}`));
19613
19756
  });
19614
19757
  });
19615
19758
  } finally {
19616
- (0, import_node_fs24.closeSync)(log);
19617
- if (output !== void 0) (0, import_node_fs24.closeSync)(output);
19759
+ (0, import_node_fs25.closeSync)(log);
19760
+ if (output !== void 0) (0, import_node_fs25.closeSync)(output);
19618
19761
  }
19619
19762
  };
19620
19763
  function signingMaterial(values) {
@@ -19625,7 +19768,7 @@ function signingMaterial(values) {
19625
19768
  return bytes;
19626
19769
  };
19627
19770
  const certificate = decode2("HARMONY_CERTIFICATE_BASE64");
19628
- const fingerprint = new import_node_crypto8.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19771
+ const fingerprint = new import_node_crypto9.X509Certificate(certificate).fingerprint256.replace(/:/g, "");
19629
19772
  return { keystore: decode2("HARMONY_KEYSTORE_BASE64"), certificate, profile: decode2("HARMONY_PROFILE_BASE64"), fingerprint };
19630
19773
  }
19631
19774
  function assertHarmonyMetadata(raw, version) {
@@ -19635,7 +19778,7 @@ function assertHarmonyMetadata(raw, version) {
19635
19778
  var withHarmonyPublicationLock = async (bucket2, key, publish) => {
19636
19779
  if (!/^harmony\/[\w-]+\/[\w-]+\/\.publish-lock\.json$/.test(key)) throw new Error("Invalid HarmonyOS publication lock key");
19637
19780
  await AliyunService.assertUnversionedBucket(bucket2);
19638
- const owner = (0, import_node_crypto8.randomUUID)();
19781
+ const owner = (0, import_node_crypto9.randomUUID)();
19639
19782
  try {
19640
19783
  await AliyunService.uploadJsonObject(bucket2, key, { owner, createdAt: (/* @__PURE__ */ new Date()).toISOString() }, { "x-oss-forbid-overwrite": "true" });
19641
19784
  } catch {
@@ -19658,14 +19801,14 @@ var HarmonyReleaseService = class {
19658
19801
  if (!("type" in service) || service.type !== "harmonyos" || !service.mobile || !("bundleName" in service.mobile)) throw new Error("HarmonyOS requires service.mobile.bundleName");
19659
19802
  if (service.appIds?.length !== 1) throw new Error("HarmonyOS service requires exactly one appIds application identity");
19660
19803
  const application = service.appIds[0];
19661
- const root = options.cwd ? import_node_path29.default.resolve(options.cwd) : resolveRepositoryLocalRoot(service.repository ?? service.mobile.repository ?? "");
19804
+ const root = options.cwd ? import_node_path30.default.resolve(options.cwd) : resolveRepositoryLocalRoot(service.repository ?? service.mobile.repository ?? "");
19662
19805
  const dir = service.dir ?? service.mobile.dir;
19663
19806
  if (!dir) throw new Error("HarmonyOS service requires a source directory");
19664
- const appDir = import_node_path29.default.resolve(root, dir);
19807
+ const appDir = import_node_path30.default.resolve(root, dir);
19665
19808
  if (!inside(root, appDir)) throw new Error("HarmonyOS source must stay inside the repository");
19666
19809
  const version = readHarmonyVersion(appDir, service.mobile.bundleName);
19667
19810
  const script = service.build?.script ?? "scripts/build-release.sh";
19668
- if (import_node_path29.default.isAbsolute(script) || !inside(appDir, import_node_path29.default.resolve(appDir, script)) || (!(0, import_node_fs24.existsSync)(import_node_path29.default.resolve(appDir, script)) || !(0, import_node_fs24.lstatSync)(import_node_path29.default.resolve(appDir, script)).isFile())) throw new Error("HarmonyOS build.script must name an existing script inside the application");
19811
+ if (import_node_path30.default.isAbsolute(script) || !inside(appDir, import_node_path30.default.resolve(appDir, script)) || (!(0, import_node_fs25.existsSync)(import_node_path30.default.resolve(appDir, script)) || !(0, import_node_fs25.lstatSync)(import_node_path30.default.resolve(appDir, script)).isFile())) throw new Error("HarmonyOS build.script must name an existing script inside the application");
19669
19812
  const prefix = `harmony/${service.namespace}/${service.name}`;
19670
19813
  if (![service.namespace, service.name].every((v) => /^[\w-]+$/.test(v))) throw new Error("Invalid HarmonyOS service identity");
19671
19814
  const releasePrefix = `${prefix}/${version.versionName}/${version.versionCode}/`;
@@ -19683,33 +19826,33 @@ var HarmonyReleaseService = class {
19683
19826
  if (!this.registry) throw new Error("HarmonyOS signing requires the service environment registry");
19684
19827
  const { values } = await this.registry.resolveEnv(service.id, { stage: "prod", includeSecretValue: true, includeHost: false });
19685
19828
  const material = signingMaterial(values);
19686
- const outputBase = options.outDir ? import_node_path29.default.resolve(options.outDir) : import_node_path29.default.join(import_node_os13.default.homedir(), ".pmate/harmony-builds", service.namespace, service.name);
19829
+ const outputBase = options.outDir ? import_node_path30.default.resolve(options.outDir) : import_node_path30.default.join(import_node_os14.default.homedir(), ".pmate/harmony-builds", service.namespace, service.name);
19687
19830
  if (inside(appDir, outputBase)) throw new Error("HarmonyOS output must be outside the application source directory");
19688
- (0, import_node_fs24.mkdirSync)(outputBase, { recursive: true, mode: 448 });
19689
- const output = (0, import_node_fs24.mkdtempSync)(import_node_path29.default.join(outputBase, `release-${version.versionCode}-`)), log = import_node_path29.default.join(output, "build.log");
19690
- (0, import_node_fs24.writeFileSync)(log, "", { mode: 384 });
19691
- const temp = (0, import_node_fs24.mkdtempSync)(import_node_path29.default.join(import_node_os13.default.tmpdir(), "pmate-harmony-")), run2 = this.deps.run ?? runHarmonyCommand;
19831
+ (0, import_node_fs25.mkdirSync)(outputBase, { recursive: true, mode: 448 });
19832
+ const output = (0, import_node_fs25.mkdtempSync)(import_node_path30.default.join(outputBase, `release-${version.versionCode}-`)), log = import_node_path30.default.join(output, "build.log");
19833
+ (0, import_node_fs25.writeFileSync)(log, "", { mode: 384 });
19834
+ const temp = (0, import_node_fs25.mkdtempSync)(import_node_path30.default.join(import_node_os14.default.tmpdir(), "pmate-harmony-")), run2 = this.deps.run ?? runHarmonyCommand;
19692
19835
  let artifacts = [];
19693
19836
  try {
19694
- const staged = stageHarmonySources(root, appDir, import_node_path29.default.join(temp, "checkout"));
19837
+ const staged = stageHarmonySources(root, appDir, import_node_path30.default.join(temp, "checkout"));
19695
19838
  for (const relative2 of ["build-profile.json5", "AppScope/app.json5"]) {
19696
- const file = import_node_path29.default.join(staged, relative2);
19697
- (0, import_node_fs24.writeFileSync)(file, JSON.stringify(readJson5(file), null, 2));
19839
+ const file = import_node_path30.default.join(staged, relative2);
19840
+ (0, import_node_fs25.writeFileSync)(file, JSON.stringify(readJson5(file), null, 2));
19698
19841
  }
19699
- const keys = import_node_path29.default.join(temp, "signing");
19700
- (0, import_node_fs24.mkdirSync)(keys, { mode: 448 });
19701
- for (const [name, bytes] of [["release.p12", material.keystore], ["release.cer", material.certificate], ["release.p7b", material.profile]]) (0, import_node_fs24.writeFileSync)(import_node_path29.default.join(keys, name), bytes, { mode: 384 });
19842
+ const keys = import_node_path30.default.join(temp, "signing");
19843
+ (0, import_node_fs25.mkdirSync)(keys, { mode: 448 });
19844
+ for (const [name, bytes] of [["release.p12", material.keystore], ["release.cer", material.certificate], ["release.p7b", material.profile]]) (0, import_node_fs25.writeFileSync)(import_node_path30.default.join(keys, name), bytes, { mode: 384 });
19702
19845
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("HARMONY_")));
19703
- Object.assign(env, { DEVECO_SDK_HOME: tools.sdk, OHPM_BIN: tools.ohpm, HVIGORW_BIN: tools.hvigor, NODE_BIN: tools.node, JAVA_BIN: tools.java, HAP_SIGN_TOOL: tools.signer, HARMONY_KEYSTORE_FILE: import_node_path29.default.join(keys, "release.p12"), HARMONY_CERTIFICATE_FILE: import_node_path29.default.join(keys, "release.cer"), HARMONY_PROFILE_FILE: import_node_path29.default.join(keys, "release.p7b"), HARMONY_STORE_PASSWORD: values.HARMONY_STORE_PASSWORD, HARMONY_KEY_ALIAS: values.HARMONY_KEY_ALIAS, HARMONY_KEY_PASSWORD: values.HARMONY_KEY_PASSWORD, HARMONY_VERSION_NAME: version.versionName, HARMONY_VERSION_CODE: String(version.versionCode), HARMONY_RELEASE_DRY_RUN: "0" });
19846
+ Object.assign(env, { DEVECO_SDK_HOME: tools.sdk, OHPM_BIN: tools.ohpm, HVIGORW_BIN: tools.hvigor, NODE_BIN: tools.node, JAVA_BIN: tools.java, HAP_SIGN_TOOL: tools.signer, HARMONY_KEYSTORE_FILE: import_node_path30.default.join(keys, "release.p12"), HARMONY_CERTIFICATE_FILE: import_node_path30.default.join(keys, "release.cer"), HARMONY_PROFILE_FILE: import_node_path30.default.join(keys, "release.p7b"), HARMONY_STORE_PASSWORD: values.HARMONY_STORE_PASSWORD, HARMONY_KEY_ALIAS: values.HARMONY_KEY_ALIAS, HARMONY_KEY_PASSWORD: values.HARMONY_KEY_PASSWORD, HARMONY_VERSION_NAME: version.versionName, HARMONY_VERSION_CODE: String(version.versionCode), HARMONY_RELEASE_DRY_RUN: "0" });
19704
19847
  const opts = { cwd: staged, env, log };
19705
- await run2("bash", [import_node_path29.default.resolve(staged, script)], opts);
19706
- const dist = import_node_path29.default.join(staged, "dist");
19707
- const files = (0, import_node_fs24.readdirSync)(dist, { withFileTypes: true }).filter((e) => e.isFile() && /\.(app|hap)$/.test(e.name)).map((e) => import_node_path29.default.join(dist, e.name));
19848
+ await run2("bash", [import_node_path30.default.resolve(staged, script)], opts);
19849
+ const dist = import_node_path30.default.join(staged, "dist");
19850
+ const files = (0, import_node_fs25.readdirSync)(dist, { withFileTypes: true }).filter((e) => e.isFile() && /\.(app|hap)$/.test(e.name)).map((e) => import_node_path30.default.join(dist, e.name));
19708
19851
  if (files.length !== 2 || files.filter((f) => f.endsWith(".app")).length !== 1 || files.filter((f) => f.endsWith(".hap")).length !== 1) throw new Error("HarmonyOS build must produce exactly one signed APP and one signed HAP");
19709
19852
  const check = async (file, inspectMetadata) => {
19710
- const id = (0, import_node_crypto8.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path29.default.join(temp, `${id}.cer`);
19711
- await run2(tools.java, ["-jar", tools.signer, "verify-app", "-inFile", file, "-outCertChain", cert, "-outProfile", import_node_path29.default.join(temp, `${id}.p7b`)], opts);
19712
- if (new import_node_crypto8.X509Certificate((0, import_node_fs24.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19853
+ const id = (0, import_node_crypto9.createHash)("sha256").update(file).digest("hex").slice(0, 16), cert = import_node_path30.default.join(temp, `${id}.cer`);
19854
+ await run2(tools.java, ["-jar", tools.signer, "verify-app", "-inFile", file, "-outCertChain", cert, "-outProfile", import_node_path30.default.join(temp, `${id}.p7b`)], opts);
19855
+ if (new import_node_crypto9.X509Certificate((0, import_node_fs25.readFileSync)(cert)).fingerprint256.replace(/:/g, "") !== material.fingerprint) throw new Error("HarmonyOS signer certificate does not match service certificate");
19713
19856
  if (inspectMetadata) assertHarmonyMetadata(JSON.parse(await run2("unzip", ["-p", file, "module.json"], { ...opts, capture: true })), version);
19714
19857
  };
19715
19858
  for (const file of files) {
@@ -19719,7 +19862,7 @@ var HarmonyReleaseService = class {
19719
19862
  if (!names.length) throw new Error("HarmonyOS APP contains no package modules");
19720
19863
  for (const [index, name] of names.entries()) {
19721
19864
  if (name.startsWith("/") || name.includes("\\") || name.split("/").includes("..")) throw new Error("Unsafe HarmonyOS archive member");
19722
- const embedded = import_node_path29.default.join(temp, `module-${index}${import_node_path29.default.extname(name)}`);
19865
+ const embedded = import_node_path30.default.join(temp, `module-${index}${import_node_path30.default.extname(name)}`);
19723
19866
  await run2("unzip", ["-p", file, name], { ...opts, output: embedded });
19724
19867
  await check(embedded, true);
19725
19868
  }
@@ -19727,18 +19870,18 @@ var HarmonyReleaseService = class {
19727
19870
  }
19728
19871
  artifacts = [];
19729
19872
  for (const file of files) {
19730
- const name = import_node_path29.default.basename(file);
19873
+ const name = import_node_path30.default.basename(file);
19731
19874
  if (!/^[A-Za-z0-9._-]+\.(app|hap)$/.test(name)) throw new Error("Invalid HarmonyOS artifact filename");
19732
- const size = (0, import_node_fs24.statSync)(file).size;
19875
+ const size = (0, import_node_fs25.statSync)(file).size;
19733
19876
  if (!size) throw new Error("Empty HarmonyOS artifact");
19734
- const target = import_node_path29.default.join(output, name);
19735
- (0, import_node_fs24.cpSync)(file, target);
19736
- const hash = (0, import_node_crypto8.createHash)("sha256");
19737
- for await (const chunk of (0, import_node_fs24.createReadStream)(target)) hash.update(chunk);
19738
- artifacts.push({ name, type: import_node_path29.default.extname(name).slice(1), objectKey: releasePrefix + name, downloadUrl: `${baseUrl}/${releasePrefix}${name}`, sha256: hash.digest("hex"), size });
19877
+ const target = import_node_path30.default.join(output, name);
19878
+ (0, import_node_fs25.cpSync)(file, target);
19879
+ const hash = (0, import_node_crypto9.createHash)("sha256");
19880
+ for await (const chunk of (0, import_node_fs25.createReadStream)(target)) hash.update(chunk);
19881
+ artifacts.push({ name, type: import_node_path30.default.extname(name).slice(1), objectKey: releasePrefix + name, downloadUrl: `${baseUrl}/${releasePrefix}${name}`, sha256: hash.digest("hex"), size });
19739
19882
  }
19740
19883
  } finally {
19741
- (0, import_node_fs24.rmSync)(temp, { recursive: true, force: true });
19884
+ (0, import_node_fs25.rmSync)(temp, { recursive: true, force: true });
19742
19885
  }
19743
19886
  if (options.local) return { ...plan, status: "local", output, log, artifacts };
19744
19887
  let revision;
@@ -19753,21 +19896,21 @@ var HarmonyReleaseService = class {
19753
19896
  if (latest && (latest.serviceId !== service.id || latest.app !== application || latest.bundleName !== version.bundleName || latest.schemaVersion !== 1 || latest.platform !== "harmonyos" || latest.signature !== "verified" || !Number.isSafeInteger(latest.versionCode) || latest.versionCode <= 0)) throw new Error("Invalid existing HarmonyOS update manifest");
19754
19897
  if (latest && latest.versionCode >= version.versionCode) throw new Error("A same or newer HarmonyOS release was published during the build; latest is unchanged");
19755
19898
  if (await read(bucket, `${releasePrefix}release.json`) !== null || (await (this.deps.list ?? AliyunService.listObjects)(bucket, releasePrefix)).length) throw new Error("HarmonyOS release already exists; published objects are immutable");
19756
- for (const artifact of artifacts) await upload(import_node_path29.default.join(output, artifact.name), bucket, artifact.objectKey, { "x-oss-forbid-overwrite": "true" });
19899
+ for (const artifact of artifacts) await upload(import_node_path30.default.join(output, artifact.name), bucket, artifact.objectKey, { "x-oss-forbid-overwrite": "true" });
19757
19900
  await uploadJson(bucket, `${releasePrefix}release.json`, manifest, { "x-oss-forbid-overwrite": "true" });
19758
19901
  await uploadJson(bucket, `${prefix}/latest.json`, manifest);
19759
19902
  });
19760
- (0, import_node_fs24.writeFileSync)(import_node_path29.default.join(output, "release.json"), JSON.stringify(manifest, null, 2));
19903
+ (0, import_node_fs25.writeFileSync)(import_node_path30.default.join(output, "release.json"), JSON.stringify(manifest, null, 2));
19761
19904
  return { ...plan, status: "published", output, log, signature: "verified", artifacts };
19762
19905
  }
19763
19906
  };
19764
19907
 
19765
19908
  // src/services/IosBuildService.ts
19766
19909
  var import_node_child_process14 = require("child_process");
19767
- var import_node_crypto9 = require("crypto");
19768
- var import_node_fs25 = require("fs");
19769
- var import_node_os14 = __toESM(require("os"));
19770
- var import_node_path30 = __toESM(require("path"));
19910
+ var import_node_crypto10 = require("crypto");
19911
+ var import_node_fs26 = require("fs");
19912
+ var import_node_os15 = __toESM(require("os"));
19913
+ var import_node_path31 = __toESM(require("path"));
19771
19914
  function iosBuildInteger(value) {
19772
19915
  if (!/^(0|[1-9]\d*)$/.test(String(value)) || !Number.isSafeInteger(Number(value))) {
19773
19916
  throw new Error(`iOS Build must be a non-negative safe integer: ${String(value)}`);
@@ -19780,9 +19923,9 @@ async function runXcode(args, cwd, logPath) {
19780
19923
  let output = "";
19781
19924
  child.stdout.on("data", (chunk) => {
19782
19925
  if (args.includes("-json") || args.includes("-version")) output += chunk.toString();
19783
- (0, import_node_fs25.appendFileSync)(logPath, chunk);
19926
+ (0, import_node_fs26.appendFileSync)(logPath, chunk);
19784
19927
  });
19785
- child.stderr.on("data", (chunk) => (0, import_node_fs25.appendFileSync)(logPath, chunk));
19928
+ child.stderr.on("data", (chunk) => (0, import_node_fs26.appendFileSync)(logPath, chunk));
19786
19929
  child.on("error", reject);
19787
19930
  child.on("close", (code) => code === 0 ? resolve(output) : reject(new Error(`xcodebuild failed (${code}); see ${logPath}`)));
19788
19931
  });
@@ -19801,18 +19944,18 @@ var IosBuildService = class {
19801
19944
  const repository = service.repository ?? service.mobile?.repository;
19802
19945
  const dir = service.dir ?? service.mobile?.dir;
19803
19946
  if (!dir || !repository && !options.cwd) throw new Error("iOS service requires repository and dir, or --cwd and dir");
19804
- const repoRoot = options.cwd ? import_node_path30.default.resolve(options.cwd) : resolveRepositoryLocalRoot(repository);
19805
- const appDir = import_node_path30.default.resolve(repoRoot, dir);
19806
- if (!(0, import_node_fs25.existsSync)(appDir)) throw new Error(`iOS app dir not found: ${appDir}`);
19947
+ const repoRoot = options.cwd ? import_node_path31.default.resolve(options.cwd) : resolveRepositoryLocalRoot(repository);
19948
+ const appDir = import_node_path31.default.resolve(repoRoot, dir);
19949
+ if (!(0, import_node_fs26.existsSync)(appDir)) throw new Error(`iOS app dir not found: ${appDir}`);
19807
19950
  const explicit = options.project ?? options.workspace;
19808
- const candidates = explicit ? [import_node_path30.default.resolve(appDir, explicit)] : (0, import_node_fs25.readdirSync)(appDir).filter((name) => /\.(xcodeproj|xcworkspace)$/.test(name)).map((name) => import_node_path30.default.join(appDir, name));
19809
- if (candidates.length !== 1 || !(0, import_node_fs25.existsSync)(candidates[0])) throw new Error("Specify exactly one existing --project or --workspace; project discovery is ambiguous or empty");
19951
+ const candidates = explicit ? [import_node_path31.default.resolve(appDir, explicit)] : (0, import_node_fs26.readdirSync)(appDir).filter((name) => /\.(xcodeproj|xcworkspace)$/.test(name)).map((name) => import_node_path31.default.join(appDir, name));
19952
+ if (candidates.length !== 1 || !(0, import_node_fs26.existsSync)(candidates[0])) throw new Error("Specify exactly one existing --project or --workspace; project discovery is ambiguous or empty");
19810
19953
  const project = candidates[0];
19811
- const expectedExtension = options.workspace ? ".xcworkspace" : options.project ? ".xcodeproj" : import_node_path30.default.extname(project);
19812
- if (![".xcodeproj", ".xcworkspace"].includes(expectedExtension) || import_node_path30.default.extname(project) !== expectedExtension) throw new Error("Invalid Xcode project/workspace extension");
19813
- const root = this.deps.stateRoot ?? import_node_path30.default.join(import_node_os14.default.homedir(), ".pmate", "ios-builds");
19814
- (0, import_node_fs25.mkdirSync)(root, { recursive: true, mode: 448 });
19815
- const preflightLog = import_node_path30.default.join(root, `preflight-${process.pid}-${Date.now()}.log`);
19954
+ const expectedExtension = options.workspace ? ".xcworkspace" : options.project ? ".xcodeproj" : import_node_path31.default.extname(project);
19955
+ if (![".xcodeproj", ".xcworkspace"].includes(expectedExtension) || import_node_path31.default.extname(project) !== expectedExtension) throw new Error("Invalid Xcode project/workspace extension");
19956
+ const root = this.deps.stateRoot ?? import_node_path31.default.join(import_node_os15.default.homedir(), ".pmate", "ios-builds");
19957
+ (0, import_node_fs26.mkdirSync)(root, { recursive: true, mode: 448 });
19958
+ const preflightLog = import_node_path31.default.join(root, `preflight-${process.pid}-${Date.now()}.log`);
19816
19959
  const run2 = this.deps.run ?? runXcode;
19817
19960
  await run2(["-version"], appDir, preflightLog);
19818
19961
  const common2 = [expectedExtension === ".xcworkspace" ? "-workspace" : "-project", project, "-scheme", options.scheme, "-configuration", "Release", "-destination", "generic/platform=iOS"];
@@ -19827,19 +19970,19 @@ var IosBuildService = class {
19827
19970
  if (!bundleId || !/^\d+\.\d+(?:\.\d+)?$/.test(version ?? "") || !/^[A-Z0-9]{10}$/.test(team ?? "")) throw new Error("Missing or invalid bundle ID, MARKETING_VERSION or signing team; use --team if needed");
19828
19971
  if (service.mobile && "bundleId" in service.mobile && service.mobile.bundleId !== bundleId) throw new Error("Service bundle ID does not match application target");
19829
19972
  const currentBuild = iosBuildInteger(cfg.CURRENT_PROJECT_VERSION);
19830
- const key = (0, import_node_crypto9.createHash)("sha256").update(bundleId).digest("hex");
19831
- const statePath = import_node_path30.default.join(root, `${key}.json`);
19832
- const lockPath = import_node_path30.default.join(root, `${key}.lock`);
19973
+ const key = (0, import_node_crypto10.createHash)("sha256").update(bundleId).digest("hex");
19974
+ const statePath = import_node_path31.default.join(root, `${key}.json`);
19975
+ const lockPath = import_node_path31.default.join(root, `${key}.lock`);
19833
19976
  let lock;
19834
19977
  try {
19835
- lock = (0, import_node_fs25.openSync)(lockPath, "wx", 384);
19978
+ lock = (0, import_node_fs26.openSync)(lockPath, "wx", 384);
19836
19979
  } catch (error) {
19837
19980
  if (error.code === "EEXIST") throw new Error(`iOS build already locked: ${lockPath}. Remove only after confirming no build is running.`);
19838
19981
  throw error;
19839
19982
  }
19840
19983
  try {
19841
- (0, import_node_fs25.writeFileSync)(lock, JSON.stringify({ pid: process.pid, bundleId }));
19842
- const previous = (0, import_node_fs25.existsSync)(statePath) ? JSON.parse((0, import_node_fs25.readFileSync)(statePath, "utf8")) : void 0;
19984
+ (0, import_node_fs26.writeFileSync)(lock, JSON.stringify({ pid: process.pid, bundleId }));
19985
+ const previous = (0, import_node_fs26.existsSync)(statePath) ? JSON.parse((0, import_node_fs26.readFileSync)(statePath, "utf8")) : void 0;
19843
19986
  if (previous && previous.bundleId !== bundleId) throw new Error("iOS build state bundle ID mismatch");
19844
19987
  const buildsByVersion = { ...previous?.buildsByVersion };
19845
19988
  if (previous) buildsByVersion[previous.version] = Math.max(buildsByVersion[previous.version] ?? 0, iosBuildInteger(previous.build));
@@ -19847,46 +19990,46 @@ var IosBuildService = class {
19847
19990
  if (priorBuild === void 0 && options.lastBuild === void 0) throw new Error("First build for this marketing version requires --last-build <highest Apple build for this version>; use 0 only for a new version. Import again after external uploads or changing machines.");
19848
19991
  const build = Math.max(currentBuild, priorBuild ?? 0, options.lastBuild ?? 0) + 1;
19849
19992
  iosBuildInteger(build);
19850
- const buildDir = import_node_path30.default.join(root, key, `${version}-${build}`);
19851
- (0, import_node_fs25.mkdirSync)(buildDir, { recursive: true, mode: 448 });
19852
- const archivePath = import_node_path30.default.join(buildDir, "App.xcarchive");
19853
- const logPath = import_node_path30.default.join(buildDir, "build.log");
19993
+ const buildDir = import_node_path31.default.join(root, key, `${version}-${build}`);
19994
+ (0, import_node_fs26.mkdirSync)(buildDir, { recursive: true, mode: 448 });
19995
+ const archivePath = import_node_path31.default.join(buildDir, "App.xcarchive");
19996
+ const logPath = import_node_path31.default.join(buildDir, "build.log");
19854
19997
  buildsByVersion[version] = build;
19855
19998
  const state = { bundleId, version, build, buildsByVersion, status: "reserved", archivePath, logPath };
19856
19999
  const persist = () => {
19857
20000
  const temp = `${statePath}.${process.pid}.tmp`;
19858
- (0, import_node_fs25.writeFileSync)(temp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
19859
- (0, import_node_fs25.renameSync)(temp, statePath);
20001
+ (0, import_node_fs26.writeFileSync)(temp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20002
+ (0, import_node_fs26.renameSync)(temp, statePath);
19860
20003
  };
19861
20004
  persist();
19862
- (0, import_node_fs25.writeFileSync)(logPath, `Service ${service.id}: ${bundleId} ${version} (${build})
20005
+ (0, import_node_fs26.writeFileSync)(logPath, `Service ${service.id}: ${bundleId} ${version} (${build})
19863
20006
  Preflight log: ${preflightLog}
19864
20007
  `, { mode: 384 });
19865
20008
  try {
19866
- await run2([...common2, `CURRENT_PROJECT_VERSION=${build}`, `MARKETING_VERSION=${version}`, "-archivePath", archivePath, "-derivedDataPath", import_node_path30.default.join(buildDir, "DerivedData"), "-allowProvisioningUpdates", "archive"], appDir, logPath);
19867
- const applications = import_node_path30.default.join(archivePath, "Products", "Applications");
19868
- const builtApps = (0, import_node_fs25.readdirSync)(applications).filter((name) => name.endsWith(".app"));
20009
+ await run2([...common2, `CURRENT_PROJECT_VERSION=${build}`, `MARKETING_VERSION=${version}`, "-archivePath", archivePath, "-derivedDataPath", import_node_path31.default.join(buildDir, "DerivedData"), "-allowProvisioningUpdates", "archive"], appDir, logPath);
20010
+ const applications = import_node_path31.default.join(archivePath, "Products", "Applications");
20011
+ const builtApps = (0, import_node_fs26.readdirSync)(applications).filter((name) => name.endsWith(".app"));
19869
20012
  if (builtApps.length !== 1) throw new Error("Archive must contain exactly one application");
19870
- const plist = (0, import_node_fs25.readFileSync)(import_node_path30.default.join(applications, builtApps[0], "Info.plist"));
20013
+ const plist = (0, import_node_fs26.readFileSync)(import_node_path31.default.join(applications, builtApps[0], "Info.plist"));
19871
20014
  const info = await (this.deps.readPlist ?? readPlist)(plist);
19872
20015
  if (info.CFBundleIdentifier !== bundleId || info.CFBundleShortVersionString !== version || String(info.CFBundleVersion) !== String(build)) throw new Error("Archive metadata does not match requested bundle, version and Build; upload stopped");
19873
- const exportPlist = import_node_path30.default.join(buildDir, "ExportOptions.plist");
19874
- (0, import_node_fs25.writeFileSync)(exportPlist, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>method</key><string>app-store-connect</string><key>destination</key><string>upload</string><key>teamID</key><string>${team}</string><key>signingStyle</key><string>automatic</string><key>manageAppVersionAndBuildNumber</key><false/><key>uploadSymbols</key><true/></dict></plist>`);
19875
- await run2(["-exportArchive", "-archivePath", archivePath, "-exportOptionsPlist", exportPlist, "-exportPath", import_node_path30.default.join(buildDir, "export"), "-allowProvisioningUpdates"], appDir, logPath);
20016
+ const exportPlist = import_node_path31.default.join(buildDir, "ExportOptions.plist");
20017
+ (0, import_node_fs26.writeFileSync)(exportPlist, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>method</key><string>app-store-connect</string><key>destination</key><string>upload</string><key>teamID</key><string>${team}</string><key>signingStyle</key><string>automatic</string><key>manageAppVersionAndBuildNumber</key><false/><key>uploadSymbols</key><true/></dict></plist>`);
20018
+ await run2(["-exportArchive", "-archivePath", archivePath, "-exportOptionsPlist", exportPlist, "-exportPath", import_node_path31.default.join(buildDir, "export"), "-allowProvisioningUpdates"], appDir, logPath);
19876
20019
  state.status = "uploaded-processing";
19877
20020
  persist();
19878
20021
  return { serviceId: service.id, bundleId, version, build, status: "uploaded-processing", archivePath, logPath };
19879
20022
  } catch (error) {
19880
20023
  state.status = "failed";
19881
20024
  persist();
19882
- (0, import_node_fs25.appendFileSync)(logPath, `
20025
+ (0, import_node_fs26.appendFileSync)(logPath, `
19883
20026
  ${String(error)}
19884
20027
  `);
19885
20028
  throw new Error(`iOS Build ${build} failed; sequence reserved. See ${logPath}. ${String(error)}`);
19886
20029
  }
19887
20030
  } finally {
19888
- (0, import_node_fs25.closeSync)(lock);
19889
- (0, import_node_fs25.unlinkSync)(lockPath);
20031
+ (0, import_node_fs26.closeSync)(lock);
20032
+ (0, import_node_fs26.unlinkSync)(lockPath);
19890
20033
  }
19891
20034
  }
19892
20035
  };
@@ -19938,9 +20081,9 @@ var NativeServiceDeploy = class {
19938
20081
  const repository = service.repository ?? service.mobile?.repository;
19939
20082
  const dir = service.dir ?? service.mobile?.dir;
19940
20083
  if (!dir || !repository && !args.cwd) throw new Error("Native service requires repository and dir");
19941
- const root = args.cwd ? import_node_path31.default.resolve(args.cwd) : resolveRepositoryLocalRoot(repository);
19942
- const appDir = import_node_path31.default.resolve(root, dir);
19943
- if (!(0, import_node_fs26.existsSync)(appDir)) throw new Error(`Service source directory not found: ${appDir}`);
20084
+ const root = args.cwd ? import_node_path32.default.resolve(args.cwd) : resolveRepositoryLocalRoot(repository);
20085
+ const appDir = import_node_path32.default.resolve(root, dir);
20086
+ if (!(0, import_node_fs27.existsSync)(appDir)) throw new Error(`Service source directory not found: ${appDir}`);
19944
20087
  const settings = service.build ?? {};
19945
20088
  if (service.type === "harmonyos") {
19946
20089
  rejectNativeOverrides(args, ["dryRun", "local", "outDir"]);
@@ -19974,10 +20117,10 @@ var NativeServiceDeploy = class {
19974
20117
  const options2 = {
19975
20118
  id: app,
19976
20119
  target: "electron",
19977
- config: args.config ? import_node_path31.default.resolve(args.config) : import_node_path31.default.resolve(appDir, settings.config ?? "desktop.config.json"),
20120
+ config: args.config ? import_node_path32.default.resolve(args.config) : import_node_path32.default.resolve(appDir, settings.config ?? "desktop.config.json"),
19978
20121
  platform: args.platform ?? settings.platform ?? (process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform),
19979
20122
  arch: args.arch ?? settings.arch ?? process.arch,
19980
- outDir: args.outDir ? import_node_path31.default.resolve(args.outDir) : import_node_path31.default.join(root, "release", service.name),
20123
+ outDir: args.outDir ? import_node_path32.default.resolve(args.outDir) : import_node_path32.default.join(root, "release", service.name),
19981
20124
  signed: !args.unsigned,
19982
20125
  dir: !!args.dir,
19983
20126
  dryRun: !!args.dryRun,
@@ -20090,9 +20233,9 @@ async function requestDeveloperLogTool(tool, params, fetcher = fetch, delegate)
20090
20233
  }
20091
20234
 
20092
20235
  // src/services/ServiceRuntimeRunner.ts
20093
- var import_node_fs27 = require("fs");
20094
- var import_node_os15 = __toESM(require("os"));
20095
- var import_node_path32 = __toESM(require("path"));
20236
+ var import_node_fs28 = require("fs");
20237
+ var import_node_os16 = __toESM(require("os"));
20238
+ var import_node_path33 = __toESM(require("path"));
20096
20239
  var import_node_child_process15 = require("child_process");
20097
20240
  var import_node_readline = require("readline");
20098
20241
  var import_chalk3 = __toESM(require("chalk"));
@@ -20592,7 +20735,7 @@ var ServiceRuntimeRunner = class {
20592
20735
  }
20593
20736
  resolveRepoRoot(service, cwd) {
20594
20737
  if (cwd) {
20595
- return import_node_path32.default.resolve(process.cwd(), cwd);
20738
+ return import_node_path33.default.resolve(process.cwd(), cwd);
20596
20739
  }
20597
20740
  const repository = this.getType(service) === "vite" || this.getType(service) === "static" ? this.getRepoStaticSite(service).repository.trim() : this.getType(service) === "fc" ? this.getFc(service).repository?.trim() : this.getType(service) === "ios" || this.getType(service) === "android" ? void 0 : this.getNetwork(service).repository?.trim();
20598
20741
  if (repository) {
@@ -20600,8 +20743,8 @@ var ServiceRuntimeRunner = class {
20600
20743
  if (selected) return selected;
20601
20744
  const repoName = repository.replace(/\/+$/, "").split("/").pop()?.replace(/\.git$/i, "");
20602
20745
  if (repoName) {
20603
- const candidate = import_node_path32.default.join(import_node_os15.default.homedir(), "dev", "pmate", repoName);
20604
- if ((0, import_node_fs27.existsSync)(candidate)) {
20746
+ const candidate = import_node_path33.default.join(import_node_os16.default.homedir(), "dev", "pmate", repoName);
20747
+ if ((0, import_node_fs28.existsSync)(candidate)) {
20605
20748
  return candidate;
20606
20749
  }
20607
20750
  }
@@ -20614,15 +20757,15 @@ var ServiceRuntimeRunner = class {
20614
20757
  if (!dir) {
20615
20758
  throw new Error(`Missing service dir for ${service.id}`);
20616
20759
  }
20617
- return import_node_path32.default.resolve(repoRoot, dir);
20760
+ return import_node_path33.default.resolve(repoRoot, dir);
20618
20761
  }
20619
20762
  async deployVite(service, options) {
20620
20763
  this.assertDeployableStaticSite(service);
20621
20764
  const repoRoot = this.resolveViteDeployRoot(service);
20622
20765
  await this.checkoutViteMain(service, repoRoot);
20623
20766
  const appDir = this.resolveLocalDir(service, repoRoot);
20624
- const packageJsonPath = import_node_path32.default.join(appDir, "package.json");
20625
- if (!(0, import_node_fs27.existsSync)(packageJsonPath)) {
20767
+ const packageJsonPath = import_node_path33.default.join(appDir, "package.json");
20768
+ if (!(0, import_node_fs28.existsSync)(packageJsonPath)) {
20626
20769
  throw new Error(`No package.json found at ${packageJsonPath}`);
20627
20770
  }
20628
20771
  const pkg2 = this.loadPackageJson(packageJsonPath);
@@ -20637,8 +20780,8 @@ var ServiceRuntimeRunner = class {
20637
20780
  repoRoot,
20638
20781
  buildEnv
20639
20782
  );
20640
- const distDir = import_node_path32.default.join(appDir, "dist");
20641
- if (!(0, import_node_fs27.existsSync)(distDir)) {
20783
+ const distDir = import_node_path33.default.join(appDir, "dist");
20784
+ if (!(0, import_node_fs28.existsSync)(distDir)) {
20642
20785
  throw new Error(`No dist directory found at ${distDir}`);
20643
20786
  }
20644
20787
  const site = this.getSite(service);
@@ -20653,7 +20796,7 @@ var ServiceRuntimeRunner = class {
20653
20796
  if (!/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/.test(repository)) {
20654
20797
  throw new Error(`Invalid repository: ${repository}; expected owner/name`);
20655
20798
  }
20656
- return import_node_path32.default.join(import_node_os15.default.homedir(), ".pmate", "service-deploy", "repos", repository.toLowerCase());
20799
+ return import_node_path33.default.join(import_node_os16.default.homedir(), ".pmate", "service-deploy", "repos", repository.toLowerCase());
20657
20800
  }
20658
20801
  async checkoutViteMain(service, repoRoot) {
20659
20802
  const repository = this.getRepoStaticSite(service).repository;
@@ -20665,9 +20808,9 @@ var ServiceRuntimeRunner = class {
20665
20808
  gitEnv.GIT_CONFIG_KEY_0 = "http.https://github.com/.extraheader";
20666
20809
  gitEnv.GIT_CONFIG_VALUE_0 = `Authorization: Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
20667
20810
  }
20668
- if (!(0, import_node_fs27.existsSync)(repoRoot)) {
20669
- (0, import_node_fs27.mkdirSync)(import_node_path32.default.dirname(repoRoot), { recursive: true });
20670
- await this.runCommandWithEnv("git", ["clone", "--branch", "main", "--single-branch", "--", repoUrl, repoRoot], import_node_path32.default.dirname(repoRoot), gitEnv);
20811
+ if (!(0, import_node_fs28.existsSync)(repoRoot)) {
20812
+ (0, import_node_fs28.mkdirSync)(import_node_path33.default.dirname(repoRoot), { recursive: true });
20813
+ await this.runCommandWithEnv("git", ["clone", "--branch", "main", "--single-branch", "--", repoUrl, repoRoot], import_node_path33.default.dirname(repoRoot), gitEnv);
20671
20814
  }
20672
20815
  ui.info(`Deployment checkout: ${repoRoot}`);
20673
20816
  ui.info(`Updating ${repository} to latest main for Vite deployment`);
@@ -20697,8 +20840,8 @@ var ServiceRuntimeRunner = class {
20697
20840
  async deployStatic(service, options) {
20698
20841
  this.assertDeployableStaticSite(service);
20699
20842
  const appDir = this.resolveLocalDir(service, options.cwd);
20700
- const srcDir = import_node_path32.default.join(appDir, "src");
20701
- if (!(0, import_node_fs27.existsSync)(srcDir)) {
20843
+ const srcDir = import_node_path33.default.join(appDir, "src");
20844
+ if (!(0, import_node_fs28.existsSync)(srcDir)) {
20702
20845
  throw new Error(`No src directory found at ${srcDir}`);
20703
20846
  }
20704
20847
  const site = this.getSite(service);
@@ -20732,8 +20875,8 @@ var ServiceRuntimeRunner = class {
20732
20875
  this.validateFcConfig(service, fc);
20733
20876
  const repoRoot = this.resolveRepoRoot(service, options.cwd);
20734
20877
  const appDir = this.resolveLocalDir(service, options.cwd);
20735
- const packageJsonPath = import_node_path32.default.join(appDir, "package.json");
20736
- if (!(0, import_node_fs27.existsSync)(packageJsonPath)) {
20878
+ const packageJsonPath = import_node_path33.default.join(appDir, "package.json");
20879
+ if (!(0, import_node_fs28.existsSync)(packageJsonPath)) {
20737
20880
  throw new Error(`No package.json found at ${packageJsonPath}`);
20738
20881
  }
20739
20882
  const pkg2 = this.loadPackageJson(packageJsonPath);
@@ -20786,15 +20929,15 @@ var ServiceRuntimeRunner = class {
20786
20929
  const repoRoot = this.resolveRepoRoot(service, options.cwd);
20787
20930
  const appDir = this.resolveLocalDir(service, options.cwd);
20788
20931
  await this.ensurePnpmWorkspaceRoot(repoRoot);
20789
- const configPath = import_node_path32.default.join(appDir, fc.configFile ?? "s.yaml");
20790
- if (!(0, import_node_fs27.existsSync)(configPath)) {
20932
+ const configPath = import_node_path33.default.join(appDir, fc.configFile ?? "s.yaml");
20933
+ if (!(0, import_node_fs28.existsSync)(configPath)) {
20791
20934
  throw new Error(`Missing FC config file at ${configPath}`);
20792
20935
  }
20793
- const packageJsonPath = import_node_path32.default.join(appDir, "package.json");
20794
- if (!(0, import_node_fs27.existsSync)(packageJsonPath)) {
20936
+ const packageJsonPath = import_node_path33.default.join(appDir, "package.json");
20937
+ if (!(0, import_node_fs28.existsSync)(packageJsonPath)) {
20795
20938
  throw new Error(`No package.json found at ${packageJsonPath}`);
20796
20939
  }
20797
- const rawConfig = (0, import_node_fs27.readFileSync)(configPath, "utf8");
20940
+ const rawConfig = (0, import_node_fs28.readFileSync)(configPath, "utf8");
20798
20941
  if (!rawConfig.includes(fc.functionName)) {
20799
20942
  throw new Error(`FC config ${configPath} does not mention functionName ${fc.functionName}`);
20800
20943
  }
@@ -21084,7 +21227,7 @@ var ServiceRuntimeRunner = class {
21084
21227
  const serverAddress = await resolveServerAddress(server);
21085
21228
  const templateName = exposeType === "websocket" ? "nginx.ws.template" : exposeType === "mixed" ? "nginx.mixed.template" : "nginx.rest.template";
21086
21229
  const templatePath = this.resolveTemplatePath(templateName);
21087
- const template = (0, import_node_fs27.readFileSync)(templatePath, "utf8");
21230
+ const template = (0, import_node_fs28.readFileSync)(templatePath, "utf8");
21088
21231
  const host = `${subdomain}.${("domain" in network ? network.domain?.trim() : void 0) || "pmate.chat"}`;
21089
21232
  const rendered = template.replace(/\$\{\{PORT\}\}/g, String(port)).replace(/\$\{\{HOSTS\}\}/g, host).replace(/\$\{\{HOST\}\}/g, host);
21090
21233
  const remotePath = `/etc/nginx/sites-enabled/${subdomain}.conf`;
@@ -21116,11 +21259,11 @@ var ServiceRuntimeRunner = class {
21116
21259
  }
21117
21260
  if (config.ensurePackageJson) {
21118
21261
  const appDir = this.resolveLocalDir(service, options.cwd);
21119
- const packageJsonPath = import_node_path32.default.join(appDir, "package.json");
21120
- if (!(0, import_node_fs27.existsSync)(packageJsonPath)) {
21262
+ const packageJsonPath = import_node_path33.default.join(appDir, "package.json");
21263
+ if (!(0, import_node_fs28.existsSync)(packageJsonPath)) {
21121
21264
  throw new Error(`Missing package.json at ${packageJsonPath}`);
21122
21265
  }
21123
- const pkgStat = (0, import_node_fs27.statSync)(packageJsonPath);
21266
+ const pkgStat = (0, import_node_fs28.statSync)(packageJsonPath);
21124
21267
  if (!pkgStat.isFile()) {
21125
21268
  throw new Error(`package.json is not a file at ${packageJsonPath}`);
21126
21269
  }
@@ -21576,12 +21719,12 @@ var ServiceRuntimeRunner = class {
21576
21719
  }
21577
21720
  resolveTemplatePath(templateName) {
21578
21721
  const candidates = [
21579
- import_node_path32.default.join(__dirname, "..", "templates", templateName),
21580
- import_node_path32.default.join(__dirname, "..", "src", "templates", templateName),
21581
- import_node_path32.default.join(__dirname, "templates", templateName)
21722
+ import_node_path33.default.join(__dirname, "..", "templates", templateName),
21723
+ import_node_path33.default.join(__dirname, "..", "src", "templates", templateName),
21724
+ import_node_path33.default.join(__dirname, "templates", templateName)
21582
21725
  ];
21583
21726
  for (const candidate of candidates) {
21584
- if ((0, import_node_fs27.existsSync)(candidate)) {
21727
+ if ((0, import_node_fs28.existsSync)(candidate)) {
21585
21728
  return candidate;
21586
21729
  }
21587
21730
  }
@@ -21613,7 +21756,7 @@ var ServiceRuntimeRunner = class {
21613
21756
  });
21614
21757
  }
21615
21758
  loadPackageJson(packageJsonPath) {
21616
- const raw = (0, import_node_fs27.readFileSync)(packageJsonPath, "utf8");
21759
+ const raw = (0, import_node_fs28.readFileSync)(packageJsonPath, "utf8");
21617
21760
  const parsed = JSON.parse(raw);
21618
21761
  if (!parsed || typeof parsed !== "object") {
21619
21762
  throw new Error(`Invalid package.json at ${packageJsonPath}`);
@@ -21622,7 +21765,7 @@ var ServiceRuntimeRunner = class {
21622
21765
  }
21623
21766
  writePackageJson(packageJsonPath, data) {
21624
21767
  const serialized = JSON.stringify(data, null, 2);
21625
- (0, import_node_fs27.writeFileSync)(packageJsonPath, `${serialized}
21768
+ (0, import_node_fs28.writeFileSync)(packageJsonPath, `${serialized}
21626
21769
  `, "utf8");
21627
21770
  }
21628
21771
  validateFcConfig(service, fc) {
@@ -21649,8 +21792,8 @@ var ServiceRuntimeRunner = class {
21649
21792
  }
21650
21793
  }
21651
21794
  async ensurePnpmWorkspaceRoot(repoRoot) {
21652
- const workspacePath = import_node_path32.default.join(repoRoot, "pnpm-workspace.yaml");
21653
- if (!(0, import_node_fs27.existsSync)(workspacePath)) {
21795
+ const workspacePath = import_node_path33.default.join(repoRoot, "pnpm-workspace.yaml");
21796
+ if (!(0, import_node_fs28.existsSync)(workspacePath)) {
21654
21797
  throw new Error(`Missing pnpm-workspace.yaml at ${workspacePath}`);
21655
21798
  }
21656
21799
  }
@@ -21724,16 +21867,16 @@ var ServiceRuntimeRunner = class {
21724
21867
  if (!privateKeyPath) {
21725
21868
  throw new Error("Missing ssl.prv in ~/.pmate/config.yaml.");
21726
21869
  }
21727
- if (!(0, import_node_fs27.existsSync)(certificatePath)) {
21870
+ if (!(0, import_node_fs28.existsSync)(certificatePath)) {
21728
21871
  throw new Error(`SSL certificate file not found: ${certificatePath}`);
21729
21872
  }
21730
- if (!(0, import_node_fs27.existsSync)(privateKeyPath)) {
21873
+ if (!(0, import_node_fs28.existsSync)(privateKeyPath)) {
21731
21874
  throw new Error(`SSL private key file not found: ${privateKeyPath}`);
21732
21875
  }
21733
21876
  return {
21734
21877
  certName: host,
21735
- certificate: (0, import_node_fs27.readFileSync)(certificatePath, "utf8"),
21736
- privateKey: (0, import_node_fs27.readFileSync)(privateKeyPath, "utf8")
21878
+ certificate: (0, import_node_fs28.readFileSync)(certificatePath, "utf8"),
21879
+ privateKey: (0, import_node_fs28.readFileSync)(privateKeyPath, "utf8")
21737
21880
  };
21738
21881
  }
21739
21882
  resolveFcProtocol(fc, certConfig) {
@@ -21814,7 +21957,7 @@ var ServiceRuntimeRunner = class {
21814
21957
  });
21815
21958
  }
21816
21959
  runRemoteCommand(server, command) {
21817
- if (server === "local") return this.runCommandWithEnv("bash", ["-c", command], import_node_os15.default.homedir());
21960
+ if (server === "local") return this.runCommandWithEnv("bash", ["-c", command], import_node_os16.default.homedir());
21818
21961
  return new Promise((resolve, reject) => {
21819
21962
  const target = `pmate@${server}`;
21820
21963
  const child = (0, import_node_child_process15.spawn)("ssh", [...deploySshIdentityArgs(), target, "bash -ls"], { stdio: ["pipe", "inherit", "inherit"] });
@@ -21881,8 +22024,8 @@ function remoteGitAuthorization(command, token) {
21881
22024
  function deploySshIdentityArgs(env = process.env) {
21882
22025
  const identity = env.PMATE_DEPLOY_SSH_IDENTITY_FILE?.trim();
21883
22026
  if (!identity) return [];
21884
- const file = identity.startsWith("~/") ? import_node_path32.default.join(import_node_os15.default.homedir(), identity.slice(2)) : identity;
21885
- if (!import_node_path32.default.isAbsolute(file) || !(0, import_node_fs27.existsSync)(file) || !(0, import_node_fs27.statSync)(file).isFile()) {
22027
+ const file = identity.startsWith("~/") ? import_node_path33.default.join(import_node_os16.default.homedir(), identity.slice(2)) : identity;
22028
+ if (!import_node_path33.default.isAbsolute(file) || !(0, import_node_fs28.existsSync)(file) || !(0, import_node_fs28.statSync)(file).isFile()) {
21886
22029
  throw new Error("PMATE_DEPLOY_SSH_IDENTITY_FILE must reference an existing absolute local file");
21887
22030
  }
21888
22031
  return ["-i", file, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes"];
@@ -22051,6 +22194,12 @@ var ServiceCommandHandler = class {
22051
22194
  this.renderJson(payload, args.json);
22052
22195
  return;
22053
22196
  }
22197
+ case "testflight": {
22198
+ const record = await registry.getService(args.namespace, args.name);
22199
+ const result = await new TestFlightService().execute(record, args);
22200
+ this.renderJson(result, true);
22201
+ return;
22202
+ }
22054
22203
  case "deploy": {
22055
22204
  const record = await registry.getService(args.namespace, args.name);
22056
22205
  if ("type" in record && (record.type === "electron" || record.type === "ios" || record.type === "android" || record.type === "harmonyos")) {
@@ -22222,7 +22371,7 @@ var ServiceCommandHandler = class {
22222
22371
  format: "dotenv"
22223
22372
  }
22224
22373
  );
22225
- const outputPath = import_node_path33.default.resolve(process.cwd(), args.output);
22374
+ const outputPath = import_node_path34.default.resolve(process.cwd(), args.output);
22226
22375
  await (0, import_promises5.writeFile)(outputPath, payload.content, "utf8");
22227
22376
  ui.success(`Wrote env file for ${args.appId} to ${outputPath}`);
22228
22377
  this.renderJson({ ...payload, output: outputPath }, args.json);
@@ -22449,11 +22598,11 @@ var ServiceCommandHandler = class {
22449
22598
  return (baseUrl2 || process.env.PMATE_APPS_API_BASE_URL || "https://apps-api.pmate.chat").replace(/\/+$/, "");
22450
22599
  }
22451
22600
  readJsonFile(filePath) {
22452
- const absolutePath = import_node_path33.default.resolve(process.cwd(), filePath);
22453
- if (!(0, import_node_fs28.existsSync)(absolutePath)) {
22601
+ const absolutePath = import_node_path34.default.resolve(process.cwd(), filePath);
22602
+ if (!(0, import_node_fs29.existsSync)(absolutePath)) {
22454
22603
  throw new Error(`JSON file not found: ${absolutePath}`);
22455
22604
  }
22456
- const raw = (0, import_node_fs28.readFileSync)(absolutePath, "utf8");
22605
+ const raw = (0, import_node_fs29.readFileSync)(absolutePath, "utf8");
22457
22606
  try {
22458
22607
  return JSON.parse(raw);
22459
22608
  } catch (error) {
@@ -23214,9 +23363,9 @@ var RoleCommandHandler = class {
23214
23363
  };
23215
23364
 
23216
23365
  // src/commands/AccountCommandHandler.ts
23217
- var import_node_fs29 = require("fs");
23218
- var import_node_crypto10 = require("crypto");
23219
- var import_node_path34 = __toESM(require("path"));
23366
+ var import_node_fs30 = require("fs");
23367
+ var import_node_crypto11 = require("crypto");
23368
+ var import_node_path35 = __toESM(require("path"));
23220
23369
  init_sessionStore();
23221
23370
  var AccountCommandHandler = class {
23222
23371
  async handle(args) {
@@ -23224,9 +23373,9 @@ var AccountCommandHandler = class {
23224
23373
  case "bot-keygen": {
23225
23374
  const keyFile = this.generateBotKeyFile(args.app, args.name);
23226
23375
  const outPath = args.out ? this.resolveFilePath(args.out) : this.resolveDefaultBotKeyPath(args.app, args.name);
23227
- (0, import_node_fs29.mkdirSync)(import_node_path34.default.dirname(outPath), { recursive: true });
23228
- (0, import_node_fs29.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
23229
- (0, import_node_fs29.chmodSync)(outPath, 384);
23376
+ (0, import_node_fs30.mkdirSync)(import_node_path35.default.dirname(outPath), { recursive: true });
23377
+ (0, import_node_fs30.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
23378
+ (0, import_node_fs30.chmodSync)(outPath, 384);
23230
23379
  if (!args.json) {
23231
23380
  ui.success(`Bot key saved to ${outPath}`);
23232
23381
  }
@@ -23831,10 +23980,10 @@ var AccountCommandHandler = class {
23831
23980
  throw new Error("Missing visible apps input");
23832
23981
  }
23833
23982
  const absolutePath = this.resolveFilePath(args.filePath);
23834
- if (!(0, import_node_fs29.existsSync)(absolutePath)) {
23983
+ if (!(0, import_node_fs30.existsSync)(absolutePath)) {
23835
23984
  throw new Error(`JSON file not found: ${absolutePath}`);
23836
23985
  }
23837
- const raw = (0, import_node_fs29.readFileSync)(absolutePath, "utf8");
23986
+ const raw = (0, import_node_fs30.readFileSync)(absolutePath, "utf8");
23838
23987
  let parsed;
23839
23988
  try {
23840
23989
  parsed = JSON.parse(raw);
@@ -23848,19 +23997,19 @@ var AccountCommandHandler = class {
23848
23997
  return parsed;
23849
23998
  }
23850
23999
  resolveFilePath(filePath) {
23851
- return import_node_path34.default.resolve(process.cwd(), filePath);
24000
+ return import_node_path35.default.resolve(process.cwd(), filePath);
23852
24001
  }
23853
24002
  resolveDefaultBotKeyPath(app, name) {
23854
- return import_node_path34.default.join(this.homeDir(), ".pmate", "bots", app, `${name}.bot-key.json`);
24003
+ return import_node_path35.default.join(this.homeDir(), ".pmate", "bots", app, `${name}.bot-key.json`);
23855
24004
  }
23856
24005
  resolveDefaultAccessKeyPath(app, name) {
23857
- return import_node_path34.default.join(this.homeDir(), ".pmate", "access-keys", app, `${name}.access-key.json`);
24006
+ return import_node_path35.default.join(this.homeDir(), ".pmate", "access-keys", app, `${name}.access-key.json`);
23858
24007
  }
23859
24008
  homeDir() {
23860
24009
  return process.env.HOME || process.env.USERPROFILE || process.cwd();
23861
24010
  }
23862
24011
  generateBotKeyFile(app, name) {
23863
- const { publicKey, privateKey } = (0, import_node_crypto10.generateKeyPairSync)("ed25519");
24012
+ const { publicKey, privateKey } = (0, import_node_crypto11.generateKeyPairSync)("ed25519");
23864
24013
  return {
23865
24014
  type: "pmate-bot-key",
23866
24015
  version: 1,
@@ -23874,14 +24023,14 @@ var AccountCommandHandler = class {
23874
24023
  }
23875
24024
  renameDefaultBotKeyFile(app, name, newName) {
23876
24025
  const oldPath = this.resolveDefaultBotKeyPath(app, name);
23877
- if (!(0, import_node_fs29.existsSync)(oldPath)) {
24026
+ if (!(0, import_node_fs30.existsSync)(oldPath)) {
23878
24027
  return void 0;
23879
24028
  }
23880
24029
  const keyFile = this.readBotKeyFile(oldPath, app, name);
23881
24030
  const newPath = this.resolveDefaultBotKeyPath(app, newName);
23882
- (0, import_node_fs29.mkdirSync)(import_node_path34.default.dirname(newPath), { recursive: true, mode: 448 });
23883
- (0, import_node_fs29.writeFileSync)(newPath, JSON.stringify({ ...keyFile, name: newName }, null, 2));
23884
- (0, import_node_fs29.chmodSync)(newPath, 384);
24031
+ (0, import_node_fs30.mkdirSync)(import_node_path35.default.dirname(newPath), { recursive: true, mode: 448 });
24032
+ (0, import_node_fs30.writeFileSync)(newPath, JSON.stringify({ ...keyFile, name: newName }, null, 2));
24033
+ (0, import_node_fs30.chmodSync)(newPath, 384);
23885
24034
  return newPath;
23886
24035
  }
23887
24036
  readBotKeyFile(filePath, expectedApp, expectedName) {
@@ -23889,10 +24038,10 @@ var AccountCommandHandler = class {
23889
24038
  throw new Error("Missing bot key file");
23890
24039
  }
23891
24040
  const absolutePath = this.resolveFilePath(filePath);
23892
- if (!(0, import_node_fs29.existsSync)(absolutePath)) {
24041
+ if (!(0, import_node_fs30.existsSync)(absolutePath)) {
23893
24042
  throw new Error(`Bot key file not found: ${absolutePath}`);
23894
24043
  }
23895
- const parsed = JSON.parse((0, import_node_fs29.readFileSync)(absolutePath, "utf8"));
24044
+ const parsed = JSON.parse((0, import_node_fs30.readFileSync)(absolutePath, "utf8"));
23896
24045
  if (parsed.type !== "pmate-bot-key" || parsed.version !== 1 || parsed.algorithm !== "ed25519" || !parsed.publicKey || !parsed.privateKey) {
23897
24046
  throw new Error(`Invalid PMate bot key file: ${absolutePath}`);
23898
24047
  }
@@ -23909,10 +24058,10 @@ var AccountCommandHandler = class {
23909
24058
  throw new Error("Missing access key file");
23910
24059
  }
23911
24060
  const absolutePath = this.resolveFilePath(filePath);
23912
- if (!(0, import_node_fs29.existsSync)(absolutePath)) {
24061
+ if (!(0, import_node_fs30.existsSync)(absolutePath)) {
23913
24062
  throw new Error(`Access key file not found: ${absolutePath}`);
23914
24063
  }
23915
- const parsed = JSON.parse((0, import_node_fs29.readFileSync)(absolutePath, "utf8"));
24064
+ const parsed = JSON.parse((0, import_node_fs30.readFileSync)(absolutePath, "utf8"));
23916
24065
  if (parsed.type !== "pmate-access-key" || parsed.version !== 1 || !parsed.id || !parsed.app || !parsed.secret || !parsed.expiresAt) {
23917
24066
  throw new Error(`Invalid PMate access key file: ${absolutePath}`);
23918
24067
  }
@@ -23934,9 +24083,9 @@ var AccountCommandHandler = class {
23934
24083
  createdAt: result.key.createdAt
23935
24084
  };
23936
24085
  const outPath = out ? this.resolveFilePath(out) : this.resolveDefaultAccessKeyPath(result.key.app, result.key.name);
23937
- (0, import_node_fs29.mkdirSync)(import_node_path34.default.dirname(outPath), { recursive: true });
23938
- (0, import_node_fs29.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
23939
- (0, import_node_fs29.chmodSync)(outPath, 384);
24086
+ (0, import_node_fs30.mkdirSync)(import_node_path35.default.dirname(outPath), { recursive: true });
24087
+ (0, import_node_fs30.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
24088
+ (0, import_node_fs30.chmodSync)(outPath, 384);
23940
24089
  }
23941
24090
  renderAccessKeyCreateResult(result, asJson, out) {
23942
24091
  if (asJson) {
@@ -23982,12 +24131,12 @@ var AccountCommandHandler = class {
23982
24131
  });
23983
24132
  }
23984
24133
  signBotChallenge(challenge, privateKey) {
23985
- const key = (0, import_node_crypto10.createPrivateKey)({
24134
+ const key = (0, import_node_crypto11.createPrivateKey)({
23986
24135
  key: Buffer.from(privateKey, "base64url"),
23987
24136
  format: "der",
23988
24137
  type: "pkcs8"
23989
24138
  });
23990
- return (0, import_node_crypto10.sign)(
24139
+ return (0, import_node_crypto11.sign)(
23991
24140
  null,
23992
24141
  Buffer.from(JSON.stringify({
23993
24142
  id: challenge.id,
@@ -24021,8 +24170,8 @@ function encodePathSegment2(value) {
24021
24170
  }
24022
24171
 
24023
24172
  // src/commands/OrgCommandHandler.ts
24024
- var import_node_fs30 = require("fs");
24025
- var import_node_path35 = __toESM(require("path"));
24173
+ var import_node_fs31 = require("fs");
24174
+ var import_node_path36 = __toESM(require("path"));
24026
24175
  init_sessionStore();
24027
24176
  var OrgCommandHandler = class {
24028
24177
  async handle(args) {
@@ -24159,11 +24308,11 @@ var OrgCommandHandler = class {
24159
24308
  if (!filePath) {
24160
24309
  throw new Error(`Missing ${itemLabel} input`);
24161
24310
  }
24162
- const absolutePath = import_node_path35.default.resolve(process.cwd(), filePath);
24163
- if (!(0, import_node_fs30.existsSync)(absolutePath)) {
24311
+ const absolutePath = import_node_path36.default.resolve(process.cwd(), filePath);
24312
+ if (!(0, import_node_fs31.existsSync)(absolutePath)) {
24164
24313
  throw new Error(`JSON file not found: ${absolutePath}`);
24165
24314
  }
24166
- const raw = (0, import_node_fs30.readFileSync)(absolutePath, "utf8");
24315
+ const raw = (0, import_node_fs31.readFileSync)(absolutePath, "utf8");
24167
24316
  let parsed;
24168
24317
  try {
24169
24318
  parsed = JSON.parse(raw);
@@ -24234,9 +24383,9 @@ function encodePathSegment3(value) {
24234
24383
  }
24235
24384
 
24236
24385
  // src/commands/HostCommandHandler.ts
24237
- var import_node_fs31 = require("fs");
24238
- var import_node_os16 = require("os");
24239
- var import_node_path36 = __toESM(require("path"));
24386
+ var import_node_fs32 = require("fs");
24387
+ var import_node_os17 = require("os");
24388
+ var import_node_path37 = __toESM(require("path"));
24240
24389
  var import_node_child_process18 = require("child_process");
24241
24390
  var BLOCK_START = "# >>> pmate host env >>>";
24242
24391
  var BLOCK_END = "# <<< pmate host env <<<";
@@ -24249,7 +24398,7 @@ fi
24249
24398
  ${BLOCK_END}`;
24250
24399
  var HostCommandHandler = class {
24251
24400
  async handle(args) {
24252
- const hostId = normalizeHostId(args.host ?? process.env.PMATE_HOST_ID ?? (0, import_node_os16.hostname)());
24401
+ const hostId = normalizeHostId(args.host ?? process.env.PMATE_HOST_ID ?? (0, import_node_os17.hostname)());
24253
24402
  const client = new ServiceRegistryClient(args.baseUrl);
24254
24403
  if (args.action === "env-list") {
24255
24404
  const items = await client.listHostEnv(hostId);
@@ -25201,6 +25350,42 @@ function parseServiceArgs(tokens) {
25201
25350
  }
25202
25351
  let baseUrl2;
25203
25352
  let json = false;
25353
+ if (action === "testflight") {
25354
+ const sub = rest.shift();
25355
+ if (sub !== "groups" && sub !== "status" && sub !== "distribute") throw new Error("Usage: service testflight groups|status|distribute NS:SERVICE");
25356
+ const ref = rest.shift();
25357
+ if (!ref || ref.startsWith("-")) throw new Error("A service ref is required");
25358
+ const parsed = parseNamespacedRef(ref, { entityLabel: "service ref" });
25359
+ const options = {};
25360
+ let submitReview = false;
25361
+ while (rest.length) {
25362
+ const flag = rest.shift();
25363
+ if (flag === "--json") json = true;
25364
+ else if (flag === "--submit-review" && sub === "distribute") submitReview = true;
25365
+ else if (["--version", "--build", "--base-url", ...sub === "distribute" ? ["--group", "--notes-file", "--locale"] : []].includes(flag)) {
25366
+ if (options[flag] !== void 0) throw new Error(`Duplicate option: ${flag}`);
25367
+ options[flag] = requireValue4(rest, flag);
25368
+ } else throw new Error(`Unknown testflight ${sub} option: ${flag}`);
25369
+ }
25370
+ if (sub !== "groups" && (!options["--version"] || !options["--build"])) throw new Error("--version and --build are required; latest is never inferred");
25371
+ if (options["--build"] && !/^[1-9][0-9]*$/.test(options["--build"])) throw new Error("--build must be a positive integer");
25372
+ if (sub === "distribute" && (!options["--group"] || !options["--notes-file"])) throw new Error("distribute requires --group and --notes-file");
25373
+ return {
25374
+ type: "service" /* Service */,
25375
+ action,
25376
+ testflightAction: sub,
25377
+ namespace: parsed.namespace,
25378
+ name: parsed.objectId,
25379
+ version: options["--version"],
25380
+ build: options["--build"],
25381
+ group: options["--group"],
25382
+ notesFile: options["--notes-file"],
25383
+ locale: options["--locale"],
25384
+ submitReview,
25385
+ baseUrl: options["--base-url"],
25386
+ json
25387
+ };
25388
+ }
25204
25389
  if (action === "list") {
25205
25390
  let namespace;
25206
25391
  let repository;
@@ -27405,7 +27590,7 @@ function requireValue10(tokens, option) {
27405
27590
 
27406
27591
  // src/index.ts
27407
27592
  var pkg = JSON.parse(
27408
- (0, import_node_fs32.readFileSync)(import_node_path37.default.resolve(__dirname, "..", "package.json"), "utf8")
27593
+ (0, import_node_fs33.readFileSync)(import_node_path38.default.resolve(__dirname, "..", "package.json"), "utf8")
27409
27594
  );
27410
27595
  var HELP_TEXT = [
27411
27596
  import_chalk4.default.bold(`pmate v${pkg.version}`),