native-update 4.3.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,7 +28,7 @@ are available as an HTTP API for CI and coding agents.
28
28
 
29
29
  | | |
30
30
  |---|---|
31
- | **Version** | `4.3.0` |
31
+ | **Version** | `4.4.1` |
32
32
  | **License** | Proprietary — free to use in your apps ([LICENSE](./LICENSE)) |
33
33
  | **Node** | `>=24.16.0` (install + CLI toolchain) |
34
34
  | **Platforms** | iOS 14+ · Android 8.0+ (API 26) · Web |
@@ -383,6 +383,12 @@ npx native-update deploy ./dist --app com.example.app --version 1.2.0 --wait
383
383
  | `--channel <name>` | `production` | release channel |
384
384
  | `--rollout <percent>` | — | release to a percentage of devices |
385
385
  | `--wait` | `false` | block until the queued upload finishes — **use this in CI** |
386
+ | `--ota-tag <prefix>` | — | publish as `<version>-<prefix><N>`, e.g. `1.16.1-nu2`; N restarts at 1 when the version changes |
387
+ | `--min-native <version>` | `versionName` in `android/app/build.gradle` with `--ota-tag` | lowest binary that may receive the bundle |
388
+ | `--dry-run` | `false` | print the version, channel and minimum native version; upload nothing |
389
+
390
+ A tag sorts below its own version (`1.16.1-nu3` < `1.16.1`), so the store release of that version supersedes it,
391
+ and the version must be above the `versionName` your devices run: `--ota-tag` refuses it otherwise.
386
392
 
