@protobase/cli 0.40.1 → 0.40.3

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.40.1";
2
+ var version = "0.40.3";
3
3
  //#endregion
4
4
  export { version };
@@ -0,0 +1,53 @@
1
+ import { statSync } from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/mobile/android-signing.ts
4
+ /** The variables an Android release is signed from. */
5
+ const androidSigningVariables = [
6
+ "PROTOBASE_ANDROID_KEYSTORE",
7
+ "PROTOBASE_ANDROID_KEYSTORE_PASSWORD",
8
+ "PROTOBASE_ANDROID_KEY_ALIAS",
9
+ "PROTOBASE_ANDROID_KEY_PASSWORD"
10
+ ];
11
+ const signingNames = new Set(androidSigningVariables);
12
+ const isSigningVariable = (key) => signingNames.has(key.toUpperCase());
13
+ /** `env` without the signing variables, in any letter case. */
14
+ const withoutAndroidSigning = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => !isSigningVariable(key)));
15
+ const isFile = (file) => {
16
+ try {
17
+ return statSync(file).isFile();
18
+ } catch (error) {
19
+ if (error.code === "ENOENT") return false;
20
+ throw error;
21
+ }
22
+ };
23
+ /**
24
+ * The signing variables Gradle gets, read from `env` and checked before anything is installed: all four set, and the
25
+ * keystore a file, made absolute against the project folder since Gradle would read a relative one from `android/app`.
26
+ */
27
+ const androidSigning = (env, projectDir) => {
28
+ const missing = androidSigningVariables.filter((key) => !env[key]);
29
+ if (missing.length > 0) throw new Error(`An Android release is signed with your upload key: set ${missing.join(", ")}`);
30
+ const keystore = path.resolve(projectDir, env.PROTOBASE_ANDROID_KEYSTORE);
31
+ if (!isFile(keystore)) throw new Error(`PROTOBASE_ANDROID_KEYSTORE names ${keystore}, which is not a file`);
32
+ return { env: {
33
+ ...Object.fromEntries(androidSigningVariables.map((key) => [key, env[key]])),
34
+ PROTOBASE_ANDROID_KEYSTORE: keystore
35
+ } };
36
+ };
37
+ const releaseAnchor = " buildTypes {\n release {\n";
38
+ const signingConfig = ` signingConfigs {
39
+ release {
40
+ storeFile file(System.getenv('PROTOBASE_ANDROID_KEYSTORE'))
41
+ storePassword System.getenv('PROTOBASE_ANDROID_KEYSTORE_PASSWORD')
42
+ keyAlias System.getenv('PROTOBASE_ANDROID_KEY_ALIAS')
43
+ keyPassword System.getenv('PROTOBASE_ANDROID_KEY_PASSWORD')
44
+ }
45
+ }
46
+ `;
47
+ /** The app's build.gradle signing its release build from the signing variables, naming them only, never a value. */
48
+ const withReleaseSigning = (gradle) => {
49
+ if (gradle.split(releaseAnchor).length !== 2 || gradle.includes("signingConfigs")) throw new Error("app/build.gradle does not have the one release build type of Capacitor's template");
50
+ return gradle.replace(releaseAnchor, `${signingConfig}${releaseAnchor} signingConfig signingConfigs.release\n`);
51
+ };
52
+ //#endregion
53
+ export { androidSigning, androidSigningVariables, withReleaseSigning, withoutAndroidSigning };
@@ -30,5 +30,14 @@ const forwardedPort = (url, platform) => {
30
30
  if (platform !== "android" || !loopback.includes(url.hostname)) return void 0;
31
31
  return Number(url.port || (url.protocol === "https:" ? 443 : 80));
32
32
  };
33
+ const isLocalHost = (hostname) => hostname === "localhost" || hostname.endsWith(".localhost") || hostname.startsWith("127.") || hostname === "[::1]" || hostname === "0.0.0.0" || hostname === "10.0.2.2";
34
+ /**
35
+ * Throws unless a release may call `url`: https to a server that is not this machine, so the app allows no plain http
36
+ * and no mixed content, which anyone between could read or change.
37
+ */
38
+ const checkReleaseUrl = (url) => {
39
+ const { cleartext, mixedContent } = httpAllowances(url);
40
+ if (cleartext || mixedContent || url.protocol !== "https:" || isLocalHost(url.hostname)) throw new Error(`A release build calls its server over https, since anyone between could read or change plain http, and not ${url.origin} on this machine: pass --api https://… or give auth an https baseURL`);
41
+ };
33
42
  //#endregion
