@pmate/cli 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8818,8 +8818,8 @@ __export(index_exports, {
8818
8818
  parseCommandArgs: () => parseCommandArgs
8819
8819
  });
8820
8820
  module.exports = __toCommonJS(index_exports);
8821
- var import_node_fs29 = require("fs");
8822
- var import_node_path34 = __toESM(require("path"));
8821
+ var import_node_fs30 = require("fs");
8822
+ var import_node_path35 = __toESM(require("path"));
8823
8823
 
8824
8824
  // src/managedSession.ts
8825
8825
  var import_node_fs = require("fs");
@@ -14267,9 +14267,9 @@ ${indent}\`\`\``;
14267
14267
  static richTextToPlain(richText) {
14268
14268
  return richText.map((item) => item.plain_text ?? item.text?.content ?? "").join("").trim();
14269
14269
  }
14270
- static async requestJson(path34, init) {
14270
+ static async requestJson(path35, init) {
14271
14271
  const token = this.getToken();
14272
- const response = await fetch(`${this.baseUrl}${path34}`, {
14272
+ const response = await fetch(`${this.baseUrl}${path35}`, {
14273
14273
  method: init.method,
14274
14274
  headers: {
14275
14275
  Authorization: `Bearer ${token}`,
@@ -16974,8 +16974,8 @@ function descriptorPathSegments(descriptor) {
16974
16974
  return ["chains", normalized.chain, "namespaces", normalized.ns, normalized.kind, normalized.name];
16975
16975
  }
16976
16976
  function buildPathUrl(baseUrl, pathSegments, query) {
16977
- const path34 = `/${pathSegments.map((segment) => encodeURIComponent(segment)).join("/")}`;
16978
- const url = new URL(path34, baseUrl);
16977
+ const path35 = `/${pathSegments.map((segment) => encodeURIComponent(segment)).join("/")}`;
16978
+ const url = new URL(path35, baseUrl);
16979
16979
  if (query) {
16980
16980
  for (const [key, value] of Object.entries(query)) {
16981
16981
  url.searchParams.set(key, String(value));
@@ -17535,207 +17535,15 @@ var StoreCommandHandler = class {
17535
17535
  }
17536
17536
  };
17537
17537
 
17538
- // src/electronBuild.ts
17539
- var import_node_child_process9 = require("child_process");
17538
+ // src/commands/AppCommandHandler.ts
17540
17539
  var import_node_fs19 = require("fs");
17541
- var import_node_os9 = require("os");
17542
17540
  var import_node_path24 = __toESM(require("path"));
17543
-
17544
- // src/desktopRelease.ts
17545
- init_sessionStore();
17546
- var import_node_crypto4 = require("crypto");
17547
- var import_node_fs18 = require("fs");
17548
- var import_node_path23 = __toESM(require("path"));
17549
- async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
17550
- const segments = [...app.split(":"), version, platform, arch];
17551
- if (app.split(":").length !== 2 || segments.some((s) => !/^[\w.-]+$/.test(s) || s === "." || s === "..")) throw new Error("Invalid desktop release identity");
17552
- if (!["mac", "win"].includes(platform) || !["arm64", "x64"].includes(arch) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) throw new Error("Desktop publication requires a stable version and supported target");
17553
- const { token } = readRequiredSession({ preferredApp: DEFAULT_APP_ID });
17554
- const bucket = "parrot-static";
17555
- const prefix = `desktop/${segments.join("/")}/`;
17556
- const url = (key) => `https://parrot-static.pmate.chat/${key.split("/").map(encodeURIComponent).join("/")}`;
17557
- const artifacts = (0, import_node_fs18.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && (platform === "mac" ? /\.(dmg|zip)$/i : /\.(exe|zip)$/i).test(entry.name)).sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
17558
- const bytes = (0, import_node_fs18.readFileSync)(import_node_path23.default.join(directory, entry.name));
17559
- const objectKey = prefix + entry.name;
17560
- return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto4.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
17561
- });
17562
- if (!artifacts.length) throw new Error("No desktop installers found to publish");
17563
- const manifestKey = prefix + "release.json";
17564
- const existing = await AliyunService.readJsonObject(bucket, manifestKey);
17565
- const release = { schemaVersion: 1, app, version, platform, arch, artifacts };
17566
- if (existing !== null && JSON.stringify(existing) !== JSON.stringify(release)) throw new Error("Desktop release already exists with different artifacts; bump the app version");
17567
- for (const artifact of artifacts) await AliyunService.uploadFile(import_node_path23.default.join(directory, artifact.name), bucket, artifact.objectKey);
17568
- await AliyunService.uploadJsonObject(bucket, manifestKey, release);
17569
- const base = (process.env.PMATE_APPS_API_BASE_URL || "https://apps-api.pmate.chat").replace(/\/+$/, "");
17570
- const response = await fetch(`${base}/versions/${encodeURIComponent(app)}`, {
17571
- method: "POST",
17572
- headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
17573
- body: JSON.stringify({ version, platform, arch, manifestUrl: url(manifestKey) }),
17574
- signal: AbortSignal.timeout(3e4),
17575
- redirect: "error"
17576
- });
17577
- const result = await response.json();
17578
- if (!response.ok || result.success !== true) throw new Error(`Installers uploaded but version registration failed: ${result.message || response.status}. Retry this release before announcing it.`);
17579
- return { bucket, manifestUrl: url(manifestKey), downloads: artifacts };
17580
- }
17581
-
17582
- // src/electronBuild.ts
17583
- var ELECTRON_VERSION = "44.5.1";
17584
- var BUILDER_VERSION = "26.15.3";
17585
- function readDesktopConfig(file, appId) {
17586
- const c = JSON.parse((0, import_node_fs19.readFileSync)(file, "utf8"));
17587
- if (c.schemaVersion !== 2 || c.app !== appId) throw new Error("Desktop config schemaVersion/app mismatch");
17588
- for (const key of ["productName", "bundleId", "version", "icon"]) {
17589
- if (typeof c[key] !== "string" || !c[key].trim()) throw new Error(`Missing desktop ${key}`);
17590
- }
17591
- if (!/^[a-zA-Z][\w-]*(\.[a-zA-Z][\w-]*)+$/.test(c.bundleId)) throw new Error("Invalid desktop bundleId");
17592
- if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(c.version)) throw new Error("Invalid desktop version");
17593
- const origin = (value) => {
17594
- const url = new URL(value);
17595
- if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new Error("Desktop origins must be exact HTTPS origins, without paths or credentials");
17596
- };
17597
- origin(c.origin);
17598
- if (!Array.isArray(c.authOrigins)) throw new Error("authOrigins must be an array");
17599
- c.authOrigins.forEach(origin);
17600
- if (c.externalOrigins !== void 0 && !Array.isArray(c.externalOrigins)) throw new Error("externalOrigins must be an array");
17601
- c.externalOrigins?.forEach(origin);
17602
- if (c.notaryProfile !== void 0 && (typeof c.notaryProfile !== "string" || !c.notaryProfile.trim())) throw new Error("Invalid notaryProfile");
17603
- if ("web" in c) throw new Error("Remote desktop builds do not accept web build configuration; remove web");
17604
- return c;
17605
- }
17606
- function repositoryRoot(cwd) {
17607
- let dir = import_node_path24.default.resolve(cwd);
17608
- while (true) {
17609
- if ((0, import_node_fs19.existsSync)(import_node_path24.default.join(dir, ".git"))) return dir;
17610
- const parent = import_node_path24.default.dirname(dir);
17611
- if (parent === dir) return void 0;
17612
- dir = parent;
17613
- }
17614
- }
17615
- function resolveDesktopPaths(args, cwd = process.cwd()) {
17616
- const root = repositoryRoot(cwd);
17617
- const name = args.id.split(":")[1];
17618
- let file = args.config ? import_node_path24.default.resolve(cwd, args.config) : void 0;
17619
- if (!file) {
17620
- let dir = import_node_path24.default.resolve(cwd);
17621
- while (true) {
17622
- const candidates = [.../* @__PURE__ */ new Set([import_node_path24.default.join(dir, "desktop.config.json"), import_node_path24.default.join(dir, "apps", name, "desktop.config.json")])];
17623
- const matches = candidates.filter((candidate) => (0, import_node_fs19.existsSync)(candidate) && JSON.parse((0, import_node_fs19.readFileSync)(candidate, "utf8")).app === args.id);
17624
- if (matches.length > 1) throw new Error("Ambiguous desktop config; specify --config");
17625
- if (matches.length === 1) {
17626
- file = matches[0];
17627
- break;
17628
- }
17629
- const parent = import_node_path24.default.dirname(dir);
17630
- if (dir === root || parent === dir) break;
17631
- dir = parent;
17632
- }
17633
- }
17634
- if (!file) throw new Error(`No desktop config for ${args.id}; specify --config`);
17635
- return { file, output: args.outDir ? import_node_path24.default.resolve(cwd, args.outDir) : import_node_path24.default.join(root ?? import_node_path24.default.dirname(file), "release", name) };
17636
- }
17637
- function desktopBuildEnvironment(config, env = process.env) {
17638
- return { ...env, ...env.APPLE_KEYCHAIN_PROFILE ? {} : config.notaryProfile ? { APPLE_KEYCHAIN_PROFILE: config.notaryProfile } : {} };
17639
- }
17640
- function requireNotaryCredentials(env) {
17641
- if (env.APPLE_ID || env.APPLE_APP_SPECIFIC_PASSWORD) {
17642
- if (env.APPLE_ID && env.APPLE_APP_SPECIFIC_PASSWORD && env.APPLE_TEAM_ID) return;
17643
- } else if (env.APPLE_API_KEY || env.APPLE_API_KEY_ID || env.APPLE_API_ISSUER) {
17644
- if (env.APPLE_API_KEY && env.APPLE_API_KEY_ID && env.APPLE_API_ISSUER) return;
17645
- } else if (env.APPLE_KEYCHAIN_PROFILE) return;
17646
- throw new Error("macOS signed builds require complete Apple notarization credentials or APPLE_KEYCHAIN_PROFILE");
17647
- }
17648
- function requireSigningIdentity(env, inspect = () => (0, import_node_child_process9.execFileSync)("security", ["find-identity", "-v", "-p", "codesigning"], { encoding: "utf8" })) {
17649
- if (env.CSC_LINK) return;
17650
- if (!inspect().includes("Developer ID Application:")) throw new Error("No Developer ID Application signing identity available");
17651
- }
17652
- async function publishVerifiedDesktop(args, artifacts, config, verify = verifyMacRelease, upload = uploadDesktopArtifacts) {
17653
- if (args.signed && args.platform === "mac") await verify(artifacts);
17654
- if (args.dir || !args.signed) return void 0;
17655
- return upload(artifacts, config.app, config.version, args.platform, args.arch);
17656
- }
17657
- async function verifyMacRelease(artifacts, run = runBuildCommand, inspect = (app) => (0, import_node_child_process9.spawnSync)("codesign", ["-dv", "--verbose=4", app], { encoding: "utf8" })) {
17658
- const apps = (0, import_node_fs19.readdirSync)(artifacts, { recursive: true, withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.endsWith(".app")).map((entry) => import_node_path24.default.join(entry.parentPath, entry.name)).filter((file) => !file.slice(0, -4).includes(".app/"));
17659
- if (!apps.length) throw new Error("No packaged macOS app found; refusing publication");
17660
- for (const app of apps) {
17661
- await run(["codesign", "--verify", "--deep", "--strict", app], artifacts);
17662
- const signature = inspect(app);
17663
- if (signature.status !== 0 || !signature.stderr.includes("Authority=Developer ID Application:")) throw new Error("Packaged app lacks Developer ID Application signature");
17664
- await run(["xcrun", "stapler", "validate", app], artifacts);
17665
- await run(["spctl", "--assess", "--type", "execute", "--verbose=2", app], artifacts);
17666
- }
17667
- }
17668
- async function runBuildCommand(command, cwd, env = process.env) {
17669
- await new Promise((resolve, reject) => {
17670
- const child = (0, import_node_child_process9.spawn)(command[0], command.slice(1), { cwd, env, stdio: "inherit", shell: false });
17671
- child.once("error", reject);
17672
- child.once("exit", (code, signal) => code === 0 ? resolve() : reject(new Error(`${command[0]} failed (${signal ?? code})`)));
17673
- });
17674
- }
17675
- async function buildDesktop(args) {
17676
- const { file, output } = resolveDesktopPaths(args);
17677
- const c = readDesktopConfig(file, args.id);
17678
- const base = import_node_path24.default.dirname(file);
17679
- const icon = import_node_path24.default.resolve(base, c.icon);
17680
- const env = desktopBuildEnvironment(c);
17681
- if (!(0, import_node_fs19.existsSync)(icon) || !(0, import_node_fs19.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
17682
- if (!["mac", "win"].includes(args.platform) || !["arm64", "x64"].includes(args.arch)) throw new Error("Supported target: mac|win --arch arm64|x64");
17683
- if (args.platform === "mac" && process.platform !== "darwin") throw new Error("macOS desktop packaging requires a macOS build host");
17684
- 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, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
17685
- console.log(JSON.stringify({ phase: "plan", ...plan }, null, 2));
17686
- if (args.dryRun) return;
17687
- if (args.signed && args.platform === "mac") {
17688
- requireNotaryCredentials(env);
17689
- requireSigningIdentity(env);
17690
- }
17691
- (0, import_node_fs19.mkdirSync)(output, { recursive: true });
17692
- const staging = (0, import_node_fs19.mkdtempSync)(import_node_path24.default.join(output, ".desktop-build-"));
17693
- const appDir = import_node_path24.default.join(staging, "app");
17694
- (0, import_node_fs19.mkdirSync)(appDir);
17695
- const templateDir = import_node_path24.default.join(__dirname, "templates", "electron");
17696
- (0, import_node_fs19.cpSync)(templateDir, appDir, { recursive: true });
17697
- (0, import_node_fs19.writeFileSync)(import_node_path24.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 }));
17698
- (0, import_node_fs19.writeFileSync)(import_node_path24.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" } }));
17699
- await runBuildCommand(["npm", "install", "--omit=dev", "--no-audit", "--no-fund"], appDir);
17700
- const cache = import_node_path24.default.join((0, import_node_os9.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
17701
- (0, import_node_fs19.mkdirSync)(cache, { recursive: true });
17702
- const toolPackage = { name: "pmate-desktop-toolchain", private: true, dependencies: { electron: ELECTRON_VERSION, "electron-builder": BUILDER_VERSION } };
17703
- if (!(0, import_node_fs19.existsSync)(import_node_path24.default.join(cache, "node_modules", "electron", "dist", "Electron.app")) || !(0, import_node_fs19.existsSync)(import_node_path24.default.join(cache, "node_modules", "electron-builder", "cli.js"))) {
17704
- (0, import_node_fs19.writeFileSync)(import_node_path24.default.join(cache, "package.json"), JSON.stringify(toolPackage));
17705
- await runBuildCommand(["npm", (0, import_node_fs19.existsSync)(import_node_path24.default.join(cache, "package-lock.json")) ? "ci" : "install", "--no-audit", "--no-fund"], cache);
17706
- }
17707
- const builderConfig = {
17708
- appId: c.bundleId,
17709
- productName: c.productName,
17710
- electronVersion: ELECTRON_VERSION,
17711
- directories: { app: appDir, output: import_node_path24.default.join(staging, "artifacts") },
17712
- files: ["**/*"],
17713
- asar: true,
17714
- artifactName: "${productName}-${version}-${arch}.${ext}",
17715
- publish: [{ provider: "generic", url: `https://parrot-static.pmate.chat/desktop/${c.app.split(":").map(encodeURIComponent).join("/")}/${c.version}/${args.platform}/${args.arch}/` }],
17716
- mac: { icon, target: args.dir ? ["dir"] : ["dmg", "zip"], category: "public.app-category.social-networking", hardenedRuntime: args.signed, extendInfo: { NSMicrophoneUsageDescription: `${c.productName} uses your microphone for voice calls and voice messages.` }, ...args.signed ? {} : { identity: "-", notarize: false } },
17717
- win: { icon, target: args.dir ? ["dir"] : ["nsis", "zip"], ...args.signed ? {} : { signExecutable: false } },
17718
- forceCodeSigning: args.signed
17719
- };
17720
- const configPath = import_node_path24.default.join(staging, "builder.json");
17721
- (0, import_node_fs19.writeFileSync)(configPath, JSON.stringify(builderConfig));
17722
- await runBuildCommand([process.execPath, import_node_path24.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" } });
17723
- 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_path24.default.join(staging, "artifacts") };
17724
- (0, import_node_fs19.writeFileSync)(import_node_path24.default.join(staging, "build-report.json"), JSON.stringify(result, null, 2));
17725
- const publication = await publishVerifiedDesktop(args, result.artifacts, c);
17726
- (0, import_node_fs19.writeFileSync)(import_node_path24.default.join(staging, "build-report.json"), JSON.stringify({ ...result, publication }, null, 2));
17727
- console.log(JSON.stringify({ phase: "complete", report: import_node_path24.default.join(staging, "build-report.json"), artifacts: result.artifacts, signature: result.signature, publication }, null, 2));
17728
- }
17729
-
17730
- // src/commands/AppCommandHandler.ts
17731
- var import_node_fs21 = require("fs");
17732
- var import_node_path26 = __toESM(require("path"));
17733
17541
  init_sessionStore();
17734
17542
 
17735
17543
  // src/appIcon.ts
17736
- var import_node_fs20 = require("fs");
17737
- var import_node_os10 = __toESM(require("os"));
17738
- var import_node_path25 = __toESM(require("path"));
17544
+ var import_node_fs18 = require("fs");
17545
+ var import_node_os9 = __toESM(require("os"));
17546
+ var import_node_path23 = __toESM(require("path"));
17739
17547
  var import_sharp = __toESM(require("sharp"));
17740
17548
  init_namespacedRef();
17741
17549
  var ANDROID_ICON_SPECS = [
@@ -17840,13 +17648,13 @@ function createAppIconExportPlans(input) {
17840
17648
  if (!input.outDir) {
17841
17649
  throw new Error("App icon preset export requires --out-dir.");
17842
17650
  }
17843
- const outDir = import_node_path25.default.resolve(input.cwd, input.outDir);
17844
- (0, import_node_fs20.mkdirSync)(outDir, { recursive: true });
17651
+ const outDir = import_node_path23.default.resolve(input.cwd, input.outDir);
17652
+ (0, import_node_fs18.mkdirSync)(outDir, { recursive: true });
17845
17653
  return specs.map((spec) => ({
17846
17654
  width: spec.width,
17847
17655
  height: spec.height,
17848
17656
  format: "png",
17849
- outputPath: import_node_path25.default.join(
17657
+ outputPath: import_node_path23.default.join(
17850
17658
  outDir,
17851
17659
  `${namespace}-${objectId}-${spec.name}-${spec.width}x${spec.height}.png`
17852
17660
  )
@@ -17859,8 +17667,8 @@ function createAppIconExportPlans(input) {
17859
17667
  if (!input.output) {
17860
17668
  throw new Error("Single-size app icon export requires --output.");
17861
17669
  }
17862
- const resolvedOutput = import_node_path25.default.resolve(input.cwd, input.output);
17863
- (0, import_node_fs20.mkdirSync)(import_node_path25.default.dirname(resolvedOutput), { recursive: true });
17670
+ const resolvedOutput = import_node_path23.default.resolve(input.cwd, input.output);
17671
+ (0, import_node_fs18.mkdirSync)(import_node_path23.default.dirname(resolvedOutput), { recursive: true });
17864
17672
  return [
17865
17673
  {
17866
17674
  width: input.width,
@@ -17874,7 +17682,7 @@ async function exportAppIcon(icon, plans) {
17874
17682
  const svg = await resolveAppIconSvg(icon);
17875
17683
  for (const plan of plans) {
17876
17684
  const bytes = await renderAppIcon(svg, plan.width, plan.height, plan.format);
17877
- (0, import_node_fs20.writeFileSync)(plan.outputPath, bytes);
17685
+ (0, import_node_fs18.writeFileSync)(plan.outputPath, bytes);
17878
17686
  }
17879
17687
  }
17880
17688
  async function renderAppIconVariant(input) {
@@ -17882,9 +17690,9 @@ async function renderAppIconVariant(input) {
17882
17690
  const bytes = await renderAppIcon(svg, input.width, input.height, input.format);
17883
17691
  let outputPath;
17884
17692
  if (input.output) {
17885
- outputPath = import_node_path25.default.resolve(input.cwd, input.output);
17886
- (0, import_node_fs20.mkdirSync)(import_node_path25.default.dirname(outputPath), { recursive: true });
17887
- (0, import_node_fs20.writeFileSync)(outputPath, bytes);
17693
+ outputPath = import_node_path23.default.resolve(input.cwd, input.output);
17694
+ (0, import_node_fs18.mkdirSync)(import_node_path23.default.dirname(outputPath), { recursive: true });
17695
+ (0, import_node_fs18.writeFileSync)(outputPath, bytes);
17888
17696
  }
17889
17697
  if (input.name) {
17890
17698
  return {
@@ -17905,7 +17713,7 @@ async function renderAppIconVariant(input) {
17905
17713
  };
17906
17714
  }
17907
17715
  async function loadAppIconVariantFile(input) {
17908
- const absolutePath = import_node_path25.default.resolve(input.cwd, input.filePath);
17716
+ const absolutePath = import_node_path23.default.resolve(input.cwd, input.filePath);
17909
17717
  const format = inferVariantFormatFromPath(absolutePath);
17910
17718
  return {
17911
17719
  value: input.name ? await uploadAppIconVariantAsset({
@@ -17914,7 +17722,7 @@ async function loadAppIconVariantFile(input) {
17914
17722
  name: input.name,
17915
17723
  format,
17916
17724
  sourcePath: absolutePath
17917
- }) : createImageDataUrl((0, import_node_fs20.readFileSync)(absolutePath), format),
17725
+ }) : createImageDataUrl((0, import_node_fs18.readFileSync)(absolutePath), format),
17918
17726
  format,
17919
17727
  absolutePath
17920
17728
  };
@@ -17973,7 +17781,7 @@ function shouldAutoGenerateDefaultVariant(icon) {
17973
17781
  return looksLikeSvgMarkup(icon) || looksLikeSvgUrl(icon);
17974
17782
  }
17975
17783
  function inferVariantFormatFromPath(filePath) {
17976
- const ext = import_node_path25.default.extname(filePath).toLowerCase();
17784
+ const ext = import_node_path23.default.extname(filePath).toLowerCase();
17977
17785
  switch (ext) {
17978
17786
  case ".png":
17979
17787
  return "png";
@@ -18044,13 +17852,13 @@ async function uploadAppIconVariantAsset(input) {
18044
17852
  await AliyunService.uploadFile(sourcePath, DEFAULT_APP_ICON_VARIANT_BUCKET, objectKey);
18045
17853
  } finally {
18046
17854
  if (shouldCleanup) {
18047
- (0, import_node_fs20.rmSync)(import_node_path25.default.dirname(sourcePath), { recursive: true, force: true });
17855
+ (0, import_node_fs18.rmSync)(import_node_path23.default.dirname(sourcePath), { recursive: true, force: true });
18048
17856
  }
18049
17857
  }
18050
17858
  return `${DEFAULT_APP_ICON_VARIANT_PUBLIC_BASE_URL}/${objectKey}`;
18051
17859
  }
18052
17860
  function buildAppIconVariantObjectKey(input) {
18053
- return import_node_path25.default.posix.join(
17861
+ return import_node_path23.default.posix.join(
18054
17862
  "apps",
18055
17863
  `${resolveAppIconAssetStem(input.icon, input.appRef)}-${input.name}.${extensionForIconFormat(input.format)}`
18056
17864
  );
@@ -18059,8 +17867,8 @@ function resolveAppIconAssetStem(icon, appRef2) {
18059
17867
  if (icon) {
18060
17868
  try {
18061
17869
  const url = new URL(icon);
18062
- const ext = import_node_path25.default.posix.extname(url.pathname);
18063
- const basename = import_node_path25.default.posix.basename(url.pathname, ext);
17870
+ const ext = import_node_path23.default.posix.extname(url.pathname);
17871
+ const basename = import_node_path23.default.posix.basename(url.pathname, ext);
18064
17872
  const normalized = sanitizeAppIconAssetStem(basename);
18065
17873
  if (normalized) {
18066
17874
  return normalized;
@@ -18089,9 +17897,9 @@ function writeTempAppIconVariantFile(objectKey, format, bytes) {
18089
17897
  if (!bytes) {
18090
17898
  throw new Error("App icon variant upload requires bytes or a source file.");
18091
17899
  }
18092
- const tempDir = (0, import_node_fs20.mkdtempSync)(import_node_path25.default.join(import_node_os10.default.tmpdir(), "pmate-app-icon-"));
18093
- const tempPath = import_node_path25.default.join(tempDir, import_node_path25.default.basename(objectKey) || `variant.${extensionForIconFormat(format)}`);
18094
- (0, import_node_fs20.writeFileSync)(tempPath, bytes);
17900
+ const tempDir = (0, import_node_fs18.mkdtempSync)(import_node_path23.default.join(import_node_os9.default.tmpdir(), "pmate-app-icon-"));
17901
+ const tempPath = import_node_path23.default.join(tempDir, import_node_path23.default.basename(objectKey) || `variant.${extensionForIconFormat(format)}`);
17902
+ (0, import_node_fs18.writeFileSync)(tempPath, bytes);
18095
17903
  return tempPath;
18096
17904
  }
18097
17905
 
@@ -18099,7 +17907,6 @@ function writeTempAppIconVariantFile(objectKey, format, bytes) {
18099
17907
  init_namespacedRef();
18100
17908
  var AppCommandHandler = class {
18101
17909
  async handle(args) {
18102
- if (args.action === "build") return buildDesktop(args);
18103
17910
  const token = this.readToken();
18104
17911
  const baseUrl = this.resolveBaseUrl(args.baseUrl);
18105
17912
  switch (args.action) {
@@ -18301,10 +18108,10 @@ var AppCommandHandler = class {
18301
18108
  }
18302
18109
  readJsonFile(filePath) {
18303
18110
  const absolutePath = this.resolveFilePath(filePath);
18304
- if (!(0, import_node_fs21.existsSync)(absolutePath)) {
18111
+ if (!(0, import_node_fs19.existsSync)(absolutePath)) {
18305
18112
  throw new Error(`JSON file not found: ${absolutePath}`);
18306
18113
  }
18307
- const raw = (0, import_node_fs21.readFileSync)(absolutePath, "utf8");
18114
+ const raw = (0, import_node_fs19.readFileSync)(absolutePath, "utf8");
18308
18115
  try {
18309
18116
  return JSON.parse(raw);
18310
18117
  } catch (error) {
@@ -18314,10 +18121,10 @@ var AppCommandHandler = class {
18314
18121
  }
18315
18122
  async preparePayload(filePath, appRef2) {
18316
18123
  const absolutePath = this.resolveFilePath(filePath);
18317
- return prepareAppPayload(this.readJsonFile(filePath), import_node_path26.default.dirname(absolutePath), { appRef: appRef2 });
18124
+ return prepareAppPayload(this.readJsonFile(filePath), import_node_path24.default.dirname(absolutePath), { appRef: appRef2 });
18318
18125
  }
18319
18126
  resolveFilePath(filePath) {
18320
- return import_node_path26.default.resolve(process.cwd(), filePath);
18127
+ return import_node_path24.default.resolve(process.cwd(), filePath);
18321
18128
  }
18322
18129
  async request(baseUrl, token, method, pathname, body) {
18323
18130
  const response = await fetch(`${baseUrl}${pathname}`, {
@@ -18437,18 +18244,207 @@ function readNamespaceFromPayload(payload) {
18437
18244
  }
18438
18245
 
18439
18246
  // src/commands/ServiceCommandHandler.ts
18440
- var import_node_fs25 = require("fs");
18247
+ var import_node_fs26 = require("fs");
18441
18248
  var import_promises5 = require("fs/promises");
18442
- var import_node_path30 = __toESM(require("path"));
18249
+ var import_node_path31 = __toESM(require("path"));
18443
18250
  var import_node_child_process13 = require("child_process");
18444
18251
  var import_promises6 = require("readline/promises");
18445
18252
 
18446
- // src/services/IosBuildService.ts
18447
- var import_node_child_process11 = require("child_process");
18448
- var import_node_crypto6 = require("crypto");
18449
- var import_node_fs23 = require("fs");
18450
- var import_node_os12 = __toESM(require("os"));
18451
- var import_node_path28 = __toESM(require("path"));
18253
+ // src/services/NativeServiceDeploy.ts
18254
+ var import_node_path29 = __toESM(require("path"));
18255
+ var import_node_fs24 = require("fs");
18256
+
18257
+ // src/electronBuild.ts
18258
+ var import_node_child_process9 = require("child_process");
18259
+ var import_node_fs21 = require("fs");
18260
+ var import_node_os10 = require("os");
18261
+ var import_node_path26 = __toESM(require("path"));
18262
+
18263
+ // src/desktopRelease.ts
18264
+ init_sessionStore();
18265
+ var import_node_crypto4 = require("crypto");
18266
+ var import_node_fs20 = require("fs");
18267
+ var import_node_path25 = __toESM(require("path"));
18268
+ async function uploadDesktopArtifacts(directory, app, version, platform, arch) {
18269
+ const segments = [...app.split(":"), version, platform, arch];
18270
+ if (app.split(":").length !== 2 || segments.some((s) => !/^[\w.-]+$/.test(s) || s === "." || s === "..")) throw new Error("Invalid desktop release identity");
18271
+ if (!["mac", "win"].includes(platform) || !["arm64", "x64"].includes(arch) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) throw new Error("Desktop publication requires a stable version and supported target");
18272
+ const { token } = readRequiredSession({ preferredApp: DEFAULT_APP_ID });
18273
+ const bucket = "parrot-static";
18274
+ const prefix = `desktop/${segments.join("/")}/`;
18275
+ const url = (key) => `https://parrot-static.pmate.chat/${key.split("/").map(encodeURIComponent).join("/")}`;
18276
+ const artifacts = (0, import_node_fs20.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && (platform === "mac" ? /\.(dmg|zip)$/i : /\.(exe|zip)$/i).test(entry.name)).sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
18277
+ const bytes = (0, import_node_fs20.readFileSync)(import_node_path25.default.join(directory, entry.name));
18278
+ const objectKey = prefix + entry.name;
18279
+ return { name: entry.name, objectKey, downloadUrl: url(objectKey), sha256: (0, import_node_crypto4.createHash)("sha256").update(bytes).digest("hex"), size: bytes.length };
18280
+ });
18281
+ if (!artifacts.length) throw new Error("No desktop installers found to publish");
18282
+ const manifestKey = prefix + "release.json";
18283
+ const existing = await AliyunService.readJsonObject(bucket, manifestKey);
18284
+ const release = { schemaVersion: 1, app, version, platform, arch, artifacts };
18285
+ if (existing !== null && JSON.stringify(existing) !== JSON.stringify(release)) throw new Error("Desktop release already exists with different artifacts; bump the app version");
18286
+ for (const artifact of artifacts) await AliyunService.uploadFile(import_node_path25.default.join(directory, artifact.name), bucket, artifact.objectKey);
18287
+ await AliyunService.uploadJsonObject(bucket, manifestKey, release);
18288
+ const base = (process.env.PMATE_APPS_API_BASE_URL || "https://apps-api.pmate.chat").replace(/\/+$/, "");
18289
+ const response = await fetch(`${base}/versions/${encodeURIComponent(app)}`, {
18290
+ method: "POST",
18291
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
18292
+ body: JSON.stringify({ version, platform, arch, manifestUrl: url(manifestKey) }),
18293
+ signal: AbortSignal.timeout(3e4),
18294
+ redirect: "error"
18295
+ });
18296
+ const result = await response.json();
18297
+ if (!response.ok || result.success !== true) throw new Error(`Installers uploaded but version registration failed: ${result.message || response.status}. Retry this release before announcing it.`);
18298
+ return { bucket, manifestUrl: url(manifestKey), downloads: artifacts };
18299
+ }
18300
+
18301
+ // src/electronBuild.ts
18302
+ var ELECTRON_VERSION = "44.5.1";
18303
+ var BUILDER_VERSION = "26.15.3";
18304
+ function readDesktopConfig(file, appId) {
18305
+ const c = JSON.parse((0, import_node_fs21.readFileSync)(file, "utf8"));
18306
+ if (c.schemaVersion !== 2 || c.app !== appId) throw new Error("Desktop config schemaVersion/app mismatch");
18307
+ for (const key of ["productName", "bundleId", "version", "icon"]) {
18308
+ if (typeof c[key] !== "string" || !c[key].trim()) throw new Error(`Missing desktop ${key}`);
18309
+ }
18310
+ if (!/^[a-zA-Z][\w-]*(\.[a-zA-Z][\w-]*)+$/.test(c.bundleId)) throw new Error("Invalid desktop bundleId");
18311
+ if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(c.version)) throw new Error("Invalid desktop version");
18312
+ const origin = (value) => {
18313
+ const url = new URL(value);
18314
+ if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new Error("Desktop origins must be exact HTTPS origins, without paths or credentials");
18315
+ };
18316
+ origin(c.origin);
18317
+ if (!Array.isArray(c.authOrigins)) throw new Error("authOrigins must be an array");
18318
+ c.authOrigins.forEach(origin);
18319
+ if (c.externalOrigins !== void 0 && !Array.isArray(c.externalOrigins)) throw new Error("externalOrigins must be an array");
18320
+ c.externalOrigins?.forEach(origin);
18321
+ if (c.notaryProfile !== void 0 && (typeof c.notaryProfile !== "string" || !c.notaryProfile.trim())) throw new Error("Invalid notaryProfile");
18322
+ if ("web" in c) throw new Error("Remote desktop builds do not accept web build configuration; remove web");
18323
+ return c;
18324
+ }
18325
+ function repositoryRoot(cwd) {
18326
+ let dir = import_node_path26.default.resolve(cwd);
18327
+ while (true) {
18328
+ if ((0, import_node_fs21.existsSync)(import_node_path26.default.join(dir, ".git"))) return dir;
18329
+ const parent = import_node_path26.default.dirname(dir);
18330
+ if (parent === dir) return void 0;
18331
+ dir = parent;
18332
+ }
18333
+ }
18334
+ function resolveDesktopPaths(args, cwd = process.cwd()) {
18335
+ const root = repositoryRoot(cwd);
18336
+ const name = args.id.split(":")[1];
18337
+ let file = args.config ? import_node_path26.default.resolve(cwd, args.config) : void 0;
18338
+ if (!file) {
18339
+ let dir = import_node_path26.default.resolve(cwd);
18340
+ while (true) {
18341
+ const candidates = [.../* @__PURE__ */ new Set([import_node_path26.default.join(dir, "desktop.config.json"), import_node_path26.default.join(dir, "apps", name, "desktop.config.json")])];
18342
+ const matches = candidates.filter((candidate) => (0, import_node_fs21.existsSync)(candidate) && JSON.parse((0, import_node_fs21.readFileSync)(candidate, "utf8")).app === args.id);
18343
+ if (matches.length > 1) throw new Error("Ambiguous desktop config; specify --config");
18344
+ if (matches.length === 1) {
18345
+ file = matches[0];
18346
+ break;
18347
+ }
18348
+ const parent = import_node_path26.default.dirname(dir);
18349
+ if (dir === root || parent === dir) break;
18350
+ dir = parent;
18351
+ }
18352
+ }
18353
+ if (!file) throw new Error(`No desktop config for ${args.id}; specify --config`);
18354
+ return { file, output: args.outDir ? import_node_path26.default.resolve(cwd, args.outDir) : import_node_path26.default.join(root ?? import_node_path26.default.dirname(file), "release", name) };
18355
+ }
18356
+ function desktopBuildEnvironment(config, env = process.env) {
18357
+ return { ...env, ...env.APPLE_KEYCHAIN_PROFILE ? {} : config.notaryProfile ? { APPLE_KEYCHAIN_PROFILE: config.notaryProfile } : {} };
18358
+ }
18359
+ function requireNotaryCredentials(env) {
18360
+ if (env.APPLE_ID || env.APPLE_APP_SPECIFIC_PASSWORD) {
18361
+ if (env.APPLE_ID && env.APPLE_APP_SPECIFIC_PASSWORD && env.APPLE_TEAM_ID) return;
18362
+ } else if (env.APPLE_API_KEY || env.APPLE_API_KEY_ID || env.APPLE_API_ISSUER) {
18363
+ if (env.APPLE_API_KEY && env.APPLE_API_KEY_ID && env.APPLE_API_ISSUER) return;
18364
+ } else if (env.APPLE_KEYCHAIN_PROFILE) return;
18365
+ throw new Error("macOS signed builds require complete Apple notarization credentials or APPLE_KEYCHAIN_PROFILE");
18366
+ }
18367
+ function requireSigningIdentity(env, inspect = () => (0, import_node_child_process9.execFileSync)("security", ["find-identity", "-v", "-p", "codesigning"], { encoding: "utf8" })) {
18368
+ if (env.CSC_LINK) return;
18369
+ if (!inspect().includes("Developer ID Application:")) throw new Error("No Developer ID Application signing identity available");
18370
+ }
18371
+ async function publishVerifiedDesktop(args, artifacts, config, verify = verifyMacRelease, upload = uploadDesktopArtifacts) {
18372
+ if (args.signed && args.platform === "mac") await verify(artifacts);
18373
+ if (args.local || args.dir || !args.signed) return void 0;
18374
+ return upload(artifacts, config.app, config.version, args.platform, args.arch);
18375
+ }
18376
+ async function verifyMacRelease(artifacts, run = runBuildCommand, inspect = (app) => (0, import_node_child_process9.spawnSync)("codesign", ["-dv", "--verbose=4", app], { encoding: "utf8" })) {
18377
+ const apps = (0, import_node_fs21.readdirSync)(artifacts, { recursive: true, withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.endsWith(".app")).map((entry) => import_node_path26.default.join(entry.parentPath, entry.name)).filter((file) => !file.slice(0, -4).includes(".app/"));
18378
+ if (!apps.length) throw new Error("No packaged macOS app found; refusing publication");
18379
+ for (const app of apps) {
18380
+ await run(["codesign", "--verify", "--deep", "--strict", app], artifacts);
18381
+ const signature = inspect(app);
18382
+ if (signature.status !== 0 || !signature.stderr.includes("Authority=Developer ID Application:")) throw new Error("Packaged app lacks Developer ID Application signature");
18383
+ await run(["xcrun", "stapler", "validate", app], artifacts);
18384
+ await run(["spctl", "--assess", "--type", "execute", "--verbose=2", app], artifacts);
18385
+ }
18386
+ }
18387
+ async function runBuildCommand(command, cwd, env = process.env) {
18388
+ await new Promise((resolve, reject) => {
18389
+ const child = (0, import_node_child_process9.spawn)(command[0], command.slice(1), { cwd, env, stdio: "inherit", shell: false });
18390
+ child.once("error", reject);
18391
+ child.once("exit", (code, signal) => code === 0 ? resolve() : reject(new Error(`${command[0]} failed (${signal ?? code})`)));
18392
+ });
18393
+ }
18394
+ async function buildDesktop(args) {
18395
+ const { file, output } = resolveDesktopPaths(args);
18396
+ const c = readDesktopConfig(file, args.id);
18397
+ const base = import_node_path26.default.dirname(file);
18398
+ const icon = import_node_path26.default.resolve(base, c.icon);
18399
+ const env = desktopBuildEnvironment(c);
18400
+ if (!(0, import_node_fs21.existsSync)(icon) || !(0, import_node_fs21.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
18401
+ if (!["mac", "win"].includes(args.platform) || !["arm64", "x64"].includes(args.arch)) throw new Error("Supported target: mac|win --arch arm64|x64");
18402
+ if (args.platform === "mac" && process.platform !== "darwin") throw new Error("macOS desktop packaging requires a macOS build host");
18403
+ 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, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
18404
+ console.log(JSON.stringify({ phase: "plan", ...plan }, null, 2));
18405
+ if (args.dryRun) return;
18406
+ if (args.signed && args.platform === "mac") {
18407
+ requireNotaryCredentials(env);
18408
+ requireSigningIdentity(env);
18409
+ }
18410
+ (0, import_node_fs21.mkdirSync)(output, { recursive: true });
18411
+ const staging = (0, import_node_fs21.mkdtempSync)(import_node_path26.default.join(output, ".desktop-build-"));
18412
+ const appDir = import_node_path26.default.join(staging, "app");
18413
+ (0, import_node_fs21.mkdirSync)(appDir);
18414
+ const templateDir = import_node_path26.default.join(__dirname, "templates", "electron");
18415
+ (0, import_node_fs21.cpSync)(templateDir, appDir, { recursive: true });
18416
+ (0, import_node_fs21.writeFileSync)(import_node_path26.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 }));
18417
+ (0, import_node_fs21.writeFileSync)(import_node_path26.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" } }));
18418
+ await runBuildCommand(["npm", "install", "--omit=dev", "--no-audit", "--no-fund"], appDir);
18419
+ const cache = import_node_path26.default.join((0, import_node_os10.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
18420
+ (0, import_node_fs21.mkdirSync)(cache, { recursive: true });
18421
+ const toolPackage = { name: "pmate-desktop-toolchain", private: true, dependencies: { electron: ELECTRON_VERSION, "electron-builder": BUILDER_VERSION } };
18422
+ if (!(0, import_node_fs21.existsSync)(import_node_path26.default.join(cache, "node_modules", "electron", "dist", "Electron.app")) || !(0, import_node_fs21.existsSync)(import_node_path26.default.join(cache, "node_modules", "electron-builder", "cli.js"))) {
18423
+ (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(cache, "package.json"), JSON.stringify(toolPackage));
18424
+ await runBuildCommand(["npm", (0, import_node_fs21.existsSync)(import_node_path26.default.join(cache, "package-lock.json")) ? "ci" : "install", "--no-audit", "--no-fund"], cache);
18425
+ }
18426
+ const builderConfig = {
18427
+ appId: c.bundleId,
18428
+ productName: c.productName,
18429
+ electronVersion: ELECTRON_VERSION,
18430
+ directories: { app: appDir, output: import_node_path26.default.join(staging, "artifacts") },
18431
+ files: ["**/*"],
18432
+ asar: true,
18433
+ artifactName: "${productName}-${version}-${arch}.${ext}",
18434
+ publish: [{ provider: "generic", url: `https://parrot-static.pmate.chat/desktop/${c.app.split(":").map(encodeURIComponent).join("/")}/${c.version}/${args.platform}/${args.arch}/` }],
18435
+ mac: { icon, target: args.dir ? ["dir"] : ["dmg", "zip"], category: "public.app-category.social-networking", hardenedRuntime: args.signed, extendInfo: { NSMicrophoneUsageDescription: `${c.productName} uses your microphone for voice calls and voice messages.` }, ...args.signed ? {} : { identity: "-", notarize: false } },
18436
+ win: { icon, target: args.dir ? ["dir"] : ["nsis", "zip"], ...args.signed ? {} : { signExecutable: false } },
18437
+ forceCodeSigning: args.signed
18438
+ };
18439
+ const configPath = import_node_path26.default.join(staging, "builder.json");
18440
+ (0, import_node_fs21.writeFileSync)(configPath, JSON.stringify(builderConfig));
18441
+ await runBuildCommand([process.execPath, import_node_path26.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" } });
18442
+ 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_path26.default.join(staging, "artifacts") };
18443
+ (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(staging, "build-report.json"), JSON.stringify(result, null, 2));
18444
+ const publication = await publishVerifiedDesktop(args, result.artifacts, c);
18445
+ (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(staging, "build-report.json"), JSON.stringify({ ...result, publication }, null, 2));
18446
+ console.log(JSON.stringify({ phase: "complete", report: import_node_path26.default.join(staging, "build-report.json"), artifacts: result.artifacts, signature: result.signature, publication }, null, 2));
18447
+ }
18452
18448
 
18453
18449
  // src/services/AndroidApkReleaseService.ts
18454
18450
  var import_node_child_process10 = require("child_process");
@@ -18941,6 +18937,11 @@ function capitalize(value) {
18941
18937
  }
18942
18938
 
18943
18939
  // src/services/IosBuildService.ts
18940
+ var import_node_child_process11 = require("child_process");
18941
+ var import_node_crypto6 = require("crypto");
18942
+ var import_node_fs23 = require("fs");
18943
+ var import_node_os12 = __toESM(require("os"));
18944
+ var import_node_path28 = __toESM(require("path"));
18944
18945
  function iosBuildInteger(value) {
18945
18946
  if (!/^(0|[1-9]\d*)$/.test(String(value)) || !Number.isSafeInteger(Number(value))) {
18946
18947
  throw new Error(`iOS Build must be a non-negative safe integer: ${String(value)}`);
@@ -19091,6 +19092,64 @@ async function readPlist(input) {
19091
19092
  });
19092
19093
  }
19093
19094
 
19095
+ // src/services/NativeServiceDeploy.ts
19096
+ var electronKeys = ["config", "platform", "arch", "outDir", "unsigned", "signed", "dir"];
19097
+ var iosKeys = ["scheme", "team", "project", "workspace", "lastBuild"];
19098
+ function rejectNativeOverrides(args, allowed = []) {
19099
+ for (const key of [...electronKeys, ...iosKeys, "local", "dryRun"]) {
19100
+ if (args[key] !== void 0 && !allowed.includes(key)) throw new Error(`--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} is not supported for this service type`);
19101
+ }
19102
+ }
19103
+ var NativeServiceDeploy = class {
19104
+ constructor(deps = { desktop: buildDesktop, ios: new IosBuildService() }) {
19105
+ this.deps = deps;
19106
+ }
19107
+ async deploy(service, args) {
19108
+ if (!("type" in service) || !["electron", "ios"].includes(service.type)) throw new Error("Native deployment requires an electron or ios service");
19109
+ if ((args.env ?? "prod") !== "prod") throw new Error("Native deployment currently supports only --env prod");
19110
+ const repository = service.repository ?? service.mobile?.repository;
19111
+ const dir = service.dir ?? service.mobile?.dir;
19112
+ if (!dir || !repository && !args.cwd) throw new Error("Native service requires repository and dir");
19113
+ const root = args.cwd ? import_node_path29.default.resolve(args.cwd) : resolveRepositoryLocalRoot(repository);
19114
+ const appDir = import_node_path29.default.resolve(root, dir);
19115
+ if (!(0, import_node_fs24.existsSync)(appDir)) throw new Error(`Service source directory not found: ${appDir}`);
19116
+ const settings = service.build ?? {};
19117
+ if (service.type === "electron") {
19118
+ rejectNativeOverrides(args, [...electronKeys, "local", "dryRun"]);
19119
+ if (service.appIds?.length !== 1) throw new Error("Electron service requires exactly one appIds application identity");
19120
+ const app = service.appIds[0];
19121
+ const options2 = {
19122
+ id: app,
19123
+ target: "electron",
19124
+ config: args.config ? import_node_path29.default.resolve(args.config) : import_node_path29.default.resolve(appDir, settings.config ?? "desktop.config.json"),
19125
+ platform: args.platform ?? settings.platform ?? (process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform),
19126
+ arch: args.arch ?? settings.arch ?? process.arch,
19127
+ outDir: args.outDir ? import_node_path29.default.resolve(args.outDir) : import_node_path29.default.join(root, "release", service.name),
19128
+ signed: !args.unsigned,
19129
+ dir: !!args.dir,
19130
+ dryRun: !!args.dryRun,
19131
+ local: !!args.local,
19132
+ json: args.json
19133
+ };
19134
+ await this.deps.desktop(options2);
19135
+ return { serviceId: service.id, appId: app, status: args.dryRun ? "dry-run" : args.local ? "local" : "published", platform: options2.platform, arch: options2.arch, output: options2.outDir };
19136
+ }
19137
+ rejectNativeOverrides(args, [...iosKeys, "dryRun"]);
19138
+ const options = {
19139
+ cwd: root,
19140
+ scheme: args.scheme ?? settings.scheme ?? "",
19141
+ team: args.team ?? settings.team,
19142
+ project: args.project ?? (args.workspace ? void 0 : settings.project),
19143
+ workspace: args.workspace ?? (args.project ? void 0 : settings.workspace),
19144
+ lastBuild: args.lastBuild
19145
+ };
19146
+ if (!options.scheme.trim()) throw new Error("iOS service requires build.scheme; update the service configuration or pass --scheme");
19147
+ if (options.project && options.workspace) throw new Error("Use only one project or workspace");
19148
+ if (args.dryRun) return { serviceId: service.id, status: "dry-run", type: "ios", appDir, ...options };
19149
+ return { ...await this.deps.ios.build(service, options) };
19150
+ }
19151
+ };
19152
+
19094
19153
  // src/services/DeveloperLogsClient.ts
19095
19154
  init_sessionStore();
19096
19155
  init_namespacedRef();
@@ -19178,9 +19237,9 @@ async function requestDeveloperLogTool(tool, params, fetcher = fetch, delegate)
19178
19237
  }
19179
19238
 
19180
19239
  // src/services/ServiceRuntimeRunner.ts
19181
- var import_node_fs24 = require("fs");
19240
+ var import_node_fs25 = require("fs");
19182
19241
  var import_node_os13 = __toESM(require("os"));
19183
- var import_node_path29 = __toESM(require("path"));
19242
+ var import_node_path30 = __toESM(require("path"));
19184
19243
  var import_node_child_process12 = require("child_process");
19185
19244
  var import_node_readline = require("readline");
19186
19245
  var import_chalk3 = __toESM(require("chalk"));
@@ -19680,14 +19739,14 @@ var ServiceRuntimeRunner = class {
19680
19739
  }
19681
19740
  resolveRepoRoot(service, cwd) {
19682
19741
  if (cwd) {
19683
- return import_node_path29.default.resolve(process.cwd(), cwd);
19742
+ return import_node_path30.default.resolve(process.cwd(), cwd);
19684
19743
  }
19685
19744
  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();
19686
19745
  if (repository) {
19687
19746
  const repoName = repository.replace(/\/+$/, "").split("/").pop()?.replace(/\.git$/i, "");
19688
19747
  if (repoName) {
19689
- const candidate = import_node_path29.default.join(import_node_os13.default.homedir(), "dev", "pmate", repoName);
19690
- if ((0, import_node_fs24.existsSync)(candidate)) {
19748
+ const candidate = import_node_path30.default.join(import_node_os13.default.homedir(), "dev", "pmate", repoName);
19749
+ if ((0, import_node_fs25.existsSync)(candidate)) {
19691
19750
  return candidate;
19692
19751
  }
19693
19752
  }
@@ -19700,13 +19759,13 @@ var ServiceRuntimeRunner = class {
19700
19759
  if (!dir) {
19701
19760
  throw new Error(`Missing service dir for ${service.id}`);
19702
19761
  }
19703
- return import_node_path29.default.resolve(repoRoot, dir);
19762
+ return import_node_path30.default.resolve(repoRoot, dir);
19704
19763
  }
19705
19764
  async deployVite(service, options) {
19706
19765
  this.assertDeployableStaticSite(service);
19707
19766
  const appDir = this.resolveLocalDir(service, options.cwd);
19708
- const packageJsonPath = import_node_path29.default.join(appDir, "package.json");
19709
- if (!(0, import_node_fs24.existsSync)(packageJsonPath)) {
19767
+ const packageJsonPath = import_node_path30.default.join(appDir, "package.json");
19768
+ if (!(0, import_node_fs25.existsSync)(packageJsonPath)) {
19710
19769
  throw new Error(`No package.json found at ${packageJsonPath}`);
19711
19770
  }
19712
19771
  const pkg2 = this.loadPackageJson(packageJsonPath);
@@ -19721,8 +19780,8 @@ var ServiceRuntimeRunner = class {
19721
19780
  this.resolveRepoRoot(service, options.cwd),
19722
19781
  buildEnv
19723
19782
  );
19724
- const distDir = import_node_path29.default.join(appDir, "dist");
19725
- if (!(0, import_node_fs24.existsSync)(distDir)) {
19783
+ const distDir = import_node_path30.default.join(appDir, "dist");
19784
+ if (!(0, import_node_fs25.existsSync)(distDir)) {
19726
19785
  throw new Error(`No dist directory found at ${distDir}`);
19727
19786
  }
19728
19787
  const site = this.getSite(service);
@@ -19735,8 +19794,8 @@ var ServiceRuntimeRunner = class {
19735
19794
  async deployStatic(service, options) {
19736
19795
  this.assertDeployableStaticSite(service);
19737
19796
  const appDir = this.resolveLocalDir(service, options.cwd);
19738
- const srcDir = import_node_path29.default.join(appDir, "src");
19739
- if (!(0, import_node_fs24.existsSync)(srcDir)) {
19797
+ const srcDir = import_node_path30.default.join(appDir, "src");
19798
+ if (!(0, import_node_fs25.existsSync)(srcDir)) {
19740
19799
  throw new Error(`No src directory found at ${srcDir}`);
19741
19800
  }
19742
19801
  const site = this.getSite(service);
@@ -19770,8 +19829,8 @@ var ServiceRuntimeRunner = class {
19770
19829
  this.validateFcConfig(service, fc);
19771
19830
  const repoRoot = this.resolveRepoRoot(service, options.cwd);
19772
19831
  const appDir = this.resolveLocalDir(service, options.cwd);
19773
- const packageJsonPath = import_node_path29.default.join(appDir, "package.json");
19774
- if (!(0, import_node_fs24.existsSync)(packageJsonPath)) {
19832
+ const packageJsonPath = import_node_path30.default.join(appDir, "package.json");
19833
+ if (!(0, import_node_fs25.existsSync)(packageJsonPath)) {
19775
19834
  throw new Error(`No package.json found at ${packageJsonPath}`);
19776
19835
  }
19777
19836
  const pkg2 = this.loadPackageJson(packageJsonPath);
@@ -19824,15 +19883,15 @@ var ServiceRuntimeRunner = class {
19824
19883
  const repoRoot = this.resolveRepoRoot(service, options.cwd);
19825
19884
  const appDir = this.resolveLocalDir(service, options.cwd);
19826
19885
  await this.ensurePnpmWorkspaceRoot(repoRoot);
19827
- const configPath = import_node_path29.default.join(appDir, fc.configFile ?? "s.yaml");
19828
- if (!(0, import_node_fs24.existsSync)(configPath)) {
19886
+ const configPath = import_node_path30.default.join(appDir, fc.configFile ?? "s.yaml");
19887
+ if (!(0, import_node_fs25.existsSync)(configPath)) {
19829
19888
  throw new Error(`Missing FC config file at ${configPath}`);
19830
19889
  }
19831
- const packageJsonPath = import_node_path29.default.join(appDir, "package.json");
19832
- if (!(0, import_node_fs24.existsSync)(packageJsonPath)) {
19890
+ const packageJsonPath = import_node_path30.default.join(appDir, "package.json");
19891
+ if (!(0, import_node_fs25.existsSync)(packageJsonPath)) {
19833
19892
  throw new Error(`No package.json found at ${packageJsonPath}`);
19834
19893
  }
19835
- const rawConfig = (0, import_node_fs24.readFileSync)(configPath, "utf8");
19894
+ const rawConfig = (0, import_node_fs25.readFileSync)(configPath, "utf8");
19836
19895
  if (!rawConfig.includes(fc.functionName)) {
19837
19896
  throw new Error(`FC config ${configPath} does not mention functionName ${fc.functionName}`);
19838
19897
  }
@@ -20122,7 +20181,7 @@ var ServiceRuntimeRunner = class {
20122
20181
  const serverAddress = await resolveServerAddress(server);
20123
20182
  const templateName = exposeType === "websocket" ? "nginx.ws.template" : exposeType === "mixed" ? "nginx.mixed.template" : "nginx.rest.template";
20124
20183
  const templatePath = this.resolveTemplatePath(templateName);
20125
- const template = (0, import_node_fs24.readFileSync)(templatePath, "utf8");
20184
+ const template = (0, import_node_fs25.readFileSync)(templatePath, "utf8");
20126
20185
  const host = `${subdomain}.${("domain" in network ? network.domain?.trim() : void 0) || "pmate.chat"}`;
20127
20186
  const rendered = template.replace(/\$\{\{PORT\}\}/g, String(port)).replace(/\$\{\{HOSTS\}\}/g, host).replace(/\$\{\{HOST\}\}/g, host);
20128
20187
  const remotePath = `/etc/nginx/sites-enabled/${subdomain}.conf`;
@@ -20154,11 +20213,11 @@ var ServiceRuntimeRunner = class {
20154
20213
  }
20155
20214
  if (config.ensurePackageJson) {
20156
20215
  const appDir = this.resolveLocalDir(service, options.cwd);
20157
- const packageJsonPath = import_node_path29.default.join(appDir, "package.json");
20158
- if (!(0, import_node_fs24.existsSync)(packageJsonPath)) {
20216
+ const packageJsonPath = import_node_path30.default.join(appDir, "package.json");
20217
+ if (!(0, import_node_fs25.existsSync)(packageJsonPath)) {
20159
20218
  throw new Error(`Missing package.json at ${packageJsonPath}`);
20160
20219
  }
20161
- const pkgStat = (0, import_node_fs24.statSync)(packageJsonPath);
20220
+ const pkgStat = (0, import_node_fs25.statSync)(packageJsonPath);
20162
20221
  if (!pkgStat.isFile()) {
20163
20222
  throw new Error(`package.json is not a file at ${packageJsonPath}`);
20164
20223
  }
@@ -20569,9 +20628,9 @@ var ServiceRuntimeRunner = class {
20569
20628
  return tokens;
20570
20629
  }
20571
20630
  readPathValue(source, pathExpr) {
20572
- const path34 = pathExpr.split(".").map((segment) => segment.trim()).filter(Boolean);
20631
+ const path35 = pathExpr.split(".").map((segment) => segment.trim()).filter(Boolean);
20573
20632
  let cursor = source;
20574
- for (const segment of path34) {
20633
+ for (const segment of path35) {
20575
20634
  if (!cursor || typeof cursor !== "object" || Array.isArray(cursor)) {
20576
20635
  return void 0;
20577
20636
  }
@@ -20614,12 +20673,12 @@ var ServiceRuntimeRunner = class {
20614
20673
  }
20615
20674
  resolveTemplatePath(templateName) {
20616
20675
  const candidates = [
20617
- import_node_path29.default.join(__dirname, "..", "templates", templateName),
20618
- import_node_path29.default.join(__dirname, "..", "src", "templates", templateName),
20619
- import_node_path29.default.join(__dirname, "templates", templateName)
20676
+ import_node_path30.default.join(__dirname, "..", "templates", templateName),
20677
+ import_node_path30.default.join(__dirname, "..", "src", "templates", templateName),
20678
+ import_node_path30.default.join(__dirname, "templates", templateName)
20620
20679
  ];
20621
20680
  for (const candidate of candidates) {
20622
- if ((0, import_node_fs24.existsSync)(candidate)) {
20681
+ if ((0, import_node_fs25.existsSync)(candidate)) {
20623
20682
  return candidate;
20624
20683
  }
20625
20684
  }
@@ -20651,7 +20710,7 @@ var ServiceRuntimeRunner = class {
20651
20710
  });
20652
20711
  }
20653
20712
  loadPackageJson(packageJsonPath) {
20654
- const raw = (0, import_node_fs24.readFileSync)(packageJsonPath, "utf8");
20713
+ const raw = (0, import_node_fs25.readFileSync)(packageJsonPath, "utf8");
20655
20714
  const parsed = JSON.parse(raw);
20656
20715
  if (!parsed || typeof parsed !== "object") {
20657
20716
  throw new Error(`Invalid package.json at ${packageJsonPath}`);
@@ -20660,7 +20719,7 @@ var ServiceRuntimeRunner = class {
20660
20719
  }
20661
20720
  writePackageJson(packageJsonPath, data) {
20662
20721
  const serialized = JSON.stringify(data, null, 2);
20663
- (0, import_node_fs24.writeFileSync)(packageJsonPath, `${serialized}
20722
+ (0, import_node_fs25.writeFileSync)(packageJsonPath, `${serialized}
20664
20723
  `, "utf8");
20665
20724
  }
20666
20725
  validateFcConfig(service, fc) {
@@ -20687,8 +20746,8 @@ var ServiceRuntimeRunner = class {
20687
20746
  }
20688
20747
  }
20689
20748
  async ensurePnpmWorkspaceRoot(repoRoot) {
20690
- const workspacePath = import_node_path29.default.join(repoRoot, "pnpm-workspace.yaml");
20691
- if (!(0, import_node_fs24.existsSync)(workspacePath)) {
20749
+ const workspacePath = import_node_path30.default.join(repoRoot, "pnpm-workspace.yaml");
20750
+ if (!(0, import_node_fs25.existsSync)(workspacePath)) {
20692
20751
  throw new Error(`Missing pnpm-workspace.yaml at ${workspacePath}`);
20693
20752
  }
20694
20753
  }
@@ -20762,16 +20821,16 @@ var ServiceRuntimeRunner = class {
20762
20821
  if (!privateKeyPath) {
20763
20822
  throw new Error("Missing ssl.prv in ~/.pmate/config.yaml.");
20764
20823
  }
20765
- if (!(0, import_node_fs24.existsSync)(certificatePath)) {
20824
+ if (!(0, import_node_fs25.existsSync)(certificatePath)) {
20766
20825
  throw new Error(`SSL certificate file not found: ${certificatePath}`);
20767
20826
  }
20768
- if (!(0, import_node_fs24.existsSync)(privateKeyPath)) {
20827
+ if (!(0, import_node_fs25.existsSync)(privateKeyPath)) {
20769
20828
  throw new Error(`SSL private key file not found: ${privateKeyPath}`);
20770
20829
  }
20771
20830
  return {
20772
20831
  certName: host,
20773
- certificate: (0, import_node_fs24.readFileSync)(certificatePath, "utf8"),
20774
- privateKey: (0, import_node_fs24.readFileSync)(privateKeyPath, "utf8")
20832
+ certificate: (0, import_node_fs25.readFileSync)(certificatePath, "utf8"),
20833
+ privateKey: (0, import_node_fs25.readFileSync)(privateKeyPath, "utf8")
20775
20834
  };
20776
20835
  }
20777
20836
  resolveFcProtocol(fc, certConfig) {
@@ -21076,6 +21135,18 @@ var ServiceCommandHandler = class {
21076
21135
  }
21077
21136
  case "deploy": {
21078
21137
  const record = await registry.getService(args.namespace, args.name);
21138
+ if ("type" in record && (record.type === "electron" || record.type === "ios")) {
21139
+ try {
21140
+ const result = await new NativeServiceDeploy().deploy(record, args);
21141
+ if (!args.dryRun && !args.local) await this.appendDeployHistory(registry, record.id, args.env ?? "prod", "success", String(result.status));
21142
+ this.renderJson(result, true);
21143
+ } catch (error) {
21144
+ if (!args.dryRun && !args.local) await this.appendDeployHistory(registry, record.id, args.env ?? "prod", "failed", error instanceof Error ? error.message : String(error));
21145
+ throw error;
21146
+ }
21147
+ return;
21148
+ }
21149
+ rejectNativeOverrides(args);
21079
21150
  const service = await this.materializeServiceEnv(registry, record, args.env);
21080
21151
  try {
21081
21152
  await runtime.deploy(service, { envName: args.env, ...args.cwd ? { cwd: args.cwd } : {} });
@@ -21146,16 +21217,6 @@ var ServiceCommandHandler = class {
21146
21217
  );
21147
21218
  return;
21148
21219
  }
21149
- case "ios-build": {
21150
- const record = await registry.getService(args.namespace, args.name);
21151
- const result = await new IosBuildService().build(record, args);
21152
- if (args.json) this.renderJson(result, true);
21153
- else {
21154
- ui.success(`Uploaded iOS ${result.version} (${result.build}); Apple processing, TestFlight availability not yet verified`);
21155
- this.renderJson(result, true);
21156
- }
21157
- return;
21158
- }
21159
21220
  case "apk-release": {
21160
21221
  const record = await registry.getService(args.namespace, args.name);
21161
21222
  const apkRelease = new AndroidApkReleaseService(registry);
@@ -21258,7 +21319,7 @@ var ServiceCommandHandler = class {
21258
21319
  format: "dotenv"
21259
21320
  }
21260
21321
  );
21261
- const outputPath = import_node_path30.default.resolve(process.cwd(), args.output);
21322
+ const outputPath = import_node_path31.default.resolve(process.cwd(), args.output);
21262
21323
  await (0, import_promises5.writeFile)(outputPath, payload.content, "utf8");
21263
21324
  ui.success(`Wrote env file for ${args.appId} to ${outputPath}`);
21264
21325
  this.renderJson({ ...payload, output: outputPath }, args.json);
@@ -21484,11 +21545,11 @@ var ServiceCommandHandler = class {
21484
21545
  return (baseUrl || process.env.PMATE_APPS_API_BASE_URL || "https://apps-api.pmate.chat").replace(/\/+$/, "");
21485
21546
  }
21486
21547
  readJsonFile(filePath) {
21487
- const absolutePath = import_node_path30.default.resolve(process.cwd(), filePath);
21488
- if (!(0, import_node_fs25.existsSync)(absolutePath)) {
21548
+ const absolutePath = import_node_path31.default.resolve(process.cwd(), filePath);
21549
+ if (!(0, import_node_fs26.existsSync)(absolutePath)) {
21489
21550
  throw new Error(`JSON file not found: ${absolutePath}`);
21490
21551
  }
21491
- const raw = (0, import_node_fs25.readFileSync)(absolutePath, "utf8");
21552
+ const raw = (0, import_node_fs26.readFileSync)(absolutePath, "utf8");
21492
21553
  try {
21493
21554
  return JSON.parse(raw);
21494
21555
  } catch (error) {
@@ -22296,9 +22357,9 @@ var RoleCommandHandler = class {
22296
22357
  };
22297
22358
 
22298
22359
  // src/commands/AccountCommandHandler.ts
22299
- var import_node_fs26 = require("fs");
22360
+ var import_node_fs27 = require("fs");
22300
22361
  var import_node_crypto7 = require("crypto");
22301
- var import_node_path31 = __toESM(require("path"));
22362
+ var import_node_path32 = __toESM(require("path"));
22302
22363
  init_sessionStore();
22303
22364
  var AccountCommandHandler = class {
22304
22365
  async handle(args) {
@@ -22306,9 +22367,9 @@ var AccountCommandHandler = class {
22306
22367
  case "bot-keygen": {
22307
22368
  const keyFile = this.generateBotKeyFile(args.app, args.name);
22308
22369
  const outPath = args.out ? this.resolveFilePath(args.out) : this.resolveDefaultBotKeyPath(args.app, args.name);
22309
- (0, import_node_fs26.mkdirSync)(import_node_path31.default.dirname(outPath), { recursive: true });
22310
- (0, import_node_fs26.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
22311
- (0, import_node_fs26.chmodSync)(outPath, 384);
22370
+ (0, import_node_fs27.mkdirSync)(import_node_path32.default.dirname(outPath), { recursive: true });
22371
+ (0, import_node_fs27.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
22372
+ (0, import_node_fs27.chmodSync)(outPath, 384);
22312
22373
  if (!args.json) {
22313
22374
  ui.success(`Bot key saved to ${outPath}`);
22314
22375
  }
@@ -22868,10 +22929,10 @@ var AccountCommandHandler = class {
22868
22929
  throw new Error("Missing visible apps input");
22869
22930
  }
22870
22931
  const absolutePath = this.resolveFilePath(args.filePath);
22871
- if (!(0, import_node_fs26.existsSync)(absolutePath)) {
22932
+ if (!(0, import_node_fs27.existsSync)(absolutePath)) {
22872
22933
  throw new Error(`JSON file not found: ${absolutePath}`);
22873
22934
  }
22874
- const raw = (0, import_node_fs26.readFileSync)(absolutePath, "utf8");
22935
+ const raw = (0, import_node_fs27.readFileSync)(absolutePath, "utf8");
22875
22936
  let parsed;
22876
22937
  try {
22877
22938
  parsed = JSON.parse(raw);
@@ -22885,13 +22946,13 @@ var AccountCommandHandler = class {
22885
22946
  return parsed;
22886
22947
  }
22887
22948
  resolveFilePath(filePath) {
22888
- return import_node_path31.default.resolve(process.cwd(), filePath);
22949
+ return import_node_path32.default.resolve(process.cwd(), filePath);
22889
22950
  }
22890
22951
  resolveDefaultBotKeyPath(app, name) {
22891
- return import_node_path31.default.join(this.homeDir(), ".pmate", "bots", app, `${name}.bot-key.json`);
22952
+ return import_node_path32.default.join(this.homeDir(), ".pmate", "bots", app, `${name}.bot-key.json`);
22892
22953
  }
22893
22954
  resolveDefaultAccessKeyPath(app, name) {
22894
- return import_node_path31.default.join(this.homeDir(), ".pmate", "access-keys", app, `${name}.access-key.json`);
22955
+ return import_node_path32.default.join(this.homeDir(), ".pmate", "access-keys", app, `${name}.access-key.json`);
22895
22956
  }
22896
22957
  homeDir() {
22897
22958
  return process.env.HOME || process.env.USERPROFILE || process.cwd();
@@ -22911,14 +22972,14 @@ var AccountCommandHandler = class {
22911
22972
  }
22912
22973
  renameDefaultBotKeyFile(app, name, newName) {
22913
22974
  const oldPath = this.resolveDefaultBotKeyPath(app, name);
22914
- if (!(0, import_node_fs26.existsSync)(oldPath)) {
22975
+ if (!(0, import_node_fs27.existsSync)(oldPath)) {
22915
22976
  return void 0;
22916
22977
  }
22917
22978
  const keyFile = this.readBotKeyFile(oldPath, app, name);
22918
22979
  const newPath = this.resolveDefaultBotKeyPath(app, newName);
22919
- (0, import_node_fs26.mkdirSync)(import_node_path31.default.dirname(newPath), { recursive: true, mode: 448 });
22920
- (0, import_node_fs26.writeFileSync)(newPath, JSON.stringify({ ...keyFile, name: newName }, null, 2));
22921
- (0, import_node_fs26.chmodSync)(newPath, 384);
22980
+ (0, import_node_fs27.mkdirSync)(import_node_path32.default.dirname(newPath), { recursive: true, mode: 448 });
22981
+ (0, import_node_fs27.writeFileSync)(newPath, JSON.stringify({ ...keyFile, name: newName }, null, 2));
22982
+ (0, import_node_fs27.chmodSync)(newPath, 384);
22922
22983
  return newPath;
22923
22984
  }
22924
22985
  readBotKeyFile(filePath, expectedApp, expectedName) {
@@ -22926,10 +22987,10 @@ var AccountCommandHandler = class {
22926
22987
  throw new Error("Missing bot key file");
22927
22988
  }
22928
22989
  const absolutePath = this.resolveFilePath(filePath);
22929
- if (!(0, import_node_fs26.existsSync)(absolutePath)) {
22990
+ if (!(0, import_node_fs27.existsSync)(absolutePath)) {
22930
22991
  throw new Error(`Bot key file not found: ${absolutePath}`);
22931
22992
  }
22932
- const parsed = JSON.parse((0, import_node_fs26.readFileSync)(absolutePath, "utf8"));
22993
+ const parsed = JSON.parse((0, import_node_fs27.readFileSync)(absolutePath, "utf8"));
22933
22994
  if (parsed.type !== "pmate-bot-key" || parsed.version !== 1 || parsed.algorithm !== "ed25519" || !parsed.publicKey || !parsed.privateKey) {
22934
22995
  throw new Error(`Invalid PMate bot key file: ${absolutePath}`);
22935
22996
  }
@@ -22946,10 +23007,10 @@ var AccountCommandHandler = class {
22946
23007
  throw new Error("Missing access key file");
22947
23008
  }
22948
23009
  const absolutePath = this.resolveFilePath(filePath);
22949
- if (!(0, import_node_fs26.existsSync)(absolutePath)) {
23010
+ if (!(0, import_node_fs27.existsSync)(absolutePath)) {
22950
23011
  throw new Error(`Access key file not found: ${absolutePath}`);
22951
23012
  }
22952
- const parsed = JSON.parse((0, import_node_fs26.readFileSync)(absolutePath, "utf8"));
23013
+ const parsed = JSON.parse((0, import_node_fs27.readFileSync)(absolutePath, "utf8"));
22953
23014
  if (parsed.type !== "pmate-access-key" || parsed.version !== 1 || !parsed.id || !parsed.app || !parsed.secret || !parsed.expiresAt) {
22954
23015
  throw new Error(`Invalid PMate access key file: ${absolutePath}`);
22955
23016
  }
@@ -22971,9 +23032,9 @@ var AccountCommandHandler = class {
22971
23032
  createdAt: result.key.createdAt
22972
23033
  };
22973
23034
  const outPath = out ? this.resolveFilePath(out) : this.resolveDefaultAccessKeyPath(result.key.app, result.key.name);
22974
- (0, import_node_fs26.mkdirSync)(import_node_path31.default.dirname(outPath), { recursive: true });
22975
- (0, import_node_fs26.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
22976
- (0, import_node_fs26.chmodSync)(outPath, 384);
23035
+ (0, import_node_fs27.mkdirSync)(import_node_path32.default.dirname(outPath), { recursive: true });
23036
+ (0, import_node_fs27.writeFileSync)(outPath, JSON.stringify(keyFile, null, 2), { mode: 384 });
23037
+ (0, import_node_fs27.chmodSync)(outPath, 384);
22977
23038
  }
22978
23039
  renderAccessKeyCreateResult(result, asJson, out) {
22979
23040
  if (asJson) {
@@ -23058,8 +23119,8 @@ function encodePathSegment2(value) {
23058
23119
  }
23059
23120
 
23060
23121
  // src/commands/OrgCommandHandler.ts
23061
- var import_node_fs27 = require("fs");
23062
- var import_node_path32 = __toESM(require("path"));
23122
+ var import_node_fs28 = require("fs");
23123
+ var import_node_path33 = __toESM(require("path"));
23063
23124
  init_sessionStore();
23064
23125
  var OrgCommandHandler = class {
23065
23126
  async handle(args) {
@@ -23229,11 +23290,11 @@ var OrgCommandHandler = class {
23229
23290
  if (!filePath) {
23230
23291
  throw new Error(`Missing ${itemLabel} input`);
23231
23292
  }
23232
- const absolutePath = import_node_path32.default.resolve(process.cwd(), filePath);
23233
- if (!(0, import_node_fs27.existsSync)(absolutePath)) {
23293
+ const absolutePath = import_node_path33.default.resolve(process.cwd(), filePath);
23294
+ if (!(0, import_node_fs28.existsSync)(absolutePath)) {
23234
23295
  throw new Error(`JSON file not found: ${absolutePath}`);
23235
23296
  }
23236
- const raw = (0, import_node_fs27.readFileSync)(absolutePath, "utf8");
23297
+ const raw = (0, import_node_fs28.readFileSync)(absolutePath, "utf8");
23237
23298
  let parsed;
23238
23299
  try {
23239
23300
  parsed = JSON.parse(raw);
@@ -23304,9 +23365,9 @@ function encodePathSegment3(value) {
23304
23365
  }
23305
23366
 
23306
23367
  // src/commands/HostCommandHandler.ts
23307
- var import_node_fs28 = require("fs");
23368
+ var import_node_fs29 = require("fs");
23308
23369
  var import_node_os14 = require("os");
23309
- var import_node_path33 = __toESM(require("path"));
23370
+ var import_node_path34 = __toESM(require("path"));
23310
23371
  var import_node_child_process15 = require("child_process");
23311
23372
  var BLOCK_START = "# >>> pmate host env >>>";
23312
23373
  var BLOCK_END = "# <<< pmate host env <<<";
@@ -23813,27 +23874,7 @@ function parseAppArgs(tokens) {
23813
23874
  if (!action) {
23814
23875
  throw new Error("Missing app action. Use: app list|get|view|create|update|rename|move|icon|delete");
23815
23876
  }
23816
- if (action === "build") {
23817
- const id = parseNamespacedRef(rest.shift() ?? "", { entityLabel: "app ref" }).fullId;
23818
- const options = {};
23819
- const switches = /* @__PURE__ */ new Set();
23820
- while (rest.length) {
23821
- const key = rest.shift();
23822
- if (["--dry-run", "--signed", "--unsigned", "--dir", "--json"].includes(key)) {
23823
- if (switches.has(key)) throw new Error(`Duplicate option: ${key}`);
23824
- switches.add(key);
23825
- } else if (["--target", "--config", "--platform", "--arch", "--out-dir"].includes(key)) {
23826
- if (options[key]) throw new Error(`Duplicate option: ${key}`);
23827
- options[key] = requireValue3(rest, key);
23828
- } else throw new Error(`Unknown app build option: ${key}`);
23829
- }
23830
- if (options["--target"] && options["--target"] !== "electron") throw new Error("Supported target: electron");
23831
- if (switches.has("--signed") && switches.has("--unsigned")) throw new Error("--signed and --unsigned cannot be combined");
23832
- const platform = options["--platform"] ?? (process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform);
23833
- const arch = options["--arch"] ?? process.arch;
23834
- if (!["mac", "win"].includes(platform) || !["arm64", "x64"].includes(arch)) throw new Error("Supported target: --platform mac|win --arch arm64|x64");
23835
- return { type: "app" /* App */, action, id, target: "electron", config: options["--config"], platform, arch, outDir: options["--out-dir"], dryRun: switches.has("--dry-run"), signed: !switches.has("--unsigned"), dir: switches.has("--dir"), json: switches.has("--json") };
23836
- }
23877
+ if (action === "build") throw new Error("app build was removed; register an electron service and use pmate service deploy <ns:service>");
23837
23878
  let baseUrl;
23838
23879
  let json = false;
23839
23880
  const takeSharedOptions4 = () => {
@@ -24396,7 +24437,7 @@ function parseServiceArgs(tokens) {
24396
24437
  json
24397
24438
  };
24398
24439
  }
24399
- if (action === "ios") return parseServiceIosArgs(rest);
24440
+ if (action === "ios") throw new Error("service ios build was removed; use pmate service deploy <ns:ios-service>");
24400
24441
  if (action === "apk") {
24401
24442
  return parseServiceApkArgs(rest, { baseUrl, json });
24402
24443
  }
@@ -24405,6 +24446,9 @@ function parseServiceArgs(tokens) {
24405
24446
  if (!ref || ref.startsWith("-")) {
24406
24447
  throw new Error(`Usage: service ${action} <ns:objectId> [--base-url <url>] [--json]`);
24407
24448
  }
24449
+ const native = {};
24450
+ const buildValues = ["--config", "--platform", "--arch", "--out-dir", "--scheme", "--team", "--project", "--workspace", "--last-build"];
24451
+ const buildFlags = ["--dry-run", "--local", "--unsigned", "--signed", "--dir"];
24408
24452
  let cwd;
24409
24453
  let page = 0;
24410
24454
  let app;
@@ -24416,6 +24460,13 @@ function parseServiceArgs(tokens) {
24416
24460
  let env;
24417
24461
  while (rest.length > 0) {
24418
24462
  const token = rest.shift();
24463
+ if (buildValues.includes(token) || buildFlags.includes(token)) {
24464
+ if (action !== "deploy") throw new Error(`Unknown service ${action} option: ${token}`);
24465
+ const key = token.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
24466
+ if (native[key] !== void 0) throw new Error(`Duplicate option: ${token}`);
24467
+ native[key] = buildFlags.includes(token) ? true : requireValue4(rest, token);
24468
+ continue;
24469
+ }
24419
24470
  switch (token) {
24420
24471
  case "--category": {
24421
24472
  if (action !== "log") throw new Error(`Unknown service ${action} option: ${token}`);
@@ -24502,8 +24553,17 @@ function parseServiceArgs(tokens) {
24502
24553
  return { type: "service" /* Service */, action, namespace, name, env, page, baseUrl, json };
24503
24554
  }
24504
24555
  if (action === "deploy" || action === "stop") {
24556
+ if (native.signed && native.unsigned) throw new Error("--signed and --unsigned cannot be combined");
24557
+ if ((native.unsigned || native.dir) && !native.local) throw new Error("Use --local with --unsigned or --dir; deploy otherwise publishes a release");
24558
+ if (native.platform && !["mac", "win"].includes(String(native.platform))) throw new Error("Supported platform: mac|win");
24559
+ if (native.arch && !["arm64", "x64"].includes(String(native.arch))) throw new Error("Supported architecture: arm64|x64");
24560
+ if (native.project && native.workspace) throw new Error("Use only one of --project or --workspace");
24561
+ if (native.lastBuild !== void 0) {
24562
+ if (!/^(0|[1-9]\d*)$/.test(String(native.lastBuild)) || !Number.isSafeInteger(Number(native.lastBuild))) throw new Error("--last-build must be a non-negative safe integer");
24563
+ native.lastBuild = Number(native.lastBuild);
24564
+ }
24505
24565
  if (action === "deploy") env ??= "prod";
24506
- return { type: "service" /* Service */, action, namespace, name, env, ...cwd ? { cwd } : {}, baseUrl, json };
24566
+ return { type: "service" /* Service */, action, namespace, name, env, ...cwd ? { cwd } : {}, ...native, baseUrl, json };
24507
24567
  }
24508
24568
  if (action === "init") {
24509
24569
  if (!env) {
@@ -25166,48 +25226,6 @@ function parseServiceEnvArgs(appId, tokens) {
25166
25226
  }
25167
25227
  throw new Error(`Unknown service env action: ${action}`);
25168
25228
  }
25169
- function parseServiceIosArgs(tokens) {
25170
- const rest = [...tokens];
25171
- if (rest.shift() !== "build") throw new Error("Usage: service ios build <ns:service> --scheme <scheme>");
25172
- const ref = rest.shift();
25173
- if (!ref || ref.startsWith("-")) throw new Error("Missing iOS service ref");
25174
- const parsed = parseNamespacedRef(ref, { entityLabel: "service ref" });
25175
- const values = {};
25176
- let json = false;
25177
- const allowed = ["--scheme", "--project", "--workspace", "--team", "--cwd", "--last-build", "--base-url"];
25178
- while (rest.length) {
25179
- const token = rest.shift();
25180
- if (token === "--json") {
25181
- json = true;
25182
- continue;
25183
- }
25184
- if (!allowed.includes(token)) throw new Error(`Unknown service ios build option: ${token}`);
25185
- if (values[token] !== void 0) throw new Error(`Duplicate option: ${token}`);
25186
- values[token] = requireValue4(rest, token);
25187
- }
25188
- if (!values["--scheme"]) throw new Error("An explicit --scheme is required");
25189
- if (values["--project"] && values["--workspace"]) throw new Error("Use only one of --project or --workspace");
25190
- let lastBuild;
25191
- if (values["--last-build"] !== void 0) {
25192
- const value = values["--last-build"];
25193
- if (!/^(0|[1-9]\d*)$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error("--last-build must be a non-negative safe integer");
25194
- lastBuild = Number(value);
25195
- }
25196
- return {
25197
- type: "service" /* Service */,
25198
- action: "ios-build",
25199
- namespace: parsed.namespace,
25200
- name: parsed.objectId,
25201
- scheme: values["--scheme"],
25202
- project: values["--project"],
25203
- workspace: values["--workspace"],
25204
- team: values["--team"],
25205
- cwd: values["--cwd"],
25206
- lastBuild,
25207
- baseUrl: values["--base-url"],
25208
- json
25209
- };
25210
- }
25211
25229
 
25212
25230
  // src/logsCommandParser.ts
25213
25231
  init_namespacedRef();
@@ -26676,7 +26694,7 @@ function requireValue11(tokens, option) {
26676
26694
 
26677
26695
  // src/index.ts
26678
26696
  var pkg = JSON.parse(
26679
- (0, import_node_fs29.readFileSync)(import_node_path34.default.resolve(__dirname, "..", "package.json"), "utf8")
26697
+ (0, import_node_fs30.readFileSync)(import_node_path35.default.resolve(__dirname, "..", "package.json"), "utf8")
26680
26698
  );
26681
26699
  var HELP_TEXT = [
26682
26700
  import_chalk4.default.bold(`pmate v${pkg.version}`),
@@ -26825,7 +26843,6 @@ var HELP_TEXT = [
26825
26843
  ` ${import_chalk4.default.gray(" kv list|get|exists|set|delete <name> [options]")}`,
26826
26844
  ` ${import_chalk4.default.gray(" defaults: chain=pmate namespace=pmate env base URLs from BLOCKCHAIN_BASE_URL / INDEXER_BASE_URL")}`,
26827
26845
  ` ${import_chalk4.default.cyan("app")} Manage app registry entries via apps-api`,
26828
- ` ${import_chalk4.default.gray(" build <ns:app> [--target electron] [--config <file>] [--platform mac|win] [--arch arm64|x64] [--out-dir <dir>] [--dir] [--dry-run] [--unsigned|--signed]")}`,
26829
26846
  ` ${import_chalk4.default.gray(" list [--ns <namespace>] [--all] [--base-url <url>] [--json]")}`,
26830
26847
  ` ${import_chalk4.default.gray(" get <ns:objectId> [--base-url <url>] [--json]")}`,
26831
26848
  ` ${import_chalk4.default.gray(" view <ns:objectId> [--base-url <url>]")}`,
@@ -26841,7 +26858,7 @@ var HELP_TEXT = [
26841
26858
  ` ${import_chalk4.default.gray(" delete <ns:objectId> [--base-url <url>] [--json]")}`,
26842
26859
  ` ${import_chalk4.default.gray(" default base URL: https://apps-api.pmate.chat")}`,
26843
26860
  ` ${import_chalk4.default.cyan("service")} Manage service registry entries via apps-api`,
26844
- " ios build <ns:service> --scheme <name> [--team <id>] [--last-build <n>] [--cwd <repo>] [--project <path>|--workspace <path>] [--json]",
26861
+ " deploy <ns:service> [--env prod] [--cwd <repo>] [--dry-run] [--local] [--unsigned] [--platform mac|win] [--arch arm64|x64] [--config <file>] [--out-dir <dir>] [--scheme <name>] [--team <id>]",
26845
26862
  ` ${import_chalk4.default.gray(" list [--namespace <ns>] [--repo <owner/name|https://github.com/owner/name>] [--server <name>] [--base-url <url>] [--json]")}`,
26846
26863
  ` ${import_chalk4.default.gray(" get <ns:objectId> [--base-url <url>] [--json]")}`,
26847
26864
  ` ${import_chalk4.default.gray(" view <ns:objectId> [--base-url <url>]")}`,