387
393
  Full reference: [CLI docs](https://nativeupdate-docs.aoneahsan.com/reference/cli/overview).
388
394
 
@@ -513,9 +519,9 @@ indexed at [`/raw/manifest.json`](https://nativeupdate-docs.aoneahsan.com/raw/ma
513
519
  <a id="changelog"></a>
514
520
  ## 🔄 Changelog&nbsp;[#](#changelog)
515
521
 
516
- Latest release: **`4.3.0`**. Every update check now says which SDK is asking (`X-Client-Sdk: capacitor`) and its
517
- version, so the server only ever offers a Capacitor app a web bundle, never a native asset set built for another
518
- platform. No API change; 4.2.4's Android fixes are included.
522
+ Latest release: **`4.4.1`**. OTA version tags: `deploy --ota-tag nu` publishes `1.16.1-nu1`, `-nu2` and so
523
+ on, and every version comparison in the plugin now orders `-nu10` after `-nu9`. Before that, **`4.4.0`** added Dart
524
+ code patches for Flutter apps (`bundle flutter-patch`, `deploy --payload-type dart_aot`).
519
525
 
520
526
  Full history ships inside the package at `docs/CHANGELOG.md`, so it always matches the version you
521
527
  installed. It is also published as the
@@ -61,7 +61,7 @@ class LiveUpdatePlugin(
61
61
 
62
62
  companion object {
63
63
  /** This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts. */
64
- const val SDK_VERSION = "4.3.0"
64
+ const val SDK_VERSION = "4.4.1"
65
65
 
66
66
  // SharedPreferences keys. Kept as constants so A2 (boot-time
67
67
  // re-verification) and A3 (crash-loop auto-rollback) stay in sync
@@ -1031,16 +1031,8 @@ class LiveUpdatePlugin(
1031
1031
  }
1032
1032
  }
1033
1033
 
1034
- /** Numeric dotted-version comparison (1.10.0 > 1.9.0); a pre-release or build suffix is ignored. */
1035
- private fun compareVersions(left: String, right: String): Int {
1036
- val a = left.substringBefore('-').substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }
1037
- val b = right.substringBefore('-').substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }
1038
- for (index in 0 until maxOf(a.size, b.size)) {
1039
- val difference = (a.getOrNull(index) ?: 0) - (b.getOrNull(index) ?: 0)
1040
- if (difference != 0) return difference
1041
- }
1042
- return 0
1043
- }
1034
+ /** The shared version order: OTA tags such as 1.16.1-nu10 sort after 1.16.1-nu9 ([VersionOrder]). */
1035
+ private fun compareVersions(left: String, right: String): Int = VersionOrder.compare(left, right)
1044
1036
 
1045
1037
  fun cleanup() {
1046
1038
  // Clean up any resources
@@ -0,0 +1,60 @@
1
+ package com.aoneahsan.nativeupdate
2
+
3
+ /**
4
+ * The plugin's one version order, identical to the TypeScript `compareVersions` and the server's PHP
5
+ * `version_compare` for the shapes we ship.
6
+ *
7
+ * Semver precedence, plus one refinement: a pre-release identifier ending in digits compares those digits as a
8
+ * number, so the OTA tag `1.16.1-nu10` is newer than `1.16.1-nu9`. An OTA tag sorts below its own base
9
+ * (`1.16.1-nu3` < `1.16.1`), so a store release of that base supersedes it. Build metadata (`+…`) is ignored.
10
+ */
11
+ object VersionOrder {
12
+ private val numeric = Regex("^\\d+$")
13
+ private val lettersThenDigits = Regex("^(.*?)(\\d+)$")
14
+
15
+ /** Negative when [left] is older, zero when equal, positive when [left] is newer. */
16
+ fun compare(left: String, right: String): Int {
17
+ val a = parse(left)
18
+ val b = parse(right)
19
+ for (index in 0 until maxOf(a.first.size, b.first.size, 3)) {
20
+ val difference = (a.first.getOrNull(index) ?: 0L).compareTo(b.first.getOrNull(index) ?: 0L)
21
+ if (difference != 0) return difference
22
+ }
23
+ val preA = a.second
24
+ val preB = b.second
25
+ if (preA.isEmpty() && preB.isEmpty()) return 0
26
+ if (preA.isEmpty()) return 1
27
+ if (preB.isEmpty()) return -1
28
+ for (index in 0 until maxOf(preA.size, preB.size)) {
29
+ val leftId = preA.getOrNull(index) ?: return -1
30
+ val rightId = preB.getOrNull(index) ?: return 1
31
+ val result = compareIdentifier(leftId, rightId)
32
+ if (result != 0) return result
33
+ }
34
+ return 0
35
+ }
36
+
37
+ private fun parse(version: String): Pair<List<Long>, List<String>> {
38
+ val withoutBuild = version.trim().removePrefix("v").removePrefix("V").substringBefore('+')
39
+ val core = withoutBuild.substringBefore('-')
40
+ val pre = if (withoutBuild.contains('-')) withoutBuild.substringAfter('-') else ""
41
+ return Pair(
42
+ core.split('.').map { it.toLongOrNull() ?: 0L },
43
+ if (pre.isEmpty()) emptyList() else pre.split('.'),
44
+ )
45
+ }
46
+
47
+ private fun compareIdentifier(left: String, right: String): Int {
48
+ val leftNumeric = numeric.matches(left)
49
+ val rightNumeric = numeric.matches(right)
50
+ if (leftNumeric && rightNumeric) return left.toBigInteger().compareTo(right.toBigInteger())
51
+ if (leftNumeric) return -1
52
+ if (rightNumeric) return 1
53
+ val leftTail = lettersThenDigits.find(left)
54
+ val rightTail = lettersThenDigits.find(right)
55
+ if (leftTail != null && rightTail != null && leftTail.groupValues[1] == rightTail.groupValues[1]) {
56
+ return leftTail.groupValues[2].toBigInteger().compareTo(rightTail.groupValues[2].toBigInteger())
57
+ }
58
+ return left.compareTo(right).coerceIn(-1, 1)
59
+ }
60
+ }
@@ -0,0 +1,107 @@
1
+ import chalk from 'chalk';
2
+ import crypto from 'crypto';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+ import zlib from 'zlib';
6
+ import { ZipArchive } from 'archiver';
7
+ import { createWriteStream } from 'fs';
8
+
9
+ /**
10
+ * Reads the entries of a ZIP (an APK) from its central directory. Handles stored and deflated entries, which is
11
+ * everything the Android build tools write. Returns a Map of name -> { read(): Buffer }.
12
+ */
13
+ async function readZip(filePath) {
14
+ const buf = await fs.readFile(filePath);
15
+ const minEnd = Math.max(0, buf.length - 0xffff - 22);
16
+ let end = -1;
17
+ for (let i = buf.length - 22; i >= minEnd; i--) {
18
+ if (buf.readUInt32LE(i) === 0x06054b50) {
19
+ end = i;
20
+ break;
21
+ }
22
+ }
23
+ if (end < 0) throw new Error(`${filePath} is not a ZIP/APK file`);
24
+ const count = buf.readUInt16LE(end + 10);
25
+ let offset = buf.readUInt32LE(end + 16);
26
+ const entries = new Map();
27
+ for (let i = 0; i < count; i++) {
28
+ if (buf.readUInt32LE(offset) !== 0x02014b50) throw new Error('Corrupt ZIP central directory');
29
+ const method = buf.readUInt16LE(offset + 10);
30
+ const compressed = buf.readUInt32LE(offset + 20);
31
+ const nameLength = buf.readUInt16LE(offset + 28);
32
+ const extraLength = buf.readUInt16LE(offset + 30);
33
+ const commentLength = buf.readUInt16LE(offset + 32);
34
+ const local = buf.readUInt32LE(offset + 42);
35
+ const name = buf.toString('utf8', offset + 46, offset + 46 + nameLength);
36
+ entries.set(name, {
37
+ read() {
38
+ const localName = buf.readUInt16LE(local + 26);
39
+ const localExtra = buf.readUInt16LE(local + 28);
40
+ const start = local + 30 + localName + localExtra;
41
+ const data = buf.subarray(start, start + compressed);
42
+ if (method === 0) return Buffer.from(data);
43
+ if (method === 8) return zlib.inflateRawSync(data);
44
+ throw new Error(`Unsupported ZIP compression method ${method} for ${name}`);
45
+ },
46
+ });
47
+ offset += 46 + nameLength + extraLength + commentLength;
48
+ }
49
+ return entries;
50
+ }
51
+
52
+ const sha256 = (data) => crypto.createHash('sha256').update(data).digest('hex');
53
+
54
+ /**
55
+ * `native-update bundle flutter-patch <apk>`: turns a Flutter RELEASE APK into a Dart code update.
56
+ *
57
+ * The patch holds lib/<abi>/libapp.so for every architecture in the APK, plus the files of --assets. Next to it,
58
+ * <out>.runtime-keys lists the SHA-256 of each libflutter.so: a device is offered the patch only when its own engine
59
+ * is one of them, because compiled Dart code runs only on the engine it was built against. Build the patch APK from
60
+ * the same Flutter version and the same native plugins as the app build it updates.
61
+ */
62
+ export async function createFlutterPatch(apkPath, options) {
63
+ const entries = await readZip(apkPath);
64
+ const abis = [...entries.keys()]
65
+ .map((name) => /^lib\/([^/]+)\/libapp\.so$/.exec(name)?.[1])
66
+ .filter(Boolean);
67
+ if (abis.length === 0) {
68
+ throw new Error(
69
+ `${apkPath} has no lib/<abi>/libapp.so. Build it with \`flutter build apk --release\` (debug builds carry no compiled Dart code).`
70
+ );
71
+ }
72
+
73
+ const out = path.resolve(options.output ?? 'flutter-patch.zip');
74
+ const stage = await fs.mkdtemp(path.join(path.dirname(out), '.flutter-patch-'));
75
+ const keys = [];
76
+ try {
77
+ for (const abi of abis) {
78
+ const engine = entries.get(`lib/${abi}/libflutter.so`);
79
+ if (!engine) throw new Error(`${apkPath} has libapp.so for ${abi} but no libflutter.so`);
80
+ keys.push({ abi, key: sha256(engine.read()) });
81
+ await fs.mkdir(path.join(stage, 'lib', abi), { recursive: true });
82
+ await fs.writeFile(path.join(stage, 'lib', abi, 'libapp.so'), entries.get(`lib/${abi}/libapp.so`).read());
83
+ }
84
+ if (options.assets) {
85
+ await fs.cp(path.resolve(options.assets), stage, { recursive: true, filter: (src) => !src.includes(`${path.sep}lib${path.sep}`) });
86
+ }
87
+
88
+ await new Promise((resolve, reject) => {
89
+ const output = createWriteStream(out);
90
+ const zip = new ZipArchive({ zlib: { level: 9 } });
91
+ output.on('close', resolve);
92
+ zip.on('error', reject);
93
+ zip.pipe(output);
94
+ zip.directory(stage, false);
95
+ zip.finalize();
96
+ });
97
+ } finally {
98
+ await fs.rm(stage, { recursive: true, force: true });
99
+ }
100
+
101
+ await fs.writeFile(`${out}.runtime-keys`, keys.map((k) => k.key).join('\n') + '\n');
102
+ const size = (await fs.stat(out)).size;
103
+ console.log(chalk.green(`✓ Dart code patch: ${out} (${(size / 1024 / 1024).toFixed(2)} MB)`));
104
+ for (const { abi, key } of keys) console.log(chalk.gray(` ${abi.padEnd(12)} engine ${key}`));
105
+ console.log(chalk.gray(` Engine keys written to ${out}.runtime-keys; deploy picks them up:`));
106
+ console.log(chalk.gray(` npx native-update deploy ${path.relative(process.cwd(), out)} --app <app> --version <v> --payload-type dart_aot --wait`));
107
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * OTA version tags: `<base>-<prefix><N>`, e.g. `1.16.1-nu2`.
3
+ *
4
+ * `base` is the app's own version (package.json). `N` counts the OTA builds already published on that base in
5
+ * the channel, and starts again at 1 when the base changes. The tag sorts below its own base, so the store
6
+ * release of that base supersedes every OTA build of it — which is why the base must be ABOVE the native
7
+ * versionName the devices run: a tag on the same base as the installed binary is never offered to it.
8
+ *
9
+ * Pure functions only, so they can be unit-tested without a network or a file system.
10
+ */
11
+
12
+ const PREFIX_PATTERN = /^[a-z]+$/;
13
+ const BASE_PATTERN = /^\d+\.\d+\.\d+$/;
14
+
15
+ /**
16
+ * Validate the tag prefix (letters only, so the counter is the identifier's numeric tail).
17
+ *
18
+ * @param {string} prefix
19
+ * @returns {string} the prefix, lower-cased
20
+ */
21
+ export function normalizePrefix(prefix) {
22
+ const value = String(prefix ?? '').trim().toLowerCase();
23
+ if (!PREFIX_PATTERN.test(value)) {
24
+ throw new Error(`--ota-tag needs a letters-only prefix such as "nu", not "${prefix}"`);
25
+ }
26
+ return value;
27
+ }
28
+
29
+ /**
30
+ * The base an OTA tag hangs from: a plain `major.minor.patch`.
31
+ *
32
+ * @param {string} version e.g. "1.16.1" (a pre-release or build part is refused)
33
+ * @returns {string}
34
+ */
35
+ export function normalizeBase(version) {
36
+ const value = String(version ?? '').trim().replace(/^v/i, '');
37
+ if (!BASE_PATTERN.test(value)) {
38
+ throw new Error(`OTA base version must be plain major.minor.patch, not "${version}"`);
39
+ }
40
+ return value;
41
+ }
42
+
43
+ /**
44
+ * Compare two plain `major.minor.patch` versions.
45
+ *
46
+ * @returns {number} negative when `left` is older, 0 when equal, positive when newer
47
+ */
48
+ export function compareBase(left, right) {
49
+ const a = left.split('.').map(Number);
50
+ const b = right.split('.').map(Number);
51
+ for (let index = 0; index < 3; index++) {
52
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
53
+ if (difference !== 0) return difference;
54
+ }
55
+ return 0;
56
+ }
57
+
58
+ /**
59
+ * The next OTA tag for `base`, given every version already published in the channel (any status: the server
60
+ * refuses a duplicate version even when the earlier build failed).
61
+ *
62
+ * @param {object} input
63
+ * @param {string} input.base app version, e.g. "1.16.1"
64
+ * @param {string} input.prefix tag prefix, e.g. "nu"
65
+ * @param {string[]} input.existingVersions versions already in the channel
66
+ * @returns {string} e.g. "1.16.1-nu3"
67
+ */
68
+ export function nextOtaTag({ base, prefix, existingVersions }) {
69
+ const cleanBase = normalizeBase(base);
70
+ const cleanPrefix = normalizePrefix(prefix);
71
+ const pattern = new RegExp(`^${cleanBase.replace(/\./g, '\\.')}-${cleanPrefix}(\\d+)$`);
72
+ let highest = 0;
73
+ for (const version of existingVersions ?? []) {
74
+ const match = pattern.exec(String(version).trim());
75
+ if (match) highest = Math.max(highest, Number(match[1]));
76
+ }
77
+ return `${cleanBase}-${cleanPrefix}${highest + 1}`;
78
+ }
79
+
80
+ /**
81
+ * Refuse a base that devices on `nativeVersion` would never be offered.
82
+ *
83
+ * @param {string} base app version
84
+ * @param {string|null} nativeVersion the versionName of the native build in this tree, when known
85
+ * @returns {string|null} an error message, or null when the base is fine
86
+ */
87
+ export function baseProblem(base, nativeVersion) {
88
+ if (!nativeVersion) return null;
89
+ const native = String(nativeVersion).trim().split(/[-+]/)[0];
90
+ if (!BASE_PATTERN.test(native)) return null;
91
+ if (compareBase(normalizeBase(base), native) > 0) return null;
92
+ return (
93
+ `Base ${base} is not above the native versionName ${native}: devices running ${native} would never be ` +
94
+ `offered ${base}-<tag>. Bump the patch first (yarn version --new-version patch --no-git-tag-version), ` +
95
+ 'rebuild, and deploy again.'
96
+ );
97
+ }
98
+
99
+ /**
100
+ * Read `versionName` from an Android module's build.gradle (Groovy or Kotlin DSL).
101
+ *
102
+ * @param {string} gradleText the file's contents
103
+ * @returns {string|null}
104
+ */
105
+ export function versionNameFromGradle(gradleText) {
106
+ const match = /versionName\s*=?\s*["']([^"']+)["']/.exec(gradleText ?? '');
107
+ return match ? match[1] : null;
108
+ }
@@ -0,0 +1,94 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ import { baseProblem, nextOtaTag, versionNameFromGradle } from './ota-tag-core.js';
5
+ import { apiClient } from './remote-shared.js';
6
+
7
+ /** Pages of 50 to read when looking for earlier tags on the same base (newest first). */
8
+ const MAX_PAGES = 10;
9
+
10
+ /**
11
+ * Every version already published in a channel, newest first, read through the management API.
12
+ *
13
+ * @param {ReturnType<import('./remote-shared.js').apiClient>} client
14
+ * @param {string} app app id or numeric id
15
+ * @param {string} channel
16
+ * @returns {Promise<string[]>}
17
+ */
18
+ async function channelVersions(client, app, channel) {
19
+ const versions = [];
20
+ for (let page = 1; page <= MAX_PAGES; page++) {
21
+ const body = await client.get(`/apps/${app}/builds?channel=${encodeURIComponent(channel)}&per_page=50&page=${page}`);
22
+ for (const build of body.data ?? []) versions.push(String(build.version));
23
+ if (!body.meta || body.meta.current_page >= body.meta.last_page) break;
24
+ }
25
+ return versions;
26
+ }
27
+
28
+ /**
29
+ * The native versionName of the Android build in this tree, or null when there is none.
30
+ *
31
+ * @param {string|undefined} explicit `--native-version`
32
+ * @returns {Promise<string|null>}
33
+ */
34
+ export async function nativeVersionName(explicit) {
35
+ if (explicit) return explicit;
36
+ for (const file of ['android/app/build.gradle', 'android/app/build.gradle.kts']) {
37
+ try {
38
+ const found = versionNameFromGradle(await fs.readFile(path.join(process.cwd(), file), 'utf-8'));
39
+ if (found) return found;
40
+ } catch {
41
+ // No Android module here; the caller decides whether that matters.
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ /**
48
+ * Work out the OTA tag for this release.
49
+ *
50
+ * @param {object} input
51
+ * @param {ReturnType<import('./remote-shared.js').apiClient>} input.client
52
+ * @param {string} input.app
53
+ * @param {string} input.channel
54
+ * @param {string} input.base app version the tag hangs from
55
+ * @param {string} input.prefix e.g. "nu"
56
+ * @param {string|undefined} input.nativeVersion `--native-version`
57
+ * @returns {Promise<{ tag: string, nativeVersion: string|null }>}
58
+ */
59
+ export async function resolveOtaTag({ client, app, channel, base, prefix, nativeVersion }) {
60
+ const native = await nativeVersionName(nativeVersion);
61
+ const problem = baseProblem(base, native);
62
+ if (problem) throw new Error(problem);
63
+ const tag = nextOtaTag({ base, prefix, existingVersions: await channelVersions(client, app, channel) });
64
+ return { tag, nativeVersion: native };
65
+ }
66
+
67
+ /**
68
+ * `native-update ota-tag --app <id> --ota-tag nu` — print only the next tag, so a script that signs its bundle
69
+ * locally can stamp the same version into `bundle create` before `deploy`.
70
+ *
71
+ * @param {object} options commander options
72
+ */
73
+ export async function otaTagCommand(options) {
74
+ const base = options.version ?? (await packageVersion());
75
+ if (!base) throw new Error('no --version, and no version found in ./package.json');
76
+ const { tag } = await resolveOtaTag({
77
+ client: apiClient(options),
78
+ app: options.app,
79
+ channel: options.channel,
80
+ base,
81
+ prefix: options.otaTag,
82
+ nativeVersion: options.nativeVersion,
83
+ });
84
+ process.stdout.write(`${tag}\n`);
85
+ }
86
+
87
+ /** The version in ./package.json, or null. */
88
+ export async function packageVersion() {
89
+ try {
90
+ return JSON.parse(await fs.readFile(path.join(process.cwd(), 'package.json'), 'utf-8')).version ?? null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
@@ -117,7 +117,9 @@ export function apiClient(options) {
117
117
  const buffer = await fs.readFile(filePath);
118
118
  form.append('file', new Blob([buffer], { type: 'application/zip' }), path_basename(filePath));
119
119
  for (const [key, value] of Object.entries(fields)) {
120
- if (value !== undefined && value !== null && value !== '') {
120
+ if (Array.isArray(value)) {
121
+ for (const item of value) form.append(`${key}[]`, String(item));
122
+ } else if (value !== undefined && value !== null && value !== '') {
121
123
  form.append(key, String(value));
122
124
  }
123
125
  }
@@ -75,12 +75,44 @@ export async function buildsList(app, options) {
75
75
  export async function deploy(target, options) {
76
76
  const client = apiClient(options);
77
77
 
78
- const version = options.version ?? (await versionFromPackageJson());
78
+ let version = options.version ?? (await versionFromPackageJson());
79
79
  if (!version) {
80
80
  console.error(chalk.red('Error: no --version, and no version found in ./package.json.'));
81
81
  process.exit(1);
82
82
  }
83
83
 
84
+ // --ota-tag nu: publish as <version>-nu<N>, N counting this base's OTA builds in the channel. The minimum
85
+ // native version defaults to the native build in this tree, so the bundle never reaches an older binary
86
+ // that lacks the plugins this web build calls.
87
+ let minNative = options.minNative;
88
+ if (options.otaTag) {
89
+ try {
90
+ const { resolveOtaTag } = await import('./ota-tag.js');
91
+ const resolved = await resolveOtaTag({
92
+ client,
93
+ app: options.app,
94
+ channel: options.channel,
95
+ base: version,
96
+ prefix: options.otaTag,
97
+ nativeVersion: options.nativeVersion,
98
+ });
99
+ version = resolved.tag;
100
+ minNative = minNative ?? resolved.nativeVersion ?? undefined;
101
+ } catch (error) {
102
+ console.error(chalk.red(`Error: ${error.message}`));
103
+ process.exit(1);
104
+ }
105
+ }
106
+
107
+ if (options.dryRun) {
108
+ console.log(chalk.bold('\nDry run — nothing uploaded'));
109
+ console.log(chalk.gray(` App: ${options.app}`));
110
+ console.log(chalk.gray(` Version: ${version}`));
111
+ console.log(chalk.gray(` Channel: ${options.channel}`));
112
+ console.log(chalk.gray(` Min native: ${minNative ?? '(none)'}`));
113
+ return;
114
+ }
115
+
84
116
  const bundle = await resolveBundle(target);
85
117
 
86
118
  try {
@@ -89,6 +121,7 @@ export async function deploy(target, options) {
89
121
  console.log(chalk.gray(` App: ${options.app}`));
90
122
  console.log(chalk.gray(` Version: ${version}`));
91
123
  console.log(chalk.gray(` Channel: ${options.channel}`));
124
+ if (minNative) console.log(chalk.gray(` Min native: ${minNative}`));
92
125
  console.log(chalk.gray(` Bundle: ${(stat.size / 1024 / 1024).toFixed(2)} MB`));
93
126
 
94
127
  // A detached signature from `native-update bundle sign`, if the consumer
@@ -101,18 +134,30 @@ export async function deploy(target, options) {
101
134
  }
102
135
 
103
136
  const payloadType = options.payloadType ?? 'web_bundle';
104
- if (!['web_bundle', 'assets'].includes(payloadType)) {
105
- throw new Error(`--payload-type must be web_bundle or assets, not "${payloadType}"`);
137
+ if (!['web_bundle', 'assets', 'dart_aot'].includes(payloadType)) {
138
+ throw new Error(`--payload-type must be web_bundle, assets or dart_aot, not "${payloadType}"`);
106
139
  }
107
140
  console.log(chalk.gray(` Payload: ${payloadType}`));
141
+ let runtimeKeys;
142
+ if (payloadType === 'dart_aot') {
143
+ const listed = options.runtimeKeys
144
+ ? options.runtimeKeys
145
+ : await fs.readFile(`${target}.runtime-keys`, 'utf8').catch(() => '');
146
+ runtimeKeys = listed.split(/[\s,]+/).filter(Boolean);
147
+ if (runtimeKeys.length === 0) {
148
+ throw new Error('dart_aot needs engine keys: run `bundle flutter-patch` (it writes <zip>.runtime-keys) or pass --runtime-keys');
149
+ }
150
+ console.log(chalk.gray(` Engines: ${runtimeKeys.length}`));
151
+ }
108
152
 
109
153
  const { data } = await client.upload(`/apps/${options.app}/builds`, bundle.path, {
110
154
  payload_type: payloadType,
155
+ runtime_keys: runtimeKeys,
111
156
  version,
112
157
  channel: options.channel,
113
158
  release_notes: options.notes,
114
159
  rollout_percentage: options.rollout,
115
- min_native_version: options.minNative,
160
+ min_native_version: minNative,
116
161
  signature: signature?.value,
117
162
  });
118
163
 
package/cli/index.js CHANGED
@@ -50,6 +50,25 @@ const bundleCmd = program
50
50
  .enablePositionalOptions()
51
51
  .description('Bundle management commands');
52
52
 
53
+ bundleCmd
54
+ .command('flutter-patch <apk>')
55
+ .description(`Turn a Flutter release APK into a signed-ready Dart code update (sideloaded apps only)
56
+
57
+ ${chalk.bold('Examples:')}
58
+ ${chalk.green('npx native-update bundle flutter-patch build/app/outputs/flutter-apk/app-release.apk -o patch.zip')}
59
+ ${chalk.green('npx native-update deploy patch.zip --app com.example.app --version 1.0.1 --payload-type dart_aot --wait')}`)
60
+ .option('-o, --output <file>', 'Patch ZIP to write', 'flutter-patch.zip')
61
+ .option('--assets <dir>', 'Also ship the files in this folder, read with NativeUpdate.file()')
62
+ .action(async (apk, options) => {
63
+ const { createFlutterPatch } = await import('./commands/flutter-patch.js');
64
+ try {
65
+ await createFlutterPatch(apk, options);
66
+ } catch (error) {
67
+ console.error(chalk.red(`Error: ${error.message}`));
68
+ process.exit(1);
69
+ }
70
+ });
71
+
53
72
  bundleCmd
54
73
  .command('create <webDir>')
55
74
  .alias('create-bundle')
@@ -226,6 +245,9 @@ ${chalk.bold('Examples:')}
226
245
  ${chalk.gray('# Block until the release is actually live (recommended in CI)')}
227
246
  ${chalk.green('npx native-update deploy ./dist --app com.example.app --wait')}
228
247
 
248
+ ${chalk.gray('# OTA tag: 1.16.1 → 1.16.1-nu1, then -nu2 … until the version changes')}
249
+ ${chalk.green('npx native-update deploy ./dist --app com.example.app --ota-tag nu --wait')}
250
+
229
251
  ${chalk.gray('# Staged rollout with release notes')}
230
252
  ${chalk.green('npx native-update deploy ./bundle.zip --app 12 --version 1.2.0 --rollout 10 --notes "Bug fixes"')}`)
231
253
  .requiredOption('-a, --app <appIdOrNumericId>', 'App to deploy to (app_id like com.example.app, or numeric id)')
@@ -236,16 +258,40 @@ ${chalk.bold('Examples:')}
236
258
  .option('--min-native <version>', 'Minimum native app version required')
237
259
  .option(
238
260
  '--payload-type <type>',
239
- 'web_bundle (Capacitor / React Native code) or assets (files a native Android or Flutter app reads)',
261
+ 'web_bundle (Capacitor / React Native code), assets (files a native Android or Flutter app reads) or dart_aot (a Flutter code patch from `bundle flutter-patch`)',
240
262
  'web_bundle'
241
263
  )
264
+ .option('--runtime-keys <keys>', 'dart_aot only: comma-separated engine keys (auto-read from a sibling .runtime-keys)')
242
265
  .option('--signature <file>', 'Detached signature from `bundle sign` (auto-detects a sibling .sig)')
243
266
  .option('-w, --wait', 'Wait for processing to finish (exit non-zero if it fails)', false)
267
+ .option('--ota-tag <prefix>', 'Publish as <version>-<prefix><N> (e.g. nu → 1.16.1-nu2); N restarts at 1 when the version changes')
268
+ .option('--native-version <version>', 'Native versionName the devices run (default: android/app/build.gradle)')
269
+ .option('--dry-run', 'Print the version, channel and minimum native version, upload nothing', false)
244
270
  ).action(async (target, options) => {
245
271
  const { deploy } = await import('./commands/remote.js');
246
272
  await deploy(target, options);
247
273
  });
248
274
 
275
+ // ota-tag — print the next OTA tag only (for scripts that sign the bundle locally)
276
+ remoteAuthOptions(
277
+ program
278
+ .command('ota-tag')
279
+ .description('Print the next OTA tag for this app and channel, e.g. 1.16.1-nu3')
280
+ .requiredOption('-a, --app <appIdOrNumericId>', 'App (app_id like com.example.app, or numeric id)')
281
+ .option('-v, --version <version>', 'Base version (defaults to ./package.json version)')
282
+ .option('-c, --channel <channel>', 'Release channel', 'production')
283
+ .option('--ota-tag <prefix>', 'Tag prefix', 'nu')
284
+ .option('--native-version <version>', 'Native versionName the devices run (default: android/app/build.gradle)')
285
+ ).action(async (options) => {
286
+ const { otaTagCommand } = await import('./commands/ota-tag.js');
287
+ try {
288
+ await otaTagCommand(options);
289
+ } catch (error) {
290
+ console.error(chalk.red(`Error: ${error.message}`));
291
+ process.exit(1);
292
+ }
293
+ });
294
+
249
295
  // apps
250
296
  const appsCmd = program
251
297
  .command('apps')
@@ -1,4 +1,5 @@
1
1
  import { Logger } from '../core/logger';
2
+ import { compareVersions as compareVersionOrder } from '../core/version-order';
2
3
  export class AppUpdateChecker {
3
4
  constructor(config) {
4
5
  this.cachedAppInfo = null;
@@ -63,17 +64,7 @@ export class AppUpdateChecker {
63
64
  }
64
65
  }
65
66
  compareVersions(version1, version2) {
66
- const v1Parts = version1.split('.').map(Number);
67
- const v2Parts = version2.split('.').map(Number);
68
- for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
69
- const v1Part = v1Parts[i] || 0;
70
- const v2Part = v2Parts[i] || 0;
71
- if (v1Part > v2Part)
72
- return 1;
73
- if (v1Part < v2Part)
74
- return -1;
75
- }
76
- return 0;
67
+ return compareVersionOrder(version1, version2);
77
68
  }
78
69
  isUpdateRequired(currentVersion, availableVersion, minimumVersion) {
79
70
  // Check if current version is less than available
@@ -2,6 +2,7 @@ import { BackgroundUpdateType, UpdateErrorCode } from '../definitions';
2
2
  import { Logger } from '../core/logger';
3
3
  import { ConfigManager } from '../core/config';
4
4
  import { checkForUpdate } from '../core/update-check';
5
+ import { compareVersions as compareVersionOrder } from '../core/version-order';
5
6
  export class BackgroundScheduler {
6
7
  constructor() {
7
8
  this.config = null;
@@ -317,16 +318,6 @@ export class BackgroundScheduler {
317
318
  return true;
318
319
  }
319
320
  compareVersions(version1, version2) {
320
- const v1Parts = version1.split('.').map(Number);
321
- const v2Parts = version2.split('.').map(Number);
322
- for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
323
- const v1Part = v1Parts[i] || 0;
324
- const v2Part = v2Parts[i] || 0;
325
- if (v1Part > v2Part)
326
- return 1;
327
- if (v1Part < v2Part)
328
- return -1;
329
- }
330
- return 0;
321
+ return compareVersionOrder(version1, version2);
331
322
  }
332
323
  }