34
- export { apiUrl, forwardedPort, httpAllowances };
43
+ export { apiUrl, checkReleaseUrl, forwardedPort, httpAllowances };
@@ -0,0 +1,12 @@
1
+ //#region src/mobile/app-version.ts
2
+ const replaceExactly = (text, file, anchor, count, replacement) => {
3
+ const parts = text.split(anchor);
4
+ if (parts.length - 1 !== count) throw new Error(`${file} has \`${anchor.trim()}\` ${parts.length - 1} times, not ${count} as in Capacitor's template`);
5
+ return parts.join(replacement);
6
+ };
7
+ /** The app's build.gradle with the version as versionName and the build number as versionCode. */
8
+ const withAndroidVersion = (gradle, { version, build }) => replaceExactly(replaceExactly(gradle, "app/build.gradle", " versionCode 1\n", 1, ` versionCode ${build}\n`), "app/build.gradle", " versionName \"1.0\"\n", 1, ` versionName "${version}"\n`);
9
+ /** The project.pbxproj with the version and build number in the app target's Debug and Release configurations. */
10
+ const withIosVersion = (pbxproj, { version, build }) => replaceExactly(replaceExactly(pbxproj, "project.pbxproj", "CURRENT_PROJECT_VERSION = 1;", 2, `CURRENT_PROJECT_VERSION = ${build};`), "project.pbxproj", "MARKETING_VERSION = 1.0;", 2, `MARKETING_VERSION = ${version};`);
11
+ //#endregion
12
+ export { withAndroidVersion, withIosVersion };
@@ -12,5 +12,29 @@ const parsePort = (value) => {
12
12
  if (number < 1 || number > 65535) throw new InvalidArgumentError("expected a port from 1 to 65535");
13
13
  return number;
14
14
  };
15
+ /** `--app-version`: one to three dot-separated numbers, the version both stores show, such as 1.2.3. */
16
+ const parseAppVersion = (value) => {
17
+ if (/^\d{1,9}(?:\.\d{1,9}){0,2}$/.test(value)) return value;
18
+ throw new InvalidArgumentError("expected one to three numbers separated by dots, such as 1.2.3");
19
+ };
20
+ const maxBuildNumber = 21e8;
21
+ /** `--build-number`: a whole number from 1 to 2100000000, which rises with each upload. */
22
+ const parseBuildNumber = (value) => {
23
+ if (/^[1-9]\d{0,9}$/.test(value) && Number(value) <= maxBuildNumber) return value;
24
+ throw new InvalidArgumentError(`expected a whole number from 1 to ${maxBuildNumber}`);
25
+ };
26
+ /** `--team`: an Apple Developer team id, ten capital letters and digits. */
27
+ const parseTeamId = (value) => {
28
+ if (/^[A-Z0-9]{10}$/.test(value)) return value;
29
+ throw new InvalidArgumentError("expected an Apple Developer team id, ten capital letters and digits such as ABCDE12345");
30
+ };
31
+ /**
32
+ * `--certificate` and `--profile`: a signing certificate or provisioning profile name. Capacitor writes it into its
33
+ * export plist unescaped, so no XML markup or control character, and no leading dash xcodebuild could take for a flag.
34
+ */
35
+ const parseSigningName = (value) => {
36
+ if (/^[^-<>&\p{Cc}][^<>&\p{Cc}]*$/u.test(value)) return value;
37
+ throw new InvalidArgumentError("expected a certificate or profile name without <, >, &, control characters or a leading -");
38
+ };
15
39
  //#endregion
16
- export { parsePlatform, parsePort };
40
+ export { parseAppVersion, parseBuildNumber, parsePlatform, parsePort, parseSigningName, parseTeamId };
@@ -0,0 +1,53 @@
1
+ import { androidSigning } from "./android-signing.js";
2
+ import { runChild } from "./child-process.js";
3
+ import { copyRelease, releaseFile } from "./release-output.js";
4
+ import { prepareReleaseProject } from "./release-project.js";
5
+ import { prepare, summary } from "./run.js";
6
+ import path from "node:path";
7
+ //#region src/mobile/build.ts
8
+ const gradleArgs = [
9
+ ":app:bundleRelease",
10
+ "--no-daemon",
11
+ "--no-configuration-cache",
12
+ "-Pkotlin.compiler.execution.strategy=in-process"
13
+ ];
14
+ const capBuildIos = ({ team, manual }) => [
15
+ "build",
16
+ "ios",
17
+ "--xcode-team-id",
18
+ team,
19
+ ...manual ? [
20
+ "--xcode-signing-style",
21
+ "manual",
22
+ "--xcode-signing-certificate",
23
+ manual.certificate,
24
+ "--xcode-provisioning-profile",
25
+ manual.profile
26
+ ] : []
27
+ ];
28
+ /** `protobase mobile build`: generates the native project as a release, builds it signed and copies the binary out. */
29
+ const mobileBuild = async (input, out, deps = {}) => {
30
+ const { version, outDir, ios, ...mobile } = input;
31
+ if (mobile.platform === "ios" && !ios) throw new Error("An iOS release is signed by your Apple Developer team: pass --team");
32
+ const signing = mobile.platform === "android" ? androidSigning(process.env, mobile.projectDir) : void 0;
33
+ const prepared = await prepare({
34
+ ...mobile,
35
+ release: true
36
+ }, deps);
37
+ out(summary(mobile.projectDir, prepared));
38
+ await prepareReleaseProject(prepared.ws, mobile.platform, version);
39
+ if (signing) {
40
+ const android = path.join(prepared.ws, "android");
41
+ await (deps.run ?? runChild)(path.join(android, "gradlew"), gradleArgs, {
42
+ cwd: android,
43
+ env: {
44
+ ...prepared.env,
45
+ ...signing.env
46
+ }
47
+ });
48
+ } else await prepared.cap(capBuildIos(ios));
49
+ const file = await copyRelease(releaseFile(prepared.ws, mobile.platform), outDir, `${prepared.appId}-${version.version}-${version.build}`);
50
+ out(`release ${path.relative(mobile.projectDir, file)}\n`);
51
+ };
52
+ //#endregion
53
+ export { mobileBuild };
@@ -1,5 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
2
  //#region src/mobile/child-process.ts
3
+ const forwarded = [
4
+ "SIGINT",
5
+ "SIGTERM",
6
+ "SIGHUP"
7
+ ];
3
8
  /**
4
9
  * Runs `command` with `args` as given, never through a shell, in `cwd` with exactly `env`: without it the child would
5
10
  * get the CLI's whole environment, with the project's secrets.
@@ -10,8 +15,20 @@ const runChild = (command, args, { cwd, env }, spawn$1 = spawn) => new Promise((
10
15
  env,
11
16
  stdio: "inherit"
12
17
  });
13
- child.on("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error(`${command} is not installed, or not on PATH`) : error));
14
- child.on("close", (status) => status === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`\`${command} ${args.join(" ")}\` exited with status ${status}`)));
18
+ const forward = (signal) => void child.kill(signal);
19
+ for (const signal of forwarded) process.on(signal, forward);
20
+ const done = () => {
21
+ for (const signal of forwarded) process.off(signal, forward);
22
+ };
23
+ child.on("error", (error) => {
24
+ done();
25
+ reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error(`${command} is not installed, or not on PATH`) : error);
26
+ });
27
+ child.on("close", (status, signal) => {
28
+ done();
29
+ if (status === 0) resolve();
30
+ else reject(/* @__PURE__ */ new Error(`\`${command} ${args.join(" ")}\` ${signal ? `ended on ${signal}` : `exited with status ${status}`}`));
31
+ });
15
32
  });
16
33
  //#endregion
17
34
  export { runChild };
@@ -0,0 +1,51 @@
1
+ //#region src/mobile/privacy-manifest.ts
2
+ /** Where the manifest goes in the generated iOS project, from `ios/`. */
3
+ const privacyManifestPath = [
4
+ "App",
5
+ "App",
6
+ "PrivacyInfo.xcprivacy"
7
+ ];
8
+ /** The app's privacy manifest: the live updater keeps its state in UserDefaults, for the app itself only (CA92.1). */
9
+ const privacyManifest = `<?xml version="1.0" encoding="UTF-8"?>
10
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
11
+ <plist version="1.0">
12
+ <dict>
13
+ <key>NSPrivacyAccessedAPITypes</key>
14
+ <array>
15
+ <dict>
16
+ <key>NSPrivacyAccessedAPIType</key>
17
+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>
18
+ <key>NSPrivacyAccessedAPITypeReasons</key>
19
+ <array>
20
+ <string>CA92.1</string>
21
+ </array>
22
+ </dict>
23
+ </array>
24
+ <key>NSPrivacyCollectedDataTypes</key>
25
+ <array/>
26
+ <key>NSPrivacyTracking</key>
27
+ <false/>
28
+ <key>NSPrivacyTrackingDomains</key>
29
+ <array/>
30
+ </dict>
31
+ </plist>
32
+ `;
33
+ const fileRefId = "A1B2C3D4E5F6A7B8C9D0E1F2";
34
+ const buildFileId = "A1B2C3D4E5F6A7B8C9D0E1F3";
35
+ const insertions = [
36
+ ["/* End PBXBuildFile section */", `\t\t${buildFileId} /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = ${fileRefId} /* PrivacyInfo.xcprivacy */; };\n`],
37
+ ["/* End PBXFileReference section */", `\t\t${fileRefId} /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };\n`],
38
+ [`\t\t\t\t50379B222058CBB4000EE86E /* capacitor.config.json */,\n`, `\t\t\t\t${fileRefId} /* PrivacyInfo.xcprivacy */,\n`],
39
+ [`\t\t\t\t50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,\n`, `\t\t\t\t${buildFileId} /* PrivacyInfo.xcprivacy in Resources */,\n`]
40
+ ];
41
+ /** The project.pbxproj bundling PrivacyInfo.xcprivacy into the app. */
42
+ const withPrivacyManifest = (pbxproj) => {
43
+ if (pbxproj.includes("A1B2C3D4E5F6A7B8C9D0E1F2") || pbxproj.includes("A1B2C3D4E5F6A7B8C9D0E1F3")) throw new Error("project.pbxproj already has the privacy manifest's ids");
44
+ return insertions.reduce((text, [anchor, line]) => {
45
+ const parts = text.split(anchor);
46
+ if (parts.length !== 2) throw new Error(`project.pbxproj has \`${anchor.trim()}\` ${parts.length - 1} times, not once as in Capacitor's template`);
47
+ return parts.join(`${line}${anchor}`);
48
+ }, pbxproj);
49
+ };
50
+ //#endregion
51
+ export { buildFileId, fileRefId, privacyManifest, privacyManifestPath, withPrivacyManifest };
@@ -1,5 +1,6 @@
1
1
  import { resolveExtensions } from "../project/extensions.js";
2
- import { parsePlatform, parsePort } from "./arguments.js";
2
+ import { parseAppVersion, parseBuildNumber, parsePlatform, parsePort, parseSigningName, parseTeamId } from "./arguments.js";
3
+ import path from "node:path";
3
4
  //#region src/mobile/register.ts
4
5
  const out = (text) => process.stdout.write(text);
5
6
  const collect = (value, previous) => [...previous, value];
@@ -28,6 +29,30 @@ const registerMobile = (program) => {
28
29
  ...opts.api !== void 0 && { api: opts.api }
29
30
  }, out);
30
31
  });
32
+ mobile.command("build").description("Generate the native project and build a signed release: an .aab for Google Play, an .ipa for the App Store").argument("<platform>", "ios or android", parsePlatform).requiredOption("--app-version <version>", "the version the stores show, such as 1.2.3", parseAppVersion).requiredOption("--build-number <number>", "the build number, higher with each upload", parseBuildNumber).option(api, `${apiHelp}; https only`).option("--out <dir>", "the folder the binary goes to", "mobile-release").option("--team <id>", "iOS: your Apple Developer team id", parseTeamId).option("--certificate <name>", "iOS, manual signing: the signing certificate", parseSigningName).option("--profile <name>", "iOS, manual signing: the provisioning profile", parseSigningName).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
33
+ if (chosen === "android" && (opts.team || opts.certificate || opts.profile)) throw new Error("--team, --certificate and --profile are for iOS: Android signs with the PROTOBASE_ANDROID_* variables");
34
+ if (Boolean(opts.certificate) !== Boolean(opts.profile)) throw new Error("Manual signing takes both --certificate and --profile");
35
+ const { mobileBuild } = await import("./build.js");
36
+ const projectDir = process.cwd();
37
+ await mobileBuild({
38
+ projectDir,
39
+ platform: chosen,
40
+ extensions: resolveExtensions(opts.extend),
41
+ ...opts.api !== void 0 && { api: opts.api },
42
+ version: {
43
+ version: opts.appVersion,
44
+ build: opts.buildNumber
45
+ },
46
+ outDir: path.resolve(projectDir, opts.out),
47
+ ...opts.team && { ios: {
48
+ team: opts.team,
49
+ ...opts.certificate && { manual: {
50
+ certificate: opts.certificate,
51
+ profile: opts.profile
52
+ } }
53
+ } }
54
+ }, out);
55
+ });
31
56
  };
32
57
  //#endregion
33
58
  export { registerMobile };
@@ -0,0 +1,44 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { copyFile, mkdir, writeFile } from "node:fs/promises";
4
+ //#region src/mobile/release-output.ts
5
+ const androidBundle = [
6
+ "android",
7
+ "app",
8
+ "build",
9
+ "outputs",
10
+ "bundle",
11
+ "release",
12
+ "app-release.aab"
13
+ ];
14
+ const iosOutput = [
15
+ "ios",
16
+ "App",
17
+ "output"
18
+ ];
19
+ /** The signed binary the build left in the workspace `ws`; it throws when there is none, as after a failed build. */
20
+ const releaseFile = (ws, platform) => {
21
+ if (platform === "android") {
22
+ const file = path.join(ws, ...androidBundle);
23
+ if (!existsSync(file)) throw new Error(`The Android build left no ${file}`);
24
+ return file;
25
+ }
26
+ const dir = path.join(ws, ...iosOutput);
27
+ const ipas = existsSync(dir) ? readdirSync(dir).filter((name) => name.endsWith(".ipa")) : [];
28
+ if (ipas.length !== 1) throw new Error(`The iOS build left ${ipas.length} .ipa files in ${dir}, not one`);
29
+ return path.join(dir, ipas[0]);
30
+ };
31
+ /**
32
+ * Copies the binary `file` into `outDir` as `<name>.aab` or `<name>.ipa`. A folder it creates ignores itself in git,
33
+ * so a signed binary is never committed by accident; a `.gitignore` already there is left as it is.
34
+ */
35
+ const copyRelease = async (file, outDir, name) => {
36
+ await mkdir(outDir, { recursive: true });
37
+ const ignore = path.join(outDir, ".gitignore");
38
+ if (!existsSync(ignore)) await writeFile(ignore, "*\n");
39
+ const target = path.join(outDir, `${name}${path.extname(file)}`);
40
+ await copyFile(file, target);
41
+ return target;
42
+ };
43
+ //#endregion
44
+ export { copyRelease, releaseFile };
@@ -0,0 +1,18 @@
1
+ import { withReleaseSigning } from "./android-signing.js";
2
+ import { withAndroidVersion, withIosVersion } from "./app-version.js";
3
+ import { privacyManifest, privacyManifestPath, withPrivacyManifest } from "./privacy-manifest.js";
4
+ import path from "node:path";
5
+ import { readFile, writeFile } from "node:fs/promises";
6
+ //#region src/mobile/release-project.ts
7
+ const edit = async (file, change) => writeFile(file, change(await readFile(file, "utf8")));
8
+ /**
9
+ * Makes the native project `cap add` generated in the workspace `ws` a release: the version and build number, and on
10
+ * Android signing from the environment, on iOS the privacy manifest.
11
+ */
12
+ const prepareReleaseProject = async (ws, platform, version) => {
13
+ if (platform === "android") return edit(path.join(ws, "android", "app", "build.gradle"), (gradle) => withReleaseSigning(withAndroidVersion(gradle, version)));
14
+ await edit(path.join(ws, "ios", "App", "App.xcodeproj", "project.pbxproj"), (pbxproj) => withPrivacyManifest(withIosVersion(pbxproj, version)));
15
+ await writeFile(path.join(ws, "ios", ...privacyManifestPath), privacyManifest);
16
+ };
17
+ //#endregion
18
+ export { prepareReleaseProject };
@@ -1,11 +1,12 @@
1
- import { apiUrl, httpAllowances } from "./api-origin.js";
1
+ import { withoutAndroidSigning } from "./android-signing.js";
2
+ import { runChild } from "./child-process.js";
3
+ import { apiUrl, checkReleaseUrl, httpAllowances } from "./api-origin.js";
2
4
  import { capRunArgs } from "./cap-run-args.js";
3
5
  import { installedPackage } from "./installed-package.js";
4
6
  import { capacitorRunner } from "./capacitor.js";
5
7
  import { buildWebPart, placeholderWebPart } from "./web-part.js";
6
8
  import { capacitorConfig, writeCapacitorConfig } from "./capacitor-config.js";
7
9
  import { childEnv, envFileKeys, projectEnvFiles } from "./child-env.js";
8
- import { runChild } from "./child-process.js";
9
10
  import { nativeFingerprint } from "./fingerprint.js";
10
11
  import { generatePlatform } from "./generate.js";
11
12
  import { checkInstalledPlugins } from "./pinned-packages.js";
@@ -15,12 +16,13 @@ import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from
15
16
  import path from "node:path";
16
17
  import { defaultAppName } from "@protobase/server";
17
18
  //#region src/mobile/run.ts
18
- const prepare = async ({ projectDir, platform, api, extensions, live }, { run = runChild, build }) => {
19
- const env = childEnv({ ...process.env }, envFileKeys(projectEnvFiles(projectDir)));
19
+ const prepare = async ({ projectDir, platform, api, extensions, live, release }, { run = runChild, build }) => {
20
+ const env = withoutAndroidSigning(childEnv({ ...process.env }, envFileKeys(projectEnvFiles(projectDir))));
20
21
  if (live !== void 0 && api !== void 0) throw new Error("--live opens protobase dev, which serves the API itself: leave out --api");
21
22
  const project = await loadMobileProject(projectDir, extensions);
22
23
  const mobile = checkMobileConfig(project.mobile);
23
24
  const url = live === void 0 ? apiUrl(api, project.auth?.issuer, platform) : new URL(`http://localhost:${live}`);
25
+ if (release) checkReleaseUrl(url);
24
26
  const allowances = httpAllowances(url);
25
27
  const ws = workspaceDir(projectDir);
26
28
  const plugins = Object.keys(mobile.plugins ?? {});
@@ -59,7 +61,9 @@ const prepare = async ({ projectDir, platform, api, extensions, live }, { run =
59
61
  ws,
60
62
  url,
61
63
  fingerprint,
62
- cap
64
+ cap,
65
+ env,
66
+ appId: mobile.appId
63
67
  };
64
68
  };
65
69
  const summary = (projectDir, { ws, url, fingerprint }) => `workspace ${path.relative(projectDir, ws)}, api ${url.origin}, native fingerprint ${fingerprint}\n`;
@@ -81,4 +85,4 @@ const mobileOpen = async (input, out, deps = {}) => {
81
85
  await prepared.cap(["open", input.platform]);
82
86
  };
83
87
  //#endregion
84
- export { mobileOpen, mobileRun };
88
+ export { mobileOpen, mobileRun, prepare, summary };
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import path from "node:path";
3
- import { realtimeLimits } from "@protobase/server";
3
+ import { honorSocketMessageCaps, realtimeLimits, socketMessageCapOf } from "@protobase/server";
4
4
  import { WebSocketServer } from "ws";
5
5
  //#region src/project/api-websocket-server.ts
6
6
  const require = createRequire(import.meta.url);
@@ -21,20 +21,23 @@ const maxPayloadOf = (url) => {
21
21
  };
22
22
  /**
23
23
  * The server of npm `ws` that upgrades the API's sockets, realtime's and the app's functions', on Node and Bun: a frame
24
- * over its socket's cap (`maxPayloadOf`) closes the socket with 1009 before it is read.
24
+ * over its socket's cap (`maxPayloadOf`, or a function's lower `maxMessageBytes`) closes the socket with 1009 before it
25
+ * is read.
25
26
  */
26
27
  const apiWebSocketServer = () => {
27
28
  const Base = npmWebSocketServer();
28
29
  class ApiWebSocketServer extends Base {
29
30
  handleUpgrade(...[request, ...rest]) {
30
- this.options.maxPayload = maxPayloadOf(request.url ?? "");
31
+ this.options.maxPayload = Math.min(maxPayloadOf(request.url ?? ""), socketMessageCapOf(request) ?? Infinity);
31
32
  super.handleUpgrade(request, ...rest);
32
33
  }
33
34
  }
34
- return new ApiWebSocketServer({
35
+ const server = new ApiWebSocketServer({
35
36
  noServer: true,
36
37
  maxPayload: realtimeLimits.maxFrameBytes
37
38
  });
39
+ honorSocketMessageCaps(server);
40
+ return server;
38
41
  };
39
42
  //#endregion
40
43
  export { apiWebSocketServer, maxPayloadOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.40.1",
3
+ "version": "0.40.3",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  "@better-auth/core": "^1.7.12",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.40.1",
40
- "@protobase/query": "0.40.1",
41
- "@protobase/schema": "0.40.1",
42
- "@protobase/server": "0.40.1",
43
- "@protobase/ui": "0.40.1",
39
+ "@protobase/layout": "0.40.3",
40
+ "@protobase/query": "0.40.3",
41
+ "@protobase/schema": "0.40.3",
42
+ "@protobase/server": "0.40.3",
43
+ "@protobase/ui": "0.40.3",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -175,6 +175,7 @@ A client that is no browser sends `Authorization: Bearer <token>` with its upgra
175
175
  | `onMessage(data, socket)` | Text arrives as a string, binary as an `ArrayBuffer`, byte for byte. Messages come one at a time and in order. |
176
176
  | `onClose(code, reason)` | Either side closed it, after the last message. |
177
177
  | `recheck()` | Runs every minute while the socket is open, after the framework's own check. A `401`, `403` or `404` problem it throws closes the socket with `1008`; any other error is reported and closes it with `1011`, as does a check that has not finished a minute later. What it returns is ignored, so refuse by throwing. |
178
+ | `maxMessageBytes` | Not an event: the largest message the socket takes, in bytes, a whole number of at least 1. A larger one closes the socket with `1009` before the server reads it, and `onMessage` never sees it. |
178
179
 
179
180
  `socket.send(data)` takes a string, an `ArrayBuffer` or a `Uint8Array`, and `socket.close(code?, reason?)` closes it. A handler that throws closes the socket with `1011`, and the error is reported like any other.
180
181
 
@@ -280,7 +281,7 @@ The ticket only lets the socket open, and anyone who holds it may open one with
280
281
 
281
282
  - **Await `send`** when the other side may read slowly: it resolves once the data is written, so a relay that awaits each send never piles up data in the server. It never rejects; after a close it resolves at once.
282
283
  - **Return a promise from `onMessage`** to hold the next message back until it settles. Above 1 MiB of waiting messages the server stops reading from the client, which slows it down, and reads again once they are handled. Bun's built-in `ws`, which `protobase dev` uses on Bun, cannot stop reading: there the socket closes with `1013` once 16 MiB are waiting.
283
- - **A message** may be up to 100 MiB.
284
+ - **A message** may be up to 100 MiB, or the socket's `maxMessageBytes`, which only lowers it. A larger message closes the socket with `1009` before the server reads it, so a function that only takes small messages sets it, such as `acceptWebSocket({ maxMessageBytes: 64 * 1024, onMessage })`. `protobase dev` and `protobase serve` apply it; a server of your own that hosts `createAdmin` refuses a socket with `maxMessageBytes` with a `500`, since its `ws` server would not apply it.
284
285
 
285
286
  ### Restarts
286
287
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  # A mobile app
4
4
 
5
- Run a Protobase app on iOS and Android from a mobile section in its config, without setting up Capacitor yourself.
5
+ Run a Protobase app on iOS and Android and build signed store releases from a mobile section in its config, without setting up Capacitor yourself.
6
6
 
7
7
  A Protobase app runs as an iOS or Android app with nothing more than a `mobile` section in its `protobase.config.ts`. `protobase mobile` wraps the app in [Capacitor](https://capacitorjs.com): the app's shell, its UI plugins, theme and favicon open from files on the device, and the app calls your server's API.
8
8
 
@@ -62,3 +62,42 @@ protobase mobile open ios
62
62
  ```
63
63
 
64
64
  opens the generated project in Xcode, or Android Studio for `android`. To run on an iPhone, pick a signing team in Xcode's Signing & Capabilities.
65
+
66
+ ## 6. Build a release
67
+
68
+ ```sh
69
+ protobase mobile build android --app-version 1.2.3 --build-number 7 --api https://shop.example.com
70
+ protobase mobile build ios --app-version 1.2.3 --build-number 7 --api https://shop.example.com --team ABCDE12345
71
+ ```
72
+
73
+ makes a signed release binary: an `.aab` to upload to Google Play, an `.ipa` to upload to App Store Connect. It goes to `mobile-release/`, which ignores itself in git, named `<appId>-<version>-<build number>`; `--out <dir>` picks another folder.
74
+
75
+ - The binary carries the app's files, so it opens without a network and never downloads anything on its first launch; offline it says it cannot reach the server, as the web app does.
76
+ - A release calls its server over https, at `--api` or the project's auth `baseURL`: plain http, `localhost` and `10.0.2.2` are refused.
77
+ - `--app-version` is the version the stores show, one to three numbers such as `1.2.3`. `--build-number` is a whole number that must rise with every upload, such as your CI's run number.
78
+ - Extra plugins run at build time with access to your signing key, so add only plugins you trust.
79
+
80
+ **Android.** Make an upload key once, outside the project, and never commit it:
81
+
82
+ ```sh
83
+ keytool -genkeypair -v -keystore ~/.android-keys/upload.jks -keyalg RSA -keysize 2048 -validity 10000 -alias upload
84
+ ```
85
+
86
+ Use it as the upload key with Play App Signing. Set these variables in your shell or as CI secrets, never as command arguments, where other users of the machine can read them:
87
+
88
+ - `PROTOBASE_ANDROID_KEYSTORE`: the keystore file, absolute or relative to the project folder.
89
+ - `PROTOBASE_ANDROID_KEYSTORE_PASSWORD` and `PROTOBASE_ANDROID_KEY_PASSWORD`: its passwords.
90
+ - `PROTOBASE_ANDROID_KEY_ALIAS`: the key's alias, `upload` above.
91
+
92
+ Only Gradle gets them, for the length of the build: npm, its install scripts and Capacitor never do. The build needs the Android SDK and JDK 21.
93
+
94
+ **iOS**, on a Mac with Xcode: `--team` is your Apple Developer team id, shown in your account's membership details. Xcode signs with the certificates and profiles of the account you added in its settings. For manual signing, pass `--certificate <name>` and `--profile <name>` too. If automatic signing finds no profile for a new app, run `protobase mobile open ios`, pick the team in Signing & Capabilities and archive once from Xcode (Product, Archive), which creates the profile; then build again.
95
+
96
+ ## 7. What the stores accept
97
+
98
+ You submit the app under your own developer account, on both stores: Apple rejects apps from a template or app generation service unless the provider of the app's content submits them ([App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) 4.2.6).
99
+
100
+ - **What may change without a store release:** the app's files, which a later Protobase release can update over the air: the shell, UI plugins, theme, in-app logo and copy, and fixes and features within the app's purpose. Apple allows downloaded interpreted code that does not change the app's primary purpose ([Apple Developer Program License Agreement](https://developer.apple.com/support/terms/apple-developer-program-license-agreement/) 3.3.1(B)), and Google Play allows JavaScript in a WebView ([Device and Network Abuse](https://support.google.com/googleplay/android-developer/answer/9888379)).
101
+ - **What needs a store release:** native code, Capacitor or plugin changes (`mobile.plugins`), permissions, the app's name, its home-screen icon and its splash screen.
102
+ - **Big new features** still go through Apple's review with a store release, even when they could ship over the air: Apple asks that an app's features be documented and reviewed, none hidden (App Review Guidelines 2.3.1 and 2.5.19).
103
+ - **A plain WebView of an admin app risks rejection:** Apple expects an app to be more than a repackaged website (4.2). Native touches help, such as push notifications, sharing, the camera or biometric sign-in, through `mobile.plugins`.
@@ -525,6 +525,8 @@ Remove `supabase-import/` to import again. Signing in Supabase's users with Prot
525
525
  ```sh
526
526
  protobase mobile run <ios|android> [--api <url>] [--target <id>] [--live] [--port 5173] [--extend <dir>]
527
527
  protobase mobile open <ios|android> [--api <url>] [--extend <dir>]
528
+ protobase mobile build <ios|android> --app-version <x.y.z> --build-number <n> [--api <url>] [--out mobile-release] [--extend <dir>]
529
+ [--team <id> [--certificate <name> --profile <name>]]
528
530
  ```
529
531
 
530
532
  Builds the project in the current directory as an iOS or Android app with Capacitor, from the `mobile` section of its `protobase.config.ts`; without one it stops and says what to add. See [A mobile app](../guides/mobile-app.md)).
@@ -532,7 +534,9 @@ Builds the project in the current directory as an iOS or Android app with Capaci
532
534
  - It installs `@protobase/mobile`, of the CLI's version, which pins Capacitor and its plugins, with the section's `plugins` into `.protobase/mobile/` with npm, when that changed. It builds the app's files as [`build`](#build) does and keeps only `public/`, its `index.html` naming the API origin; writes `capacitor.config.json`, compiling in only the section's plugins; and generates the platform's native project again, replacing the last one.
533
535
  - `--api` is the server the app calls, the project's auth `baseURL` by default: an http or https origin, plain http only to `localhost`, `127.0.0.1` and, on iOS, `[::1]`, or on Android `10.0.2.2`. An Android app calling `localhost` gets the port forwarded.
534
536
  - `run` runs the app on `--target`, or asks for one. With `--live` it opens `protobase dev` on `localhost:--port` instead of its own files. `open` opens the native project in Xcode or Android Studio.
535
- - npm and Capacitor get the CLI's environment without any variable named in the current directory's `.env*` files, and with `CI=true`, which keeps Capacitor's telemetry off.
537
+ - `build` makes a signed release, an `.aab` (Android) or `.ipa` (iOS), and copies it to `--out`, which ignores itself in git when the command creates it, as `<appId>-<version>-<build number>`. Android signs through Gradle with the keystore, alias and passwords in `PROTOBASE_ANDROID_KEYSTORE`, `PROTOBASE_ANDROID_KEY_ALIAS`, `PROTOBASE_ANDROID_KEYSTORE_PASSWORD` and `PROTOBASE_ANDROID_KEY_PASSWORD`; iOS runs Capacitor's build with `--team`, and `--certificate` with `--profile` for manual signing.
538
+ - A release calls an https server that is not this machine, and `--app-version` (one to three numbers) and `--build-number` (1 to 2100000000) are required.
539
+ - npm and Capacitor get the CLI's environment without any variable named in the current directory's `.env*` files, nor the four `PROTOBASE_ANDROID_*` signing variables, which only Gradle gets, and with `CI=true`, which keeps Capacitor's telemetry off.
536
540
  - It prints the workspace, the API origin and the native fingerprint, which the app also sends in its user agent as `ProtobaseNative/<fingerprint>`: a hash of the `@protobase/mobile` version and the extra plugins' installed versions.
537
541
 
538
542
  ## `token`