@akanjs/devkit 3.0.0-beta.20 → 3.0.0-beta.21
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.ko.md +2 -2
- package/README.md +2 -2
- package/akanConfig/akanConfig.test.ts +58 -38
- package/akanConfig/akanConfig.ts +88 -48
- package/akanConfig/types.ts +3 -3
- package/akanContext.ts +5 -2
- package/artifact/implicitRootLayout.test.ts +23 -0
- package/artifact/implicitRootLayout.ts +24 -0
- package/biome.base.json +26 -0
- package/commandDecorators/command.ts +1 -1
- package/executors.ts +1 -12
- package/incrementalBuilder/buildBatch.proc.ts +7 -1
- package/index.ts +0 -2
- package/lint/__fixtures__/no-document-cookie/bad.tsx +4 -0
- package/lint/__fixtures__/no-document-cookie/good.tsx +7 -0
- package/lint/__fixtures__/no-web-only-api-outside-webkit/bad.tsx +7 -0
- package/lint/__fixtures__/no-web-only-api-outside-webkit/good.tsx +11 -0
- package/lint/__fixtures__/no-web-storage/bad.tsx +6 -0
- package/lint/__fixtures__/no-web-storage/good.tsx +7 -0
- package/lint/no-document-cookie.grit +29 -0
- package/lint/no-web-only-api-outside-webkit.grit +44 -0
- package/lint/no-web-storage.grit +30 -0
- package/mobile/index.ts +6 -0
- package/mobile/mobileTarget.ts +2 -0
- package/mobile/nativeApi.test.ts +30 -0
- package/mobile/nativeApi.ts +40 -0
- package/mobile/nativeApp.test.ts +85 -0
- package/mobile/nativeApp.ts +210 -0
- package/mobile/nativeConfig.test.ts +199 -0
- package/mobile/nativeConfig.ts +184 -0
- package/mobile/nativeWebDir.test.ts +80 -0
- package/mobile/nativeWebDir.ts +62 -0
- package/mobile/placeholderAppId.test.ts +13 -0
- package/mobile/placeholderAppId.ts +16 -0
- package/mobile/usageDescriptions.test.ts +27 -0
- package/mobile/usageDescriptions.ts +24 -0
- package/package.json +2 -7
- package/qualityScanner.ts +4 -2
- package/scanInfo.ts +5 -10
- package/workspaceLayout.test.ts +13 -3
- package/workspaceLayout.ts +16 -4
- package/applicationReleasePackager.ts +0 -189
- package/capacitorApp.test.ts +0 -388
- package/capacitorApp.ts +0 -1520
package/capacitorApp.ts
DELETED
|
@@ -1,1520 +0,0 @@
|
|
|
1
|
-
import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import os from "node:os";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import type { CapacitorConfig } from "@capacitor/cli";
|
|
5
|
-
import { select } from "@inquirer/prompts";
|
|
6
|
-
import { MobileProject } from "@trapezedev/project";
|
|
7
|
-
import type { AndroidProject } from "@trapezedev/project/dist/android/project";
|
|
8
|
-
import type { IosProject } from "@trapezedev/project/dist/ios/project";
|
|
9
|
-
import type { AkanNativeContext, AkanPlugin } from "akanjs";
|
|
10
|
-
import { capitalize, isRecord } from "akanjs/common";
|
|
11
|
-
import type { AkanMobileTargetConfig, MobilePermission } from "./akanConfig";
|
|
12
|
-
import { type AppExecutor, CommandExecutionError } from "./executors";
|
|
13
|
-
import { FileEditor } from "./fileEditor";
|
|
14
|
-
import { resolveMobilePath, targetHtmlFilename } from "./mobile";
|
|
15
|
-
|
|
16
|
-
interface RunConfig {
|
|
17
|
-
operation: "local" | "release";
|
|
18
|
-
env: "local" | "debug" | "develop" | "main";
|
|
19
|
-
regenerate?: boolean;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
interface RunIosConfig extends RunConfig {
|
|
23
|
-
noAllowProvisioningUpdates?: boolean;
|
|
24
|
-
iosDeviceId?: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
interface PrepareConfig extends RunConfig {
|
|
28
|
-
iosRunTargetKind?: IosRunTargetKind;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
type MobileCommandEnv = Record<string, string | undefined>;
|
|
32
|
-
|
|
33
|
-
export type IosRunTargetKind = "device" | "simulator";
|
|
34
|
-
export interface IosRunTarget {
|
|
35
|
-
id: string;
|
|
36
|
-
name: string;
|
|
37
|
-
kind: IosRunTargetKind;
|
|
38
|
-
state?: string;
|
|
39
|
-
/** Display runtime for simulators, e.g. "iOS 18.2". Undefined for physical devices. */
|
|
40
|
-
runtime?: string;
|
|
41
|
-
devicectlId?: string;
|
|
42
|
-
xcodebuildId?: string;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface IosNativeRunCommand {
|
|
46
|
-
xcodebuildArgs: string[];
|
|
47
|
-
appPath: string;
|
|
48
|
-
configuration: "Debug" | "Release";
|
|
49
|
-
derivedDataPath: string;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export type IosRunFailureKind =
|
|
53
|
-
| "apple-account"
|
|
54
|
-
| "bundle-identifier"
|
|
55
|
-
| "compiler-toolchain"
|
|
56
|
-
| "team-permission"
|
|
57
|
-
| "license-agreement"
|
|
58
|
-
| "certificate"
|
|
59
|
-
| "provisioning-profile"
|
|
60
|
-
| "device-registration"
|
|
61
|
-
| "device-state"
|
|
62
|
-
| "devicectl-unavailable"
|
|
63
|
-
| "simulator-runtime"
|
|
64
|
-
| "unknown";
|
|
65
|
-
|
|
66
|
-
// iOS 18+ SDKs split SwiftUI into a SwiftUICore dylib older runtimes lack, so such a build dyld-crashes below iOS 18.
|
|
67
|
-
export const SWIFTUICORE_MIN_IOS_MAJOR = 18;
|
|
68
|
-
|
|
69
|
-
export interface IosRunFailureClassification {
|
|
70
|
-
kind: IosRunFailureKind;
|
|
71
|
-
title: string;
|
|
72
|
-
detail: string;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const iosNativeBlockedEnvKeys = new Set(
|
|
76
|
-
"AR AS CC CFLAGS CONDA_BUILD_SYSROOT CONDA_PREFIX CPP CPPFLAGS CPATH CXX CXXFLAGS LD LDFLAGS LIBRARY_PATH"
|
|
77
|
-
.split(" ")
|
|
78
|
-
.concat("MACOSX_DEPLOYMENT_TARGET NM OBJC OBJCXX PREFIX RANLIB SDKROOT STRIP".split(" ")),
|
|
79
|
-
);
|
|
80
|
-
|
|
81
|
-
export const rootCapacitorConfigFilenames = [
|
|
82
|
-
"capacitor.config.ts",
|
|
83
|
-
"capacitor.config.js",
|
|
84
|
-
"capacitor.config.json",
|
|
85
|
-
] as const;
|
|
86
|
-
|
|
87
|
-
export const rootCapacitorConfigPaths = (appRoot: string) =>
|
|
88
|
-
rootCapacitorConfigFilenames.map((file) => path.join(appRoot, file));
|
|
89
|
-
|
|
90
|
-
export async function clearRootCapacitorConfigs(appRoot: string) {
|
|
91
|
-
await Promise.all(rootCapacitorConfigPaths(appRoot).map((file) => rm(file, { force: true })));
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export async function writeRootCapacitorConfig(appRoot: string, content: string) {
|
|
95
|
-
await clearRootCapacitorConfigs(appRoot);
|
|
96
|
-
await Bun.write(path.join(appRoot, "capacitor.config.json"), content);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
interface MaterializeCapacitorConfigOptions {
|
|
100
|
-
operation: RunConfig["operation"];
|
|
101
|
-
localServerUrl?: string;
|
|
102
|
-
localIp?: string;
|
|
103
|
-
}
|
|
104
|
-
type MobilePlatform = "ios" | "android";
|
|
105
|
-
|
|
106
|
-
type SpawnMobileOptions = Parameters<AppExecutor["spawn"]>[2] & {
|
|
107
|
-
platform?: MobilePlatform;
|
|
108
|
-
iosRunTargetKind?: IosRunTargetKind;
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
export interface LocalDevHostResolution {
|
|
112
|
-
host: string;
|
|
113
|
-
source: "override" | "detected" | "loopback" | "platform";
|
|
114
|
-
candidates: { name: string; address: string }[];
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// Almost never a LAN NIC a device can reach: bridges, tunnels, AirDrop/awdl, VM and container adapters.
|
|
118
|
-
const virtualInterfacePrefixes = "bridge utun llw awdl ap vmnet vnic tap tun docker veth vboxnet gif stf".split(" ");
|
|
119
|
-
const physicalInterfacePrefixes = ["en", "eth", "wlan", "wlp", "enp", "eno", "wlo"];
|
|
120
|
-
|
|
121
|
-
const isPrivateLanIpv4 = (address: string): boolean => {
|
|
122
|
-
if (address.startsWith("10.") || address.startsWith("192.168.")) return true;
|
|
123
|
-
const secondOctet = Number(address.match(/^172\.(\d+)\./)?.[1]);
|
|
124
|
-
return Number.isFinite(secondOctet) && secondOctet >= 16 && secondOctet <= 31;
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
// Link-local (169.254) is never routable.
|
|
128
|
-
const scoreDevHostCandidate = (name: string, address: string): number => {
|
|
129
|
-
const lowerName = name.toLowerCase();
|
|
130
|
-
let score = 0;
|
|
131
|
-
if (address.startsWith("169.254.")) score -= 1000;
|
|
132
|
-
if (virtualInterfacePrefixes.some((prefix) => lowerName.startsWith(prefix))) score -= 100;
|
|
133
|
-
else if (physicalInterfacePrefixes.some((prefix) => lowerName.startsWith(prefix))) score += 100;
|
|
134
|
-
if (isPrivateLanIpv4(address)) score += 10;
|
|
135
|
-
return score;
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
// Ranked, not first-found: an inactive Thunderbolt bridge is often enumerated before the real LAN NIC.
|
|
139
|
-
export const selectLocalDevHost = (
|
|
140
|
-
interfaces: NodeJS.Dict<os.NetworkInterfaceInfo[]>,
|
|
141
|
-
{ override }: { override?: string } = {},
|
|
142
|
-
): LocalDevHostResolution => {
|
|
143
|
-
const candidates: { name: string; address: string }[] = [];
|
|
144
|
-
for (const [name, aliases] of Object.entries(interfaces)) {
|
|
145
|
-
for (const alias of aliases ?? []) {
|
|
146
|
-
if (alias.family !== "IPv4" || alias.internal) continue;
|
|
147
|
-
candidates.push({ name, address: alias.address });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
const trimmedOverride = override?.trim();
|
|
151
|
-
if (trimmedOverride) return { host: trimmedOverride, source: "override", candidates };
|
|
152
|
-
const [best] = [...candidates].sort(
|
|
153
|
-
(a, b) =>
|
|
154
|
-
scoreDevHostCandidate(b.name, b.address) - scoreDevHostCandidate(a.name, a.address) ||
|
|
155
|
-
a.name.localeCompare(b.name) ||
|
|
156
|
-
a.address.localeCompare(b.address),
|
|
157
|
-
);
|
|
158
|
-
return best
|
|
159
|
-
? { host: best.address, source: "detected", candidates }
|
|
160
|
-
: { host: "127.0.0.1", source: "loopback", candidates };
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
const asString = (value: unknown) => (typeof value === "string" ? value : undefined);
|
|
164
|
-
|
|
165
|
-
const firstString = (...values: unknown[]) => values.find((value): value is string => typeof value === "string");
|
|
166
|
-
|
|
167
|
-
const scoreIosDeviceTarget = (target: IosRunTarget) => {
|
|
168
|
-
const state = target.state?.toLowerCase() ?? "";
|
|
169
|
-
return (state.includes("available") ? 4 : 0) + (state.includes("wired") ? 2 : 0) + (state.includes("paired") ? 1 : 0);
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
const dedupeIosRunTargets = (targets: IosRunTarget[]) => {
|
|
173
|
-
const byKey = new Map<string, IosRunTarget>();
|
|
174
|
-
const runnableTargets = targets.filter((target) => !target.state?.toLowerCase().includes("unavailable"));
|
|
175
|
-
for (const target of runnableTargets) {
|
|
176
|
-
const key = target.xcodebuildId ?? target.id;
|
|
177
|
-
const current = byKey.get(key);
|
|
178
|
-
if (!current || scoreIosDeviceTarget(target) > scoreIosDeviceTarget(current)) byKey.set(key, target);
|
|
179
|
-
}
|
|
180
|
-
return [...byKey.values()];
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
// simctl spells a runtime as a JSON key ("com.apple.CoreSimulator.SimRuntime.iOS-18-2") or as "iOS 18.2".
|
|
184
|
-
const formatSimctlRuntime = (key?: string): string | undefined => {
|
|
185
|
-
if (!key) return undefined;
|
|
186
|
-
if (/^(iOS|watchOS|tvOS|visionOS)\s+[\d.]+$/i.test(key)) return key;
|
|
187
|
-
const match = key.match(/(iOS|watchOS|tvOS|visionOS)-(\d+)(?:-(\d+))?/i);
|
|
188
|
-
if (!match) return undefined;
|
|
189
|
-
return `${match[1]} ${match[2]}${match[3] ? `.${match[3]}` : ""}`;
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
export const parseIosRuntimeMajor = (runtime?: string): number | undefined => {
|
|
193
|
-
const major = runtime?.match(/\d+/)?.[0];
|
|
194
|
-
return major === undefined ? undefined : Number.parseInt(major, 10);
|
|
195
|
-
};
|
|
196
|
-
|
|
197
|
-
const iosRunTargetRank = (target: IosRunTarget): number => {
|
|
198
|
-
const state = target.state?.toLowerCase() ?? "";
|
|
199
|
-
const ready = state.includes("booted") || state.includes("connected") || state.includes("available") ? 1000 : 0;
|
|
200
|
-
const device = target.kind === "device" ? 500 : 0;
|
|
201
|
-
return ready + device + (parseIosRuntimeMajor(target.runtime) ?? 0);
|
|
202
|
-
};
|
|
203
|
-
|
|
204
|
-
export const sortIosRunTargets = (targets: IosRunTarget[]): IosRunTarget[] =>
|
|
205
|
-
[...targets].sort((a, b) => iosRunTargetRank(b) - iosRunTargetRank(a) || a.name.localeCompare(b.name));
|
|
206
|
-
|
|
207
|
-
function walkRecords(value: unknown, visit: (record: Record<string, unknown>) => void) {
|
|
208
|
-
if (Array.isArray(value)) {
|
|
209
|
-
for (const item of value) walkRecords(item, visit);
|
|
210
|
-
return;
|
|
211
|
-
}
|
|
212
|
-
if (!isRecord(value)) return;
|
|
213
|
-
visit(value);
|
|
214
|
-
for (const item of Object.values(value)) walkRecords(item, visit);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export function parseDevicectlDevices(output: string): IosRunTarget[] {
|
|
218
|
-
try {
|
|
219
|
-
const json = JSON.parse(output) as unknown;
|
|
220
|
-
const targets = new Map<string, IosRunTarget>();
|
|
221
|
-
walkRecords(json, (record) => {
|
|
222
|
-
const deviceProperties = isRecord(record.deviceProperties) ? record.deviceProperties : {};
|
|
223
|
-
const hardwareProperties = isRecord(record.hardwareProperties) ? record.hardwareProperties : {};
|
|
224
|
-
const connectionProperties = isRecord(record.connectionProperties) ? record.connectionProperties : {};
|
|
225
|
-
const devicectlId = firstString(record.identifier, record.deviceIdentifier);
|
|
226
|
-
const potentialHostnames = Array.isArray(connectionProperties.potentialHostnames)
|
|
227
|
-
? connectionProperties.potentialHostnames.filter((value): value is string => typeof value === "string")
|
|
228
|
-
: [];
|
|
229
|
-
const hostnameUdid = potentialHostnames
|
|
230
|
-
.map((hostname) => hostname.match(/([0-9A-Fa-f]{8}-[0-9A-Fa-f]{16})\.coredevice\.local/)?.[1])
|
|
231
|
-
.find((value): value is string => Boolean(value));
|
|
232
|
-
const udid = firstString(hardwareProperties.udid, hostnameUdid, record.udid, record.UDID);
|
|
233
|
-
const id = udid ?? devicectlId;
|
|
234
|
-
const name = firstString(deviceProperties.name, record.name, record.deviceName, record.displayName);
|
|
235
|
-
if (!id || !name) return;
|
|
236
|
-
const state = [
|
|
237
|
-
firstString(record.state, record.connectionState, record.availability, connectionProperties.tunnelState),
|
|
238
|
-
firstString(connectionProperties.transportType),
|
|
239
|
-
firstString(connectionProperties.pairingState),
|
|
240
|
-
]
|
|
241
|
-
.filter(Boolean)
|
|
242
|
-
.join(" ");
|
|
243
|
-
targets.set(id, { id, name, kind: "device", state, devicectlId, xcodebuildId: udid ?? id });
|
|
244
|
-
});
|
|
245
|
-
return dedupeIosRunTargets([...targets.values()]);
|
|
246
|
-
} catch {
|
|
247
|
-
const targets: IosRunTarget[] = [];
|
|
248
|
-
for (const line of output.split(/\r?\n/)) {
|
|
249
|
-
const id = line.match(/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{16}|[0-9A-Fa-f-]{25,}/)?.[0];
|
|
250
|
-
if (!id) continue;
|
|
251
|
-
const name = line.replace(id, "").replace(/[()]/g, " ").trim().replace(/\s+/g, " ") || id;
|
|
252
|
-
targets.push({ id, name, kind: "device" });
|
|
253
|
-
}
|
|
254
|
-
return dedupeIosRunTargets(targets);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
export function parseSimctlDevices(output: string): IosRunTarget[] {
|
|
259
|
-
try {
|
|
260
|
-
const json = JSON.parse(output) as { devices?: Record<string, unknown[]> };
|
|
261
|
-
const devices = json.devices ?? {};
|
|
262
|
-
return Object.entries(devices).flatMap(([runtimeKey, list]) => {
|
|
263
|
-
const runtime = formatSimctlRuntime(runtimeKey);
|
|
264
|
-
return (Array.isArray(list) ? list : []).filter(isRecord).flatMap((device) => {
|
|
265
|
-
const id = firstString(device.udid, device.UDID, device.identifier);
|
|
266
|
-
const name = firstString(device.name, device.displayName);
|
|
267
|
-
const isAvailable = device.isAvailable !== false && device.availabilityError === undefined;
|
|
268
|
-
if (!id || !name || !isAvailable) return [];
|
|
269
|
-
return [
|
|
270
|
-
{
|
|
271
|
-
id,
|
|
272
|
-
name,
|
|
273
|
-
kind: "simulator" as const,
|
|
274
|
-
state: asString(device.state),
|
|
275
|
-
runtime: runtime ?? formatSimctlRuntime(asString(device.runtimeIdentifier)),
|
|
276
|
-
},
|
|
277
|
-
];
|
|
278
|
-
});
|
|
279
|
-
});
|
|
280
|
-
} catch {
|
|
281
|
-
const targets: IosRunTarget[] = [];
|
|
282
|
-
let runtime: string | undefined;
|
|
283
|
-
for (const line of output.split(/\r?\n/)) {
|
|
284
|
-
const header = line.match(/^--\s*(.+?)\s*--\s*$/);
|
|
285
|
-
if (header) {
|
|
286
|
-
runtime = formatSimctlRuntime(header[1]);
|
|
287
|
-
continue;
|
|
288
|
-
}
|
|
289
|
-
const match = line.match(/^\s*(.+?)\s+\(([0-9A-Fa-f-]{20,})\)\s+\(([^)]+)\)/);
|
|
290
|
-
if (!match) continue;
|
|
291
|
-
targets.push({ id: match[2], name: match[1].trim(), kind: "simulator", state: match[3], runtime });
|
|
292
|
-
}
|
|
293
|
-
return targets;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
export function buildIosNativeRunCommand({
|
|
298
|
-
appRoot,
|
|
299
|
-
device,
|
|
300
|
-
scheme = "App",
|
|
301
|
-
configuration = "Debug",
|
|
302
|
-
}: {
|
|
303
|
-
appRoot: string;
|
|
304
|
-
device: IosRunTarget;
|
|
305
|
-
scheme?: string;
|
|
306
|
-
configuration?: "Debug" | "Release";
|
|
307
|
-
}): IosNativeRunCommand {
|
|
308
|
-
const derivedDataPath = path.join(appRoot, "ios/DerivedData", device.id);
|
|
309
|
-
const productPlatform = device.kind === "device" ? "iphoneos" : "iphonesimulator";
|
|
310
|
-
const destination =
|
|
311
|
-
device.kind === "device" ? `id=${device.xcodebuildId ?? device.id}` : `platform=iOS Simulator,id=${device.id}`;
|
|
312
|
-
return {
|
|
313
|
-
configuration,
|
|
314
|
-
derivedDataPath,
|
|
315
|
-
appPath: path.join(derivedDataPath, "Build/Products", `${configuration}-${productPlatform}`, "App.app"),
|
|
316
|
-
xcodebuildArgs: [
|
|
317
|
-
"-project",
|
|
318
|
-
"App.xcodeproj",
|
|
319
|
-
"-scheme",
|
|
320
|
-
scheme,
|
|
321
|
-
"-configuration",
|
|
322
|
-
configuration,
|
|
323
|
-
"-destination",
|
|
324
|
-
destination,
|
|
325
|
-
"-derivedDataPath",
|
|
326
|
-
derivedDataPath,
|
|
327
|
-
"build",
|
|
328
|
-
],
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
export function classifyIosRunFailure(log: string): IosRunFailureClassification {
|
|
333
|
-
const lower = log.toLowerCase();
|
|
334
|
-
if (
|
|
335
|
-
lower.includes("swiftuicore") &&
|
|
336
|
-
(lower.includes("library not loaded") || lower.includes("library missing") || lower.includes("dyld"))
|
|
337
|
-
) {
|
|
338
|
-
return {
|
|
339
|
-
kind: "simulator-runtime",
|
|
340
|
-
title: "App crashed loading SwiftUICore — the iOS runtime is too old.",
|
|
341
|
-
detail: `The build links SwiftUICore, which only exists on iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+. Rerun on an iOS ${SWIFTUICORE_MIN_IOS_MAJOR} or newer simulator/device (pass --device to pick one non-interactively).`,
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
if (lower.includes("unknown argument: '-index-store-path'") || lower.includes("compiler was not recognized")) {
|
|
345
|
-
return {
|
|
346
|
-
kind: "compiler-toolchain",
|
|
347
|
-
title: "iOS build is using a non-Xcode compiler from the shell environment.",
|
|
348
|
-
detail:
|
|
349
|
-
"Akan removes common Conda/compiler environment variables for native iOS runs. If this persists, run outside the activated toolchain environment.",
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
if (lower.includes("developer mode") && lower.includes("disabled")) {
|
|
353
|
-
return {
|
|
354
|
-
kind: "device-state",
|
|
355
|
-
title: "iOS device Developer Mode is disabled.",
|
|
356
|
-
detail: "Enable Developer Mode on the iPhone, then reconnect and run the command again.",
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
if (lower.includes("untrusted") || lower.includes("not paired") || lower.includes("locked")) {
|
|
360
|
-
return {
|
|
361
|
-
kind: "device-state",
|
|
362
|
-
title: "iOS device is not ready for installation.",
|
|
363
|
-
detail: "Unlock the iPhone, trust this computer, and make sure the device is paired before retrying.",
|
|
364
|
-
};
|
|
365
|
-
}
|
|
366
|
-
if (
|
|
367
|
-
lower.includes('unable to find utility "devicectl"') ||
|
|
368
|
-
(lower.includes("devicectl") && lower.includes("not found"))
|
|
369
|
-
) {
|
|
370
|
-
return {
|
|
371
|
-
kind: "devicectl-unavailable",
|
|
372
|
-
title: "Xcode devicectl is not available.",
|
|
373
|
-
detail: "Install a recent Xcode version and verify xcode-select points to that Xcode installation.",
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
if (
|
|
377
|
-
lower.includes("there are no accounts registered with xcode") ||
|
|
378
|
-
lower.includes("unable to log in with account")
|
|
379
|
-
) {
|
|
380
|
-
return {
|
|
381
|
-
kind: "apple-account",
|
|
382
|
-
title: "Xcode Apple ID is not available.",
|
|
383
|
-
detail: "Sign in to an Apple ID in Xcode Settings > Accounts, then retry the Akan iOS command.",
|
|
384
|
-
};
|
|
385
|
-
}
|
|
386
|
-
if (
|
|
387
|
-
lower.includes("failed registering bundle identifier") ||
|
|
388
|
-
lower.includes("cannot be registered to your development team")
|
|
389
|
-
) {
|
|
390
|
-
return {
|
|
391
|
-
kind: "bundle-identifier",
|
|
392
|
-
title: "iOS bundle identifier is not available for this Apple Developer Team.",
|
|
393
|
-
detail:
|
|
394
|
-
"Change mobile appId to a globally unique bundle identifier that your team can register, then rerun the iOS command.",
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
if (lower.includes("does not have permission") || (lower.includes("your account") && lower.includes("permission"))) {
|
|
398
|
-
return {
|
|
399
|
-
kind: "team-permission",
|
|
400
|
-
title: "Apple Developer Team permission is missing.",
|
|
401
|
-
detail: "Check that the signed-in Apple ID has permission for the selected DEVELOPMENT_TEAM.",
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
if (lower.includes("license agreement") || lower.includes("program license agreement")) {
|
|
405
|
-
return {
|
|
406
|
-
kind: "license-agreement",
|
|
407
|
-
title: "Apple Developer Program license agreement is not accepted.",
|
|
408
|
-
detail: "Accept the latest Apple Developer Program license agreement, then retry.",
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
if (lower.includes("no signing certificate") || lower.includes("doesn't include signing certificate")) {
|
|
412
|
-
return {
|
|
413
|
-
kind: "certificate",
|
|
414
|
-
title: "iOS development signing certificate is missing.",
|
|
415
|
-
detail: "Create or download an Apple Development certificate for the selected team.",
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
if (lower.includes("device") && lower.includes("not") && lower.includes("registered")) {
|
|
419
|
-
return {
|
|
420
|
-
kind: "device-registration",
|
|
421
|
-
title: "iPhone is not registered in the provisioning profile.",
|
|
422
|
-
detail: "Allow provisioning updates with a team that can register this device, or register the device manually.",
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
if (lower.includes("no profiles for") || lower.includes("requires a provisioning profile")) {
|
|
426
|
-
return {
|
|
427
|
-
kind: "provisioning-profile",
|
|
428
|
-
title: "Matching iOS provisioning profile was not found.",
|
|
429
|
-
detail:
|
|
430
|
-
"Akan can request Xcode provisioning updates for physical devices, but the Apple account and team must be valid.",
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
return {
|
|
434
|
-
kind: "unknown",
|
|
435
|
-
title: "iOS native run failed.",
|
|
436
|
-
detail:
|
|
437
|
-
"Review the xcodebuild/devicectl output above. You can retry with --no-allow-provisioning-updates to use the conservative path.",
|
|
438
|
-
};
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
export function formatIosRunFailureMessage(input: {
|
|
442
|
-
classification: IosRunFailureClassification;
|
|
443
|
-
appId: string;
|
|
444
|
-
targetName: string;
|
|
445
|
-
teamId?: string;
|
|
446
|
-
}) {
|
|
447
|
-
return [
|
|
448
|
-
input.classification.title,
|
|
449
|
-
input.classification.detail,
|
|
450
|
-
`Mobile target: ${input.targetName}`,
|
|
451
|
-
`Bundle ID: ${input.appId}`,
|
|
452
|
-
input.teamId ? `Development Team: ${input.teamId}` : null,
|
|
453
|
-
"Capacitor is still used for native project generation and sync; Akan only runs the native build/install step directly.",
|
|
454
|
-
]
|
|
455
|
-
.filter((line): line is string => Boolean(line))
|
|
456
|
-
.join("\n");
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
export function sanitizeIosNativeRunEnv(env: MobileCommandEnv): MobileCommandEnv {
|
|
460
|
-
return Object.fromEntries(Object.entries(env).filter(([key]) => !iosNativeBlockedEnvKeys.has(key)));
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
// Placeholder bundle IDs are already claimed on Apple's portal, so device signing fails with "cannot be registered
|
|
464
|
-
// to your development team".
|
|
465
|
-
export const PLACEHOLDER_APP_IDS = [
|
|
466
|
-
"com.myapp.app",
|
|
467
|
-
"com.myorg.myapp",
|
|
468
|
-
"com.example.app",
|
|
469
|
-
"com.example.myapp",
|
|
470
|
-
] as const;
|
|
471
|
-
const placeholderAppIdSegment = /^(example|examples|myorg|myapp|mycompany|myorganization|changeme|todo|sample|test)$/;
|
|
472
|
-
|
|
473
|
-
export const isPlaceholderAppId = (appId: string | null | undefined): boolean => {
|
|
474
|
-
const normalized = appId?.trim().toLowerCase() ?? "";
|
|
475
|
-
if (!normalized) return true;
|
|
476
|
-
if ((PLACEHOLDER_APP_IDS as readonly string[]).includes(normalized)) return true;
|
|
477
|
-
return normalized.split(".").some((segment) => placeholderAppIdSegment.test(segment));
|
|
478
|
-
};
|
|
479
|
-
|
|
480
|
-
const androidReleaseSigningKeys = [
|
|
481
|
-
"MYAPP_RELEASE_STORE_FILE",
|
|
482
|
-
"MYAPP_RELEASE_STORE_PASSWORD",
|
|
483
|
-
"MYAPP_RELEASE_KEY_ALIAS",
|
|
484
|
-
"MYAPP_RELEASE_KEY_PASSWORD",
|
|
485
|
-
] as const;
|
|
486
|
-
|
|
487
|
-
export function getMissingAndroidReleaseSigningKeys({
|
|
488
|
-
env = process.env,
|
|
489
|
-
gradleProperties = "",
|
|
490
|
-
}: {
|
|
491
|
-
env?: NodeJS.ProcessEnv;
|
|
492
|
-
gradleProperties?: string;
|
|
493
|
-
} = {}) {
|
|
494
|
-
return androidReleaseSigningKeys.filter((key) => {
|
|
495
|
-
const gradleEnvKey = `ORG_GRADLE_PROJECT_${key}`;
|
|
496
|
-
return (
|
|
497
|
-
env[key] === undefined &&
|
|
498
|
-
env[gradleEnvKey] === undefined &&
|
|
499
|
-
!new RegExp(`^\\s*${key}\\s*=`, "m").test(gradleProperties)
|
|
500
|
-
);
|
|
501
|
-
});
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
export function formatAndroidReleaseSigningError(missingKeys: readonly string[]) {
|
|
505
|
-
return [
|
|
506
|
-
"Android release signing configuration is incomplete.",
|
|
507
|
-
`Missing: ${missingKeys.join(", ")}`,
|
|
508
|
-
"Set these values in android/gradle.properties or ORG_GRADLE_PROJECT_* environment variables before building a release artifact.",
|
|
509
|
-
].join("\n");
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
export function getAdbDeviceStateIssues(output: string) {
|
|
513
|
-
return output
|
|
514
|
-
.split(/\r?\n/)
|
|
515
|
-
.map((line) => line.trim().split(/\s+/))
|
|
516
|
-
.filter(([id, state]) => id && state && id !== "List")
|
|
517
|
-
.flatMap(([id, state]) => {
|
|
518
|
-
if (state === "unauthorized")
|
|
519
|
-
return [`Android device ${id} is unauthorized. Confirm USB debugging authorization on the device.`];
|
|
520
|
-
if (state === "offline") return [`Android device ${id} is offline. Reconnect the device or restart adb.`];
|
|
521
|
-
return [];
|
|
522
|
-
});
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
export function getAndroidLocalServerHost(adbDevicesOutput: string | undefined, fallbackHost: string) {
|
|
526
|
-
const onlineDeviceIds =
|
|
527
|
-
adbDevicesOutput
|
|
528
|
-
?.split(/\r?\n/)
|
|
529
|
-
.map((line) => line.trim().split(/\s+/))
|
|
530
|
-
.filter(([id, state]) => id && state === "device")
|
|
531
|
-
.map(([id]) => id) ?? [];
|
|
532
|
-
return onlineDeviceIds.length === 1 && onlineDeviceIds[0]?.startsWith("emulator-") ? "10.0.2.2" : fallbackHost;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
export const ANDROID_MIN_SDK_VERSION = 26;
|
|
536
|
-
export function raiseGradleMinSdkVersion(content: string, floor: number = ANDROID_MIN_SDK_VERSION): string | null {
|
|
537
|
-
const match = content.match(/minSdkVersion\s*=\s*(\d+)/);
|
|
538
|
-
if (!match?.[1]) return null;
|
|
539
|
-
const current = Number.parseInt(match[1], 10);
|
|
540
|
-
if (Number.isNaN(current) || current >= floor) return null;
|
|
541
|
-
return content.replace(/(minSdkVersion\s*=\s*)\d+/, `$1${floor}`);
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
//* Apple's Info.plist keys do not follow the description names (photo → NSPhotoLibrary…), so each one is spelled out.
|
|
545
|
-
const iosUsageDescriptionKeys = {
|
|
546
|
-
cameraUsageDescription: ["NSCameraUsageDescription"],
|
|
547
|
-
photoAddUsageDescription: ["NSPhotoLibraryAddUsageDescription"],
|
|
548
|
-
photoUsageDescription: ["NSPhotoLibraryUsageDescription"],
|
|
549
|
-
contactsUsageDescription: ["NSContactsUsageDescription"],
|
|
550
|
-
//? iOS 11+ reads the AlwaysAndWhenInUse key; the Always key only serves iOS 10 and below.
|
|
551
|
-
locationAlwaysUsageDescription: ["NSLocationAlwaysAndWhenInUseUsageDescription", "NSLocationAlwaysUsageDescription"],
|
|
552
|
-
locationWhenInUseUsageDescription: ["NSLocationWhenInUseUsageDescription"],
|
|
553
|
-
microphoneUsageDescription: ["NSMicrophoneUsageDescription"],
|
|
554
|
-
speechRecognitionUsageDescription: ["NSSpeechRecognitionUsageDescription"],
|
|
555
|
-
} as const;
|
|
556
|
-
|
|
557
|
-
export const toIosInfoPlistUsageDescriptions = (descriptions: { [key: string]: string }) =>
|
|
558
|
-
Object.fromEntries(
|
|
559
|
-
Object.entries(descriptions).flatMap(([key, value]) => {
|
|
560
|
-
const plistKeys: readonly string[] = Object.hasOwn(iosUsageDescriptionKeys, key)
|
|
561
|
-
? iosUsageDescriptionKeys[key as keyof typeof iosUsageDescriptionKeys]
|
|
562
|
-
: [`NS${capitalize(key)}`];
|
|
563
|
-
return plistKeys.map((plistKey) => [plistKey, value]);
|
|
564
|
-
}),
|
|
565
|
-
);
|
|
566
|
-
|
|
567
|
-
const mergeAllowNavigation = (configured: unknown, localIp: string | undefined) => {
|
|
568
|
-
const values = Array.isArray(configured)
|
|
569
|
-
? configured.filter((value): value is string => typeof value === "string")
|
|
570
|
-
: [];
|
|
571
|
-
if (localIp) values.push(localIp);
|
|
572
|
-
values.push("localhost");
|
|
573
|
-
return [...new Set(values)];
|
|
574
|
-
};
|
|
575
|
-
|
|
576
|
-
export function assertJsonSerializable(value: unknown, label = "capacitor.config", seen = new WeakSet<object>()) {
|
|
577
|
-
if (value === null) return;
|
|
578
|
-
const valueType = typeof value;
|
|
579
|
-
if (valueType === "function" || valueType === "symbol" || valueType === "bigint" || valueType === "undefined") {
|
|
580
|
-
throw new Error(`${label} must be JSON serializable. Found ${valueType}.`);
|
|
581
|
-
}
|
|
582
|
-
if (valueType === "number" && !Number.isFinite(value)) {
|
|
583
|
-
throw new Error(`${label} must be JSON serializable. Found non-finite number.`);
|
|
584
|
-
}
|
|
585
|
-
if (valueType !== "object") return;
|
|
586
|
-
const objectValue = value as object;
|
|
587
|
-
if (seen.has(objectValue)) throw new Error(`${label} must be JSON serializable. Found circular reference.`);
|
|
588
|
-
seen.add(objectValue);
|
|
589
|
-
if (Array.isArray(value)) {
|
|
590
|
-
for (const [index, item] of value.entries()) assertJsonSerializable(item, `${label}[${index}]`, seen);
|
|
591
|
-
return;
|
|
592
|
-
}
|
|
593
|
-
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
|
|
594
|
-
assertJsonSerializable(item, `${label}.${key}`, seen);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
export function materializeCapacitorConfig(
|
|
599
|
-
target: AkanMobileTargetConfig,
|
|
600
|
-
{ operation, localServerUrl, localIp }: MaterializeCapacitorConfigOptions,
|
|
601
|
-
): CapacitorConfig {
|
|
602
|
-
const {
|
|
603
|
-
name,
|
|
604
|
-
basePath: _basePath,
|
|
605
|
-
indexPath: _indexPath,
|
|
606
|
-
version: _version,
|
|
607
|
-
buildNum: _buildNum,
|
|
608
|
-
assets: _assets,
|
|
609
|
-
permissions: _permissions,
|
|
610
|
-
deepLinks: _deepLinks,
|
|
611
|
-
files: _files,
|
|
612
|
-
appId,
|
|
613
|
-
appName,
|
|
614
|
-
webDir: _webDir,
|
|
615
|
-
plugins,
|
|
616
|
-
server,
|
|
617
|
-
android,
|
|
618
|
-
ios,
|
|
619
|
-
cordova,
|
|
620
|
-
experimental,
|
|
621
|
-
...capacitorConfig
|
|
622
|
-
} = target;
|
|
623
|
-
const serverConfig = isRecord(server) ? server : undefined;
|
|
624
|
-
const cordovaConfig = isRecord(cordova) ? cordova : undefined;
|
|
625
|
-
const experimentalConfig = isRecord(experimental) ? experimental : undefined;
|
|
626
|
-
const pluginsConfig = isRecord(plugins) ? plugins : {};
|
|
627
|
-
const keyboardPluginConfig = isRecord(pluginsConfig.Keyboard) ? pluginsConfig.Keyboard : {};
|
|
628
|
-
const pushNotificationsPluginConfig = isRecord(pluginsConfig.PushNotifications)
|
|
629
|
-
? pluginsConfig.PushNotifications
|
|
630
|
-
: {};
|
|
631
|
-
const usesPushNotifications = target.permissions?.includes("push") ?? false;
|
|
632
|
-
const config: CapacitorConfig = {
|
|
633
|
-
...capacitorConfig,
|
|
634
|
-
appId,
|
|
635
|
-
appName,
|
|
636
|
-
webDir: path.posix.join(".akan", "mobile", name, "www"),
|
|
637
|
-
plugins: {
|
|
638
|
-
CapacitorCookies: { enabled: true },
|
|
639
|
-
...pluginsConfig,
|
|
640
|
-
...(usesPushNotifications || isRecord(pluginsConfig.PushNotifications)
|
|
641
|
-
? {
|
|
642
|
-
PushNotifications: {
|
|
643
|
-
...(usesPushNotifications ? { presentationOptions: ["badge", "sound", "alert"] } : {}),
|
|
644
|
-
...pushNotificationsPluginConfig,
|
|
645
|
-
},
|
|
646
|
-
}
|
|
647
|
-
: {}),
|
|
648
|
-
Keyboard: {
|
|
649
|
-
resize: "none",
|
|
650
|
-
...keyboardPluginConfig,
|
|
651
|
-
},
|
|
652
|
-
},
|
|
653
|
-
android: {
|
|
654
|
-
...(isRecord(android) ? android : {}),
|
|
655
|
-
path: "android",
|
|
656
|
-
},
|
|
657
|
-
ios: {
|
|
658
|
-
...(isRecord(ios) ? ios : {}),
|
|
659
|
-
path: "ios",
|
|
660
|
-
},
|
|
661
|
-
};
|
|
662
|
-
if (operation === "local") {
|
|
663
|
-
if (!localServerUrl) throw new Error(`Local server URL is required for mobile target '${name}'.`);
|
|
664
|
-
config.server = {
|
|
665
|
-
...serverConfig,
|
|
666
|
-
androidScheme: "http",
|
|
667
|
-
url: localServerUrl,
|
|
668
|
-
cleartext: true,
|
|
669
|
-
allowNavigation: mergeAllowNavigation(serverConfig?.allowNavigation, localIp),
|
|
670
|
-
};
|
|
671
|
-
} else if (serverConfig && Object.keys(serverConfig).length > 0) {
|
|
672
|
-
config.server = serverConfig as never;
|
|
673
|
-
}
|
|
674
|
-
if (cordovaConfig && Object.keys(cordovaConfig).length > 0) {
|
|
675
|
-
config.cordova = cordovaConfig as never;
|
|
676
|
-
}
|
|
677
|
-
if (experimentalConfig && Object.keys(experimentalConfig).length > 0) {
|
|
678
|
-
config.experimental = experimentalConfig as never;
|
|
679
|
-
}
|
|
680
|
-
assertJsonSerializable(config);
|
|
681
|
-
return config;
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
export class CapacitorApp {
|
|
685
|
-
project: MobileProject & { ios: IosProject; android: AndroidProject };
|
|
686
|
-
iosTargetName = "App";
|
|
687
|
-
readonly targetRoot: string;
|
|
688
|
-
readonly targetRootPath: string;
|
|
689
|
-
readonly targetWebRoot: string;
|
|
690
|
-
readonly targetAssetRoot: string;
|
|
691
|
-
readonly iosRootPath = "ios";
|
|
692
|
-
readonly iosProjectPath = "ios/App";
|
|
693
|
-
readonly androidRootPath = "android";
|
|
694
|
-
readonly androidAssetsPath = "android/app/src/main/assets";
|
|
695
|
-
#iosEntitlements: Record<string, string | string[]> = {};
|
|
696
|
-
constructor(
|
|
697
|
-
private readonly app: AppExecutor,
|
|
698
|
-
readonly target: AkanMobileTargetConfig,
|
|
699
|
-
) {
|
|
700
|
-
this.targetRootPath = path.posix.join(".akan", "mobile", this.target.name);
|
|
701
|
-
this.targetRoot = path.join(this.app.cwdPath, this.targetRootPath);
|
|
702
|
-
this.targetWebRoot = path.join(this.targetRoot, "www");
|
|
703
|
-
this.targetAssetRoot = path.join(this.targetRoot, "assets");
|
|
704
|
-
this.project = new MobileProject(this.app.cwdPath, {
|
|
705
|
-
android: { path: this.androidRootPath },
|
|
706
|
-
ios: { path: this.iosProjectPath },
|
|
707
|
-
}) as MobileProject & { ios: IosProject; android: AndroidProject };
|
|
708
|
-
}
|
|
709
|
-
async init({
|
|
710
|
-
platform,
|
|
711
|
-
operation = "release",
|
|
712
|
-
env = "debug",
|
|
713
|
-
regenerate = false,
|
|
714
|
-
}: { platform?: "ios" | "android" } & Partial<PrepareConfig> = {}) {
|
|
715
|
-
await mkdir(this.targetRoot, { recursive: true });
|
|
716
|
-
if (regenerate) {
|
|
717
|
-
if (!platform || platform === "ios")
|
|
718
|
-
await rm(path.join(this.app.cwdPath, this.iosRootPath), { recursive: true, force: true });
|
|
719
|
-
if (!platform || platform === "android")
|
|
720
|
-
await rm(path.join(this.app.cwdPath, this.androidRootPath), { recursive: true, force: true });
|
|
721
|
-
}
|
|
722
|
-
const project = this.project as MobileProject;
|
|
723
|
-
await this.project.load();
|
|
724
|
-
if ((!platform || platform === "android") && !project.android) {
|
|
725
|
-
await this.#spawnMobile("npx", ["cap", "add", "android"], { operation, env });
|
|
726
|
-
await this.project.load();
|
|
727
|
-
}
|
|
728
|
-
if ((!platform || platform === "ios") && !project.ios) {
|
|
729
|
-
await this.#spawnMobile("npx", ["cap", "add", "ios"], { operation, env });
|
|
730
|
-
await this.project.load();
|
|
731
|
-
}
|
|
732
|
-
return this;
|
|
733
|
-
}
|
|
734
|
-
async save() {
|
|
735
|
-
await this.project.commit();
|
|
736
|
-
}
|
|
737
|
-
async #prepareIos({ operation, env, regenerate = false, iosRunTargetKind }: PrepareConfig) {
|
|
738
|
-
await this.init({ platform: "ios", operation, env, regenerate });
|
|
739
|
-
await this.#prepareTargetAssets();
|
|
740
|
-
await this.#prepareExternalFiles("ios");
|
|
741
|
-
await this.#applyIosMetadata();
|
|
742
|
-
await this.#applyPermissions({ operation, env });
|
|
743
|
-
await this.#applyDeepLinks("ios", { operation, env });
|
|
744
|
-
await this.#flushIosEntitlements();
|
|
745
|
-
await this.project.commit();
|
|
746
|
-
await this.#setCodeSignEntitlementsInIosIfExists("App/App.entitlements");
|
|
747
|
-
await this.#generateAssets({ operation, env });
|
|
748
|
-
this.app.verbose(`syncing iOS`);
|
|
749
|
-
await this.#spawnMobile("npx", ["cap", "sync", "ios"], { operation, env }, { iosRunTargetKind });
|
|
750
|
-
this.app.verbose(`sync completed.`);
|
|
751
|
-
}
|
|
752
|
-
async buildIos({ env = "debug", regenerate = false }: { env?: RunConfig["env"]; regenerate?: boolean } = {}) {
|
|
753
|
-
await this.prepareWww();
|
|
754
|
-
await this.#prepareIos({ operation: "release", env, regenerate });
|
|
755
|
-
await this.#spawnMobile("npx", ["cap", "build", "ios"], { operation: "release", env }, { stdio: "inherit" });
|
|
756
|
-
this.app.verbose(`build completed iOS.`);
|
|
757
|
-
}
|
|
758
|
-
async syncIos() {
|
|
759
|
-
await this.#spawnMobile("npx", ["cap", "sync", "ios"], { operation: "local", env: "local" });
|
|
760
|
-
}
|
|
761
|
-
async openIos() {
|
|
762
|
-
await this.#spawnMobile("npx", ["cap", "open", "ios"], { operation: "local", env: "local" });
|
|
763
|
-
}
|
|
764
|
-
async runIos({ operation, env, regenerate = false, noAllowProvisioningUpdates = false, iosDeviceId }: RunIosConfig) {
|
|
765
|
-
if (operation === "release") await this.prepareWww();
|
|
766
|
-
const runTarget = await this.#selectIosRunTarget(iosDeviceId);
|
|
767
|
-
await this.#prepareIos({ operation, env, regenerate, iosRunTargetKind: runTarget.kind });
|
|
768
|
-
if (runTarget.kind === "simulator") {
|
|
769
|
-
await this.#spawnMobile(
|
|
770
|
-
"npx",
|
|
771
|
-
["cap", "run", "ios", "--target", runTarget.id, "--no-sync"],
|
|
772
|
-
{ operation, env },
|
|
773
|
-
{ stdio: "inherit", platform: "ios", iosRunTargetKind: runTarget.kind },
|
|
774
|
-
);
|
|
775
|
-
return;
|
|
776
|
-
}
|
|
777
|
-
await this.#runIosPhysicalDevice({ operation, env, runTarget, noAllowProvisioningUpdates });
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
async #selectIosRunTarget(deviceId?: string) {
|
|
781
|
-
const targets = sortIosRunTargets([
|
|
782
|
-
...(await this.#loadPhysicalIosDevices()),
|
|
783
|
-
...(await this.#loadIosSimulators()),
|
|
784
|
-
]);
|
|
785
|
-
if (deviceId) {
|
|
786
|
-
const needle = deviceId.toLowerCase();
|
|
787
|
-
const found =
|
|
788
|
-
targets.find((target) => target.id === deviceId) ??
|
|
789
|
-
targets.find((target) => target.name.toLowerCase() === needle) ??
|
|
790
|
-
targets.find(
|
|
791
|
-
(target) =>
|
|
792
|
-
target.name.toLowerCase().includes(needle) ||
|
|
793
|
-
target.id.toLowerCase().includes(needle) ||
|
|
794
|
-
(target.runtime?.toLowerCase().includes(needle) ?? false),
|
|
795
|
-
);
|
|
796
|
-
if (!found) {
|
|
797
|
-
const available = targets.map((t) => `${t.name}${t.runtime ? ` (${t.runtime})` : ""}`).join(", ") || "none";
|
|
798
|
-
throw new Error(`iOS run target '${deviceId}' was not found. Available: ${available}`);
|
|
799
|
-
}
|
|
800
|
-
this.#warnIfLegacySimulatorRuntime(found);
|
|
801
|
-
return found;
|
|
802
|
-
}
|
|
803
|
-
if (targets.length === 0) {
|
|
804
|
-
throw new Error("No iOS run targets found. Open Simulator or connect an iPhone, then retry.");
|
|
805
|
-
}
|
|
806
|
-
const selected = await select<IosRunTarget>({
|
|
807
|
-
message: "Select iOS run target",
|
|
808
|
-
choices: targets.map((target) => ({
|
|
809
|
-
name: `[${target.kind}] ${target.name}${target.runtime ? ` — ${target.runtime}` : ""}${target.state ? ` (${target.state})` : ""}`,
|
|
810
|
-
value: target,
|
|
811
|
-
})),
|
|
812
|
-
});
|
|
813
|
-
this.#warnIfLegacySimulatorRuntime(selected);
|
|
814
|
-
return selected;
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
#warnIfLegacySimulatorRuntime(target: IosRunTarget) {
|
|
818
|
-
if (target.kind !== "simulator") return;
|
|
819
|
-
const major = parseIosRuntimeMajor(target.runtime);
|
|
820
|
-
if (major === undefined || major >= SWIFTUICORE_MIN_IOS_MAJOR) return;
|
|
821
|
-
this.app.logger.warn(
|
|
822
|
-
`Selected simulator runs ${target.runtime ?? "an older iOS"}. Recent SDK builds link SwiftUICore and require iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+; if the app crashes at launch with a "Library not loaded: SwiftUICore" dyld error, pick an iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+ simulator instead.`,
|
|
823
|
-
);
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
async #loadPhysicalIosDevices() {
|
|
827
|
-
try {
|
|
828
|
-
return parseDevicectlDevices(await this.#spawn("xcrun", ["devicectl", "list", "devices", "--json-output", "-"]));
|
|
829
|
-
} catch (jsonError) {
|
|
830
|
-
try {
|
|
831
|
-
return parseDevicectlDevices(await this.#spawn("xcrun", ["devicectl", "list", "devices"]));
|
|
832
|
-
} catch (textError) {
|
|
833
|
-
const classification = classifyIosRunFailure(
|
|
834
|
-
`${jsonError instanceof Error ? jsonError.message : ""}\n${textError instanceof Error ? textError.message : ""}`,
|
|
835
|
-
);
|
|
836
|
-
if (classification.kind === "devicectl-unavailable") this.app.logger.warn(classification.detail);
|
|
837
|
-
return [];
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
async #loadIosSimulators() {
|
|
843
|
-
try {
|
|
844
|
-
return parseSimctlDevices(await this.#spawn("xcrun", ["simctl", "list", "devices", "available", "--json"]));
|
|
845
|
-
} catch {
|
|
846
|
-
try {
|
|
847
|
-
return parseSimctlDevices(await this.#spawn("xcrun", ["simctl", "list", "devices", "available"]));
|
|
848
|
-
} catch {
|
|
849
|
-
return [];
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
async #runIosPhysicalDevice({
|
|
855
|
-
operation,
|
|
856
|
-
env,
|
|
857
|
-
runTarget,
|
|
858
|
-
noAllowProvisioningUpdates,
|
|
859
|
-
}: Pick<RunConfig, "operation" | "env"> & {
|
|
860
|
-
runTarget: IosRunTarget;
|
|
861
|
-
noAllowProvisioningUpdates: boolean;
|
|
862
|
-
}) {
|
|
863
|
-
const mobileEnv = sanitizeIosNativeRunEnv(await this.#commandEnv(operation, env));
|
|
864
|
-
const configContent = await this.#writeCapacitorConfig(
|
|
865
|
-
{ operation, platform: "ios", iosRunTargetKind: runTarget.kind },
|
|
866
|
-
mobileEnv,
|
|
867
|
-
);
|
|
868
|
-
await writeRootCapacitorConfig(this.app.cwdPath, configContent);
|
|
869
|
-
const command = buildIosNativeRunCommand({
|
|
870
|
-
appRoot: this.app.cwdPath,
|
|
871
|
-
device: runTarget,
|
|
872
|
-
scheme: isRecord(this.target.ios) && typeof this.target.ios.scheme === "string" ? this.target.ios.scheme : "App",
|
|
873
|
-
configuration: operation === "release" ? "Release" : "Debug",
|
|
874
|
-
});
|
|
875
|
-
const xcodebuildArgs = noAllowProvisioningUpdates
|
|
876
|
-
? command.xcodebuildArgs
|
|
877
|
-
: [...command.xcodebuildArgs.slice(0, -1), "-allowProvisioningUpdates", ...command.xcodebuildArgs.slice(-1)];
|
|
878
|
-
try {
|
|
879
|
-
await this.#spawn("xcodebuild", xcodebuildArgs, {
|
|
880
|
-
cwd: path.join(this.app.cwdPath, this.iosProjectPath),
|
|
881
|
-
env: mobileEnv,
|
|
882
|
-
});
|
|
883
|
-
const devicectlId = runTarget.devicectlId ?? runTarget.id;
|
|
884
|
-
const devicectl = (verb: string[], subject: string) =>
|
|
885
|
-
this.#spawn("xcrun", ["devicectl", "device", ...verb, "--device", devicectlId, subject], { env: mobileEnv });
|
|
886
|
-
await devicectl(["install", "app"], command.appPath);
|
|
887
|
-
await devicectl(["process", "launch"], this.target.appId);
|
|
888
|
-
} catch (error) {
|
|
889
|
-
throw new Error(
|
|
890
|
-
formatIosRunFailureMessage({
|
|
891
|
-
classification: classifyIosRunFailure(this.#errorOutput(error)),
|
|
892
|
-
appId: this.target.appId,
|
|
893
|
-
targetName: this.target.name,
|
|
894
|
-
teamId: await this.#getIosDevelopmentTeam(),
|
|
895
|
-
}),
|
|
896
|
-
);
|
|
897
|
-
} finally {
|
|
898
|
-
await clearRootCapacitorConfigs(this.app.cwdPath);
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
async #getIosDevelopmentTeam() {
|
|
903
|
-
const pbxprojPath = path.join(this.app.cwdPath, this.iosProjectPath, "App.xcodeproj/project.pbxproj");
|
|
904
|
-
if (!(await Bun.file(pbxprojPath).exists())) return undefined;
|
|
905
|
-
return (await Bun.file(pbxprojPath).text()).match(/DEVELOPMENT_TEAM = ([^;]+);/)?.[1]?.trim();
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
#errorOutput(error: unknown) {
|
|
909
|
-
if (error instanceof CommandExecutionError) return `${error.stdout}\n${error.stderr}\n${error.message}`;
|
|
910
|
-
return error instanceof Error ? error.message : String(error);
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
async #prepareAndroid({ operation, env, regenerate = false }: PrepareConfig) {
|
|
914
|
-
await this.init({ platform: "android", operation, env, regenerate });
|
|
915
|
-
await this.#prepareTargetAssets();
|
|
916
|
-
await this.#prepareExternalFiles("android");
|
|
917
|
-
await this.#applyAndroidMetadata();
|
|
918
|
-
await this.#applyAndroidMinSdkVersion();
|
|
919
|
-
await this.#applyPermissions({ operation, env });
|
|
920
|
-
await this.#applyDeepLinks("android", { operation, env });
|
|
921
|
-
await this.#disableNativeKeyboardResizeInAndroid();
|
|
922
|
-
await this.project.commit();
|
|
923
|
-
await this.#generateAssets({ operation, env });
|
|
924
|
-
await mkdir(path.join(this.app.cwdPath, this.androidAssetsPath), { recursive: true });
|
|
925
|
-
await this.#ensureAndroidDebugKeystore();
|
|
926
|
-
await this.#spawnMobile("npx", ["cap", "sync", "android"], { operation, env });
|
|
927
|
-
await this.#setDeepLinksInAndroid(this.target.deepLinks?.schemes ?? [], this.target.deepLinks?.domains ?? []);
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
async #updateAndroidBuildTypes() {
|
|
931
|
-
const appGradle = await FileEditor.create(path.join(this.app.cwdPath, this.androidRootPath, "app/build.gradle"));
|
|
932
|
-
const buildTypesBlock = `
|
|
933
|
-
debug {
|
|
934
|
-
applicationIdSuffix ".debug"
|
|
935
|
-
versionNameSuffix "-DEBUG"
|
|
936
|
-
debuggable true
|
|
937
|
-
minifyEnabled false
|
|
938
|
-
}
|
|
939
|
-
`;
|
|
940
|
-
const singinConfigBlock = `
|
|
941
|
-
signingConfigs {
|
|
942
|
-
debug {
|
|
943
|
-
storeFile file('debug.keystore')
|
|
944
|
-
storePassword 'android'
|
|
945
|
-
keyAlias 'androiddebugkey'
|
|
946
|
-
keyPassword 'android'
|
|
947
|
-
}
|
|
948
|
-
release {
|
|
949
|
-
if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
|
|
950
|
-
storeFile file(MYAPP_RELEASE_STORE_FILE)
|
|
951
|
-
storePassword MYAPP_RELEASE_STORE_PASSWORD
|
|
952
|
-
keyAlias MYAPP_RELEASE_KEY_ALIAS
|
|
953
|
-
keyPassword MYAPP_RELEASE_KEY_PASSWORD
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
`;
|
|
958
|
-
if (appGradle.find("signingConfigs {") === -1) {
|
|
959
|
-
appGradle.insertBefore("buildTypes {", singinConfigBlock);
|
|
960
|
-
}
|
|
961
|
-
if (appGradle.find(`applicationIdSuffix ".debug"`) === -1) {
|
|
962
|
-
appGradle.insertAfter("buildTypes {", buildTypesBlock);
|
|
963
|
-
}
|
|
964
|
-
await appGradle.save();
|
|
965
|
-
}
|
|
966
|
-
async buildAndroid(
|
|
967
|
-
assembleType: "apk" | "aab",
|
|
968
|
-
{ env = "debug", regenerate = false }: { env?: RunConfig["env"]; regenerate?: boolean } = {},
|
|
969
|
-
) {
|
|
970
|
-
await this.prepareWww();
|
|
971
|
-
await this.#prepareAndroid({ operation: "release", env, regenerate });
|
|
972
|
-
await this.#assertAndroidReleaseSigningConfig();
|
|
973
|
-
await this.#updateAndroidBuildTypes();
|
|
974
|
-
const gradleCommand = process.platform === "win32" ? "gradlew.bat" : "./gradlew";
|
|
975
|
-
await this.app.spawn(gradleCommand, [assembleType === "apk" ? "assembleRelease" : "bundleRelease"], {
|
|
976
|
-
stdio: "inherit",
|
|
977
|
-
cwd: path.join(this.app.cwdPath, this.androidRootPath),
|
|
978
|
-
env: await this.#commandEnv("release", env),
|
|
979
|
-
});
|
|
980
|
-
}
|
|
981
|
-
async openAndroid() {
|
|
982
|
-
await this.#spawnMobile("npx", ["cap", "open", "android"], { operation: "local", env: "local" });
|
|
983
|
-
}
|
|
984
|
-
async #disableNativeKeyboardResizeInAndroid() {
|
|
985
|
-
const manifestPath = path.join(this.app.cwdPath, this.androidRootPath, "app/src/main/AndroidManifest.xml");
|
|
986
|
-
let manifest = await readFile(manifestPath, "utf8");
|
|
987
|
-
let changed = false;
|
|
988
|
-
manifest = manifest.replace(/<activity\b[^>]*android:name="\.MainActivity"[^>]*>/, (activityTag) => {
|
|
989
|
-
if (activityTag.includes("android:windowSoftInputMode=")) {
|
|
990
|
-
const nextTag = activityTag.replace(
|
|
991
|
-
/android:windowSoftInputMode="[^"]*"/,
|
|
992
|
-
'android:windowSoftInputMode="adjustNothing"',
|
|
993
|
-
);
|
|
994
|
-
changed ||= nextTag !== activityTag;
|
|
995
|
-
return nextTag;
|
|
996
|
-
}
|
|
997
|
-
changed = true;
|
|
998
|
-
return activityTag.replace(/>$/, '\n android:windowSoftInputMode="adjustNothing">');
|
|
999
|
-
});
|
|
1000
|
-
if (changed) await writeFile(manifestPath, manifest);
|
|
1001
|
-
}
|
|
1002
|
-
async #ensureAndroidDebugKeystore() {
|
|
1003
|
-
const keystorePath = path.join(this.app.cwdPath, this.androidRootPath, "app/debug.keystore");
|
|
1004
|
-
if (await Bun.file(keystorePath).exists()) return;
|
|
1005
|
-
|
|
1006
|
-
const options =
|
|
1007
|
-
"-storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000";
|
|
1008
|
-
await this.#spawn("keytool", [
|
|
1009
|
-
"-genkeypair",
|
|
1010
|
-
"-v",
|
|
1011
|
-
"-keystore",
|
|
1012
|
-
keystorePath,
|
|
1013
|
-
...options.split(" "),
|
|
1014
|
-
"-dname",
|
|
1015
|
-
"CN=Android Debug,O=Android,C=US",
|
|
1016
|
-
]);
|
|
1017
|
-
}
|
|
1018
|
-
async syncAndroid(options: { regenerate?: boolean } = {}) {
|
|
1019
|
-
await this.prepareWww();
|
|
1020
|
-
await this.#prepareAndroid({ operation: "release", env: "debug", ...options });
|
|
1021
|
-
this.app.log(`Sync Android Completed.`);
|
|
1022
|
-
}
|
|
1023
|
-
async runAndroid({ operation, env, regenerate = false }: RunConfig) {
|
|
1024
|
-
if (operation === "release") await this.prepareWww();
|
|
1025
|
-
await this.#prepareAndroid({ operation, env, regenerate });
|
|
1026
|
-
await this.#assertAndroidAdbReady();
|
|
1027
|
-
this.app.logger.info(`Running Android in ${operation} mode on ${env} env`);
|
|
1028
|
-
await this.#spawnMobile("npx", ["cap", "run", "android"], { operation, env }, { stdio: "inherit" });
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
async #assertAndroidReleaseSigningConfig() {
|
|
1032
|
-
const gradlePropertiesPath = path.join(this.app.cwdPath, this.androidRootPath, "gradle.properties");
|
|
1033
|
-
const gradleProperties = (await Bun.file(gradlePropertiesPath).exists())
|
|
1034
|
-
? await Bun.file(gradlePropertiesPath).text()
|
|
1035
|
-
: "";
|
|
1036
|
-
const missingKeys = getMissingAndroidReleaseSigningKeys({ gradleProperties });
|
|
1037
|
-
if (missingKeys.length > 0) throw new Error(formatAndroidReleaseSigningError(missingKeys));
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
async #assertAndroidAdbReady() {
|
|
1041
|
-
try {
|
|
1042
|
-
const issues = getAdbDeviceStateIssues(await this.#spawn("adb", ["devices"]));
|
|
1043
|
-
if (issues.length > 0) throw new Error(issues.join("\n"));
|
|
1044
|
-
} catch (error) {
|
|
1045
|
-
if (error instanceof CommandExecutionError) return;
|
|
1046
|
-
throw error;
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
async releaseIos() {
|
|
1051
|
-
await this.prepareWww();
|
|
1052
|
-
await this.#prepareIos({ operation: "release", env: "main" });
|
|
1053
|
-
}
|
|
1054
|
-
async releaseAndroid() {
|
|
1055
|
-
await this.prepareWww();
|
|
1056
|
-
await this.#prepareAndroid({ operation: "release", env: "main" });
|
|
1057
|
-
}
|
|
1058
|
-
async prepareWww() {
|
|
1059
|
-
const htmlSource = path.join(this.app.dist.cwdPath, "csr", targetHtmlFilename(this.target));
|
|
1060
|
-
if (!(await Bun.file(htmlSource).exists()))
|
|
1061
|
-
throw new Error(`CSR html for mobile target '${this.target.name}' not found: ${htmlSource}`);
|
|
1062
|
-
await rm(this.targetWebRoot, { recursive: true, force: true });
|
|
1063
|
-
await mkdir(this.targetWebRoot, { recursive: true });
|
|
1064
|
-
await Bun.write(
|
|
1065
|
-
path.join(this.targetWebRoot, "index.html"),
|
|
1066
|
-
this.#injectMobileTargetMeta(await Bun.file(htmlSource).text()),
|
|
1067
|
-
);
|
|
1068
|
-
}
|
|
1069
|
-
#injectMobileTargetMeta(html: string) {
|
|
1070
|
-
const basePath = this.target.basePath?.replace(/^\/+|\/+$/g, "") ?? "";
|
|
1071
|
-
const script = `<script>window.__AKAN_MOBILE_TARGET__=${JSON.stringify({
|
|
1072
|
-
name: this.target.name,
|
|
1073
|
-
basePath,
|
|
1074
|
-
indexPath: this.target.indexPath,
|
|
1075
|
-
})};</script>`;
|
|
1076
|
-
if (html.includes("window.__AKAN_MOBILE_TARGET__")) return html;
|
|
1077
|
-
return html.replace(/<\/head\s*>/i, `${script}\n</head>`);
|
|
1078
|
-
}
|
|
1079
|
-
async #writeCapacitorConfig(
|
|
1080
|
-
{
|
|
1081
|
-
operation,
|
|
1082
|
-
platform,
|
|
1083
|
-
iosRunTargetKind,
|
|
1084
|
-
}: Pick<RunConfig, "operation"> & { platform?: MobilePlatform; iosRunTargetKind?: IosRunTargetKind },
|
|
1085
|
-
commandEnv: MobileCommandEnv,
|
|
1086
|
-
) {
|
|
1087
|
-
await mkdir(this.targetRoot, { recursive: true });
|
|
1088
|
-
let localIp: string | undefined;
|
|
1089
|
-
if (operation === "local") {
|
|
1090
|
-
const override = commandEnv.AKAN_PUBLIC_CLIENT_HOST ?? process.env.AKAN_PUBLIC_CLIENT_HOST;
|
|
1091
|
-
const resolution = await this.#resolveLocalDevHost({ override, platform, iosRunTargetKind });
|
|
1092
|
-
localIp = resolution.host;
|
|
1093
|
-
this.#logDevHostResolution(resolution, commandEnv);
|
|
1094
|
-
}
|
|
1095
|
-
const config = materializeCapacitorConfig(this.target, {
|
|
1096
|
-
operation,
|
|
1097
|
-
localIp,
|
|
1098
|
-
localServerUrl: localIp ? this.#localCsrUrl(localIp, commandEnv) : undefined,
|
|
1099
|
-
});
|
|
1100
|
-
const content = `${JSON.stringify(config, null, 2)}\n`;
|
|
1101
|
-
await Bun.write(path.join(this.targetRoot, "capacitor.config.json"), content);
|
|
1102
|
-
return content;
|
|
1103
|
-
}
|
|
1104
|
-
// Emulators and simulators reach the host through a loopback alias (10.0.2.2 / localhost); only devices need the LAN.
|
|
1105
|
-
async #resolveLocalDevHost({
|
|
1106
|
-
override,
|
|
1107
|
-
platform,
|
|
1108
|
-
iosRunTargetKind,
|
|
1109
|
-
}: {
|
|
1110
|
-
override?: string;
|
|
1111
|
-
platform?: MobilePlatform;
|
|
1112
|
-
iosRunTargetKind?: IosRunTargetKind;
|
|
1113
|
-
}): Promise<LocalDevHostResolution> {
|
|
1114
|
-
const resolution = selectLocalDevHost(os.networkInterfaces(), { override });
|
|
1115
|
-
if (resolution.source === "override") return resolution;
|
|
1116
|
-
if (platform === "ios" && iosRunTargetKind === "simulator")
|
|
1117
|
-
return { ...resolution, host: "localhost", source: "platform" };
|
|
1118
|
-
if (platform === "android") {
|
|
1119
|
-
try {
|
|
1120
|
-
const host = getAndroidLocalServerHost(await this.#spawn("adb", ["devices"]), resolution.host);
|
|
1121
|
-
return host === resolution.host ? resolution : { ...resolution, host, source: "platform" };
|
|
1122
|
-
} catch {
|
|
1123
|
-
return resolution;
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
return resolution;
|
|
1127
|
-
}
|
|
1128
|
-
#logDevHostResolution(resolution: LocalDevHostResolution, commandEnv: MobileCommandEnv) {
|
|
1129
|
-
this.app.log(`Mobile live-reload server: ${this.#localCsrUrl(resolution.host, commandEnv)}`);
|
|
1130
|
-
if (resolution.source === "override" || resolution.source === "platform") return;
|
|
1131
|
-
const suspicious = resolution.host === "127.0.0.1" || resolution.host.startsWith("169.254.");
|
|
1132
|
-
const alternatives = resolution.candidates.filter((candidate) => candidate.address !== resolution.host);
|
|
1133
|
-
if (!suspicious && alternatives.length === 0) return;
|
|
1134
|
-
const alternativeText = alternatives.length
|
|
1135
|
-
? ` Other interfaces: ${alternatives.map((candidate) => `${candidate.address} (${candidate.name})`).join(", ")}.`
|
|
1136
|
-
: "";
|
|
1137
|
-
this.app.logger.warn(
|
|
1138
|
-
`A physical device must reach ${resolution.host} on your LAN.${suspicious ? " That address looks non-routable." : ""}${alternativeText} If the device shows a blank screen, pin the right one with AKAN_PUBLIC_CLIENT_HOST=<ip>.`,
|
|
1139
|
-
);
|
|
1140
|
-
}
|
|
1141
|
-
async #prepareTargetAssets() {
|
|
1142
|
-
if (!this.target.assets) return;
|
|
1143
|
-
await mkdir(this.targetAssetRoot, { recursive: true });
|
|
1144
|
-
for (const [name, source] of [
|
|
1145
|
-
["icon", this.target.assets.icon],
|
|
1146
|
-
["splash", this.target.assets.splash],
|
|
1147
|
-
] as const)
|
|
1148
|
-
if (source)
|
|
1149
|
-
await cp(path.join(this.app.cwdPath, source), path.join(this.targetAssetRoot, `${name}.png`), { force: true });
|
|
1150
|
-
}
|
|
1151
|
-
async #prepareExternalFiles(platform: "ios" | "android") {
|
|
1152
|
-
const files = this.target.files?.[platform];
|
|
1153
|
-
if (!files) return;
|
|
1154
|
-
const platformRoot = path.join(this.app.cwdPath, platform === "ios" ? this.iosRootPath : this.androidRootPath);
|
|
1155
|
-
await Promise.all(
|
|
1156
|
-
Object.entries(files).map(async ([to, from]) => {
|
|
1157
|
-
const targetPath = path.join(platformRoot, to);
|
|
1158
|
-
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
1159
|
-
await cp(path.join(this.app.cwdPath, from), targetPath, { force: true });
|
|
1160
|
-
}),
|
|
1161
|
-
);
|
|
1162
|
-
}
|
|
1163
|
-
async #generateAssets({ operation, env }: Pick<RunConfig, "operation" | "env">) {
|
|
1164
|
-
if (!this.target.assets) return;
|
|
1165
|
-
await this.#spawnMobile(
|
|
1166
|
-
"npx",
|
|
1167
|
-
[
|
|
1168
|
-
"@capacitor/assets",
|
|
1169
|
-
"generate",
|
|
1170
|
-
"--assetPath",
|
|
1171
|
-
path.posix.join(this.targetRootPath, "assets"),
|
|
1172
|
-
"--iosProject",
|
|
1173
|
-
this.iosProjectPath,
|
|
1174
|
-
"--androidProject",
|
|
1175
|
-
this.androidRootPath,
|
|
1176
|
-
],
|
|
1177
|
-
{ operation, env },
|
|
1178
|
-
);
|
|
1179
|
-
}
|
|
1180
|
-
async #applyIosMetadata() {
|
|
1181
|
-
this.project.ios.setBundleId("App", "Debug", this.target.appId);
|
|
1182
|
-
this.project.ios.setBundleId("App", "Release", this.target.appId);
|
|
1183
|
-
await this.project.ios.setVersion("App", "Debug", this.target.version);
|
|
1184
|
-
await this.project.ios.setVersion("App", "Release", this.target.version);
|
|
1185
|
-
await this.project.ios.setBuild("App", "Debug", this.target.buildNum);
|
|
1186
|
-
await this.project.ios.setBuild("App", "Release", this.target.buildNum);
|
|
1187
|
-
}
|
|
1188
|
-
async #applyAndroidMetadata() {
|
|
1189
|
-
await this.project.android.setVersionName(this.target.version);
|
|
1190
|
-
await this.project.android.setPackageName(this.target.appId);
|
|
1191
|
-
await this.project.android.setVersionCode(this.target.buildNum);
|
|
1192
|
-
await this.project.android.setAppName(this.target.appName);
|
|
1193
|
-
}
|
|
1194
|
-
async #applyAndroidMinSdkVersion() {
|
|
1195
|
-
const variablesGradlePath = path.join(this.app.cwdPath, this.androidRootPath, "variables.gradle");
|
|
1196
|
-
if (!(await Bun.file(variablesGradlePath).exists())) return;
|
|
1197
|
-
const updated = raiseGradleMinSdkVersion(await Bun.file(variablesGradlePath).text());
|
|
1198
|
-
if (!updated) return;
|
|
1199
|
-
await writeFile(variablesGradlePath, updated);
|
|
1200
|
-
this.app.verbose(`Raised Android minSdkVersion to ${ANDROID_MIN_SDK_VERSION} in variables.gradle`);
|
|
1201
|
-
}
|
|
1202
|
-
async #applyPermissions({ operation, env }: Pick<RunConfig, "operation" | "env">) {
|
|
1203
|
-
const plugins = await this.app.collectPlugins();
|
|
1204
|
-
const nativePlugins = new Map<MobilePermission, AkanPlugin[]>();
|
|
1205
|
-
for (const plugin of plugins) {
|
|
1206
|
-
const permission = plugin.capacitor?.permission;
|
|
1207
|
-
if (!permission || !plugin.capacitor?.configureNative) continue;
|
|
1208
|
-
const claimants = nativePlugins.get(permission) ?? [];
|
|
1209
|
-
claimants.push(plugin);
|
|
1210
|
-
nativePlugins.set(permission, claimants);
|
|
1211
|
-
}
|
|
1212
|
-
for (const permission of this.target.permissions ?? []) {
|
|
1213
|
-
const claimants = nativePlugins.get(permission);
|
|
1214
|
-
if (claimants?.length) {
|
|
1215
|
-
const ctx = this.#makeNativeContext({ operation, env });
|
|
1216
|
-
for (const plugin of claimants) await plugin.capacitor?.configureNative?.(ctx);
|
|
1217
|
-
continue;
|
|
1218
|
-
}
|
|
1219
|
-
if (permission === "camera") await this.addCamera();
|
|
1220
|
-
else if (permission === "contacts") await this.addContact();
|
|
1221
|
-
else if (permission === "location") await this.addLocation();
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
#makeNativeContext({ operation, env }: Pick<RunConfig, "operation" | "env">): AkanNativeContext {
|
|
1225
|
-
return {
|
|
1226
|
-
appPath: this.app.cwdPath,
|
|
1227
|
-
executor: this.app,
|
|
1228
|
-
target: this.target,
|
|
1229
|
-
operation,
|
|
1230
|
-
env,
|
|
1231
|
-
setIosUsageDescriptions: (descriptions) => this.#setPermissionInIos(descriptions),
|
|
1232
|
-
updateIosInfoPlist: (values) => this.#updateIosInfoPlist(values),
|
|
1233
|
-
addIosEntitlements: (entitlements) => this.#addIosEntitlements(entitlements),
|
|
1234
|
-
editIosAppDelegate: (transform) => this.#editIosAppDelegate(transform),
|
|
1235
|
-
addAndroidPermissions: (permissions) => this.#setPermissionsInAndroid(permissions),
|
|
1236
|
-
addAndroidFeatures: (features) => this.#setFeaturesInAndroid(features),
|
|
1237
|
-
};
|
|
1238
|
-
}
|
|
1239
|
-
async #applyDeepLinks(platform: "ios" | "android", { operation, env }: Pick<RunConfig, "operation" | "env">) {
|
|
1240
|
-
const deepLinks = this.target.deepLinks;
|
|
1241
|
-
if (!deepLinks) return;
|
|
1242
|
-
const schemes = deepLinks.schemes ?? [];
|
|
1243
|
-
const domains = deepLinks.domains ?? [];
|
|
1244
|
-
if (domains.length > 0) this.#assertDeepLinkVerificationConfig(platform, { operation, env });
|
|
1245
|
-
if (platform === "ios") {
|
|
1246
|
-
if (schemes.length > 0) {
|
|
1247
|
-
await this.#setPermissionInIos({
|
|
1248
|
-
appTransportSecurity: "",
|
|
1249
|
-
});
|
|
1250
|
-
await this.#setUrlSchemesInIos(schemes);
|
|
1251
|
-
}
|
|
1252
|
-
if (domains.length > 0)
|
|
1253
|
-
this.#addIosEntitlements({
|
|
1254
|
-
"com.apple.developer.associated-domains": domains.map((domain) => `applinks:${domain}`),
|
|
1255
|
-
});
|
|
1256
|
-
return;
|
|
1257
|
-
}
|
|
1258
|
-
if (platform === "android") {
|
|
1259
|
-
for (const scheme of schemes) {
|
|
1260
|
-
this.project.android
|
|
1261
|
-
.getAndroidManifest()
|
|
1262
|
-
.injectFragment(
|
|
1263
|
-
"activity",
|
|
1264
|
-
`<intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="${scheme}" /></intent-filter>`,
|
|
1265
|
-
);
|
|
1266
|
-
}
|
|
1267
|
-
for (const domain of domains) {
|
|
1268
|
-
const pathPrefix = resolveMobilePath(this.target, "/");
|
|
1269
|
-
this.project.android
|
|
1270
|
-
.getAndroidManifest()
|
|
1271
|
-
.injectFragment(
|
|
1272
|
-
"activity",
|
|
1273
|
-
`<intent-filter android:autoVerify="true"><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="https" android:host="${domain}" android:pathPrefix="${pathPrefix}" /></intent-filter>`,
|
|
1274
|
-
);
|
|
1275
|
-
}
|
|
1276
|
-
await this.#setDeepLinksInAndroid(schemes, domains);
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
#assertDeepLinkVerificationConfig(
|
|
1280
|
-
platform: "ios" | "android",
|
|
1281
|
-
{ operation, env }: Pick<RunConfig, "operation" | "env">,
|
|
1282
|
-
) {
|
|
1283
|
-
const deepLinks = this.target.deepLinks;
|
|
1284
|
-
if (!deepLinks?.domains?.length) return;
|
|
1285
|
-
if (platform === "ios" && !deepLinks.ios?.teamId) {
|
|
1286
|
-
throw new Error(
|
|
1287
|
-
`Mobile target '${this.target.name}' uses deepLinks.domains but is missing deepLinks.ios.teamId in apps/${this.app.name}/akan.config.ts`,
|
|
1288
|
-
);
|
|
1289
|
-
}
|
|
1290
|
-
if (platform === "android" && !deepLinks.android?.sha256CertFingerprints?.length) {
|
|
1291
|
-
const message = `Mobile target '${this.target.name}' uses deepLinks.domains but is missing deepLinks.android.sha256CertFingerprints in apps/${this.app.name}/akan.config.ts`;
|
|
1292
|
-
if (operation === "release" || env === "main") throw new Error(message);
|
|
1293
|
-
this.app.logger.warn(message);
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
async #commandEnv(operation: "local" | "release", env: "local" | "debug" | "develop" | "main") {
|
|
1297
|
-
const devPort = operation === "local" ? (await this.app.getDevPort()).toString() : undefined;
|
|
1298
|
-
return this.app.getCommandEnv({
|
|
1299
|
-
APP_OPERATION_MODE: operation,
|
|
1300
|
-
AKAN_PUBLIC_OPERATION_MODE: env === "local" ? "local" : "cloud",
|
|
1301
|
-
AKAN_PUBLIC_ENV: env,
|
|
1302
|
-
AKAN_MOBILE_TARGET: this.target.name,
|
|
1303
|
-
...(devPort ? { PORT: devPort, AKAN_PUBLIC_CLIENT_PORT: devPort, AKAN_PUBLIC_SERVER_PORT: devPort } : {}),
|
|
1304
|
-
});
|
|
1305
|
-
}
|
|
1306
|
-
#localCsrUrl(ip: string, commandEnv: MobileCommandEnv) {
|
|
1307
|
-
const basePath = this.target.basePath?.replace(/^\/+|\/+$/g, "");
|
|
1308
|
-
const locale = commandEnv.AKAN_PUBLIC_DEFAULT_LOCALE ?? "en";
|
|
1309
|
-
const pathname = basePath ? `${locale}/${basePath}` : `${locale}/`;
|
|
1310
|
-
const port = commandEnv.AKAN_PUBLIC_CLIENT_PORT ?? commandEnv.PORT ?? "8282";
|
|
1311
|
-
const params = new URLSearchParams({ csr: "true", akanMobileTarget: this.target.name });
|
|
1312
|
-
if (basePath) params.set("akanMobileBasePath", basePath);
|
|
1313
|
-
if (this.target.indexPath) params.set("akanMobileIndexPath", this.target.indexPath);
|
|
1314
|
-
return `http://${ip}:${port}/${pathname}?${params}`;
|
|
1315
|
-
}
|
|
1316
|
-
async #spawn(command: string, args: string[] = [], options: Parameters<AppExecutor["spawn"]>[2] = {}) {
|
|
1317
|
-
return await this.app.spawn(command, args, { cwd: this.app.cwdPath, ...options });
|
|
1318
|
-
}
|
|
1319
|
-
async #spawnMobile(
|
|
1320
|
-
command: string,
|
|
1321
|
-
args: string[] = [],
|
|
1322
|
-
{ operation, env }: Pick<RunConfig, "operation" | "env">,
|
|
1323
|
-
options: SpawnMobileOptions = {},
|
|
1324
|
-
) {
|
|
1325
|
-
const { iosRunTargetKind, platform, ...spawnOptions } = options;
|
|
1326
|
-
const mobileEnv = { ...(await this.#commandEnv(operation, env)), ...options.env };
|
|
1327
|
-
const configContent = await this.#writeCapacitorConfig(
|
|
1328
|
-
{ operation, platform: platform ?? this.#inferMobilePlatform(args), iosRunTargetKind },
|
|
1329
|
-
mobileEnv,
|
|
1330
|
-
);
|
|
1331
|
-
await writeRootCapacitorConfig(this.app.cwdPath, configContent);
|
|
1332
|
-
try {
|
|
1333
|
-
return await this.#spawn(command, args, { ...spawnOptions, env: mobileEnv });
|
|
1334
|
-
} finally {
|
|
1335
|
-
await clearRootCapacitorConfigs(this.app.cwdPath);
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1338
|
-
#inferMobilePlatform(args: string[]): MobilePlatform | undefined {
|
|
1339
|
-
if (args.includes("android")) return "android";
|
|
1340
|
-
if (args.includes("ios")) return "ios";
|
|
1341
|
-
return undefined;
|
|
1342
|
-
}
|
|
1343
|
-
async addCamera() {
|
|
1344
|
-
await this.#setPermissionInIos({
|
|
1345
|
-
cameraUsageDescription: "$(PRODUCT_NAME) requires access to the camera to take photos.",
|
|
1346
|
-
photoAddUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos.",
|
|
1347
|
-
photoUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos.",
|
|
1348
|
-
});
|
|
1349
|
-
this.#setPermissionsInAndroid(["READ_MEDIA_IMAGES", "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"]);
|
|
1350
|
-
}
|
|
1351
|
-
async addContact() {
|
|
1352
|
-
await this.#setPermissionInIos({
|
|
1353
|
-
contactsUsageDescription: "$(PRODUCT_NAME) requires access to the contacts to add new contacts.",
|
|
1354
|
-
});
|
|
1355
|
-
this.#setPermissionsInAndroid(["READ_CONTACTS", "WRITE_CONTACTS"]);
|
|
1356
|
-
}
|
|
1357
|
-
async addLocation() {
|
|
1358
|
-
await this.#setPermissionInIos({
|
|
1359
|
-
locationAlwaysUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location.",
|
|
1360
|
-
locationWhenInUseUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location.",
|
|
1361
|
-
});
|
|
1362
|
-
this.#setPermissionsInAndroid(["ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION"]);
|
|
1363
|
-
this.#setFeaturesInAndroid(["android.hardware.location.gps"]);
|
|
1364
|
-
}
|
|
1365
|
-
#addIosEntitlements(entitlements: Record<string, string | string[]>) {
|
|
1366
|
-
Object.assign(this.#iosEntitlements, entitlements);
|
|
1367
|
-
}
|
|
1368
|
-
//* Feature-specific native wiring (e.g. Firebase) lives in plugins, not the framework.
|
|
1369
|
-
async #editIosAppDelegate(transform: (content: string) => string) {
|
|
1370
|
-
const appDelegatePath = path.join(this.app.cwdPath, this.iosProjectPath, "App/AppDelegate.swift");
|
|
1371
|
-
if (!(await Bun.file(appDelegatePath).exists())) return;
|
|
1372
|
-
const editor = await FileEditor.create(appDelegatePath);
|
|
1373
|
-
const content = editor.getContent();
|
|
1374
|
-
const next = transform(content);
|
|
1375
|
-
if (next !== content) await editor.setContent(next).save();
|
|
1376
|
-
}
|
|
1377
|
-
async #updateIosInfoPlist(values: Record<string, unknown>) {
|
|
1378
|
-
await Promise.all(
|
|
1379
|
-
(["Debug", "Release"] as const).map((build) =>
|
|
1380
|
-
this.project.ios.updateInfoPlist(this.iosTargetName, build, values),
|
|
1381
|
-
),
|
|
1382
|
-
);
|
|
1383
|
-
}
|
|
1384
|
-
async #setPermissionInIos(permissions: { [key: string]: string }) {
|
|
1385
|
-
await this.#updateIosInfoPlist(toIosInfoPlistUsageDescriptions(permissions));
|
|
1386
|
-
}
|
|
1387
|
-
async #setUrlSchemesInIos(schemes: string[]) {
|
|
1388
|
-
await this.#updateIosInfoPlist({
|
|
1389
|
-
CFBundleURLTypes: schemes.map((scheme) => ({ CFBundleURLName: this.target.appId, CFBundleURLSchemes: [scheme] })),
|
|
1390
|
-
});
|
|
1391
|
-
}
|
|
1392
|
-
#serializeIosEntitlements(entitlements: Record<string, string | string[]>) {
|
|
1393
|
-
const lines: string[] = [];
|
|
1394
|
-
for (const [key, value] of Object.entries(entitlements)) {
|
|
1395
|
-
lines.push(` <key>${key}</key>`);
|
|
1396
|
-
if (Array.isArray(value)) {
|
|
1397
|
-
lines.push(" <array>", ...value.map((item) => ` <string>${item}</string>`), " </array>");
|
|
1398
|
-
} else {
|
|
1399
|
-
lines.push(` <string>${value}</string>`);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
return lines;
|
|
1403
|
-
}
|
|
1404
|
-
async #flushIosEntitlements() {
|
|
1405
|
-
if (Object.keys(this.#iosEntitlements).length === 0) return;
|
|
1406
|
-
const entitlementsRelPath = "App/App.entitlements";
|
|
1407
|
-
const entitlementsPath = path.join(this.app.cwdPath, this.iosProjectPath, entitlementsRelPath);
|
|
1408
|
-
const body = [
|
|
1409
|
-
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
1410
|
-
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
1411
|
-
'<plist version="1.0">',
|
|
1412
|
-
"<dict>",
|
|
1413
|
-
...this.#serializeIosEntitlements(this.#iosEntitlements),
|
|
1414
|
-
"</dict>",
|
|
1415
|
-
"</plist>",
|
|
1416
|
-
"",
|
|
1417
|
-
].join("\n");
|
|
1418
|
-
const currentBody = (await Bun.file(entitlementsPath).exists())
|
|
1419
|
-
? await Bun.file(entitlementsPath).text()
|
|
1420
|
-
: undefined;
|
|
1421
|
-
if (currentBody !== body) await writeFile(entitlementsPath, body);
|
|
1422
|
-
await this.#setCodeSignEntitlementsInIos(entitlementsRelPath);
|
|
1423
|
-
}
|
|
1424
|
-
async #setCodeSignEntitlementsInIos(entitlementsRelPath: string) {
|
|
1425
|
-
const pbxprojPath = path.join(this.app.cwdPath, this.iosProjectPath, "App.xcodeproj/project.pbxproj");
|
|
1426
|
-
const lines = (await readFile(pbxprojPath, "utf8")).split("\n");
|
|
1427
|
-
let changed = false;
|
|
1428
|
-
for (let index = 0; index < lines.length; index++) {
|
|
1429
|
-
const line = lines[index] ?? "";
|
|
1430
|
-
if (!line.includes(`PRODUCT_BUNDLE_IDENTIFIER = ${this.target.appId};`)) continue;
|
|
1431
|
-
let start = index;
|
|
1432
|
-
while (start >= 0 && !lines[start]?.includes("buildSettings = {")) start--;
|
|
1433
|
-
let end = index;
|
|
1434
|
-
while (end < lines.length && !/^\s*\};\s*$/.test(lines[end] ?? "")) end++;
|
|
1435
|
-
const settings = lines.slice(start, end + 1);
|
|
1436
|
-
const configName = lines.slice(end + 1, end + 8).find((setting) => setting.includes("name = ")) ?? "";
|
|
1437
|
-
const indent = line.match(/^\s*/)?.[0] ?? "";
|
|
1438
|
-
const insertSettings = [];
|
|
1439
|
-
if (!settings.some((setting) => setting.includes("CODE_SIGN_ENTITLEMENTS"))) {
|
|
1440
|
-
insertSettings.push(`${indent}CODE_SIGN_ENTITLEMENTS = ${entitlementsRelPath};`);
|
|
1441
|
-
}
|
|
1442
|
-
if (
|
|
1443
|
-
configName.includes("name = Debug;") &&
|
|
1444
|
-
!settings.some((setting) => setting.includes("CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION"))
|
|
1445
|
-
) {
|
|
1446
|
-
insertSettings.push(`${indent}CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;`);
|
|
1447
|
-
}
|
|
1448
|
-
if (insertSettings.length > 0) {
|
|
1449
|
-
lines.splice(index, 0, ...insertSettings);
|
|
1450
|
-
index += insertSettings.length;
|
|
1451
|
-
changed = true;
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
if (changed) await writeFile(pbxprojPath, lines.join("\n"));
|
|
1455
|
-
}
|
|
1456
|
-
async #setCodeSignEntitlementsInIosIfExists(entitlementsRelPath: string) {
|
|
1457
|
-
const entitlementsPath = path.join(this.app.cwdPath, this.iosProjectPath, entitlementsRelPath);
|
|
1458
|
-
if (!(await Bun.file(entitlementsPath).exists())) return;
|
|
1459
|
-
await this.#setCodeSignEntitlementsInIos(entitlementsRelPath);
|
|
1460
|
-
}
|
|
1461
|
-
async #setDeepLinksInAndroid(schemes: string[], domains: string[]) {
|
|
1462
|
-
const manifestPath = path.join(this.app.cwdPath, this.androidRootPath, "app/src/main/AndroidManifest.xml");
|
|
1463
|
-
const original = await readFile(manifestPath, "utf8");
|
|
1464
|
-
const pathPrefix = resolveMobilePath(this.target, "/");
|
|
1465
|
-
let manifest = original;
|
|
1466
|
-
for (const scheme of schemes) {
|
|
1467
|
-
if (manifest.includes(`android:scheme="${scheme}"`)) continue;
|
|
1468
|
-
manifest = CapacitorApp.#withIntentFilter(manifest, "<intent-filter>", `<data android:scheme="${scheme}" />`);
|
|
1469
|
-
}
|
|
1470
|
-
for (const domain of domains) {
|
|
1471
|
-
if (manifest.includes(`android:host="${domain}"`) && manifest.includes('android:scheme="https"')) continue;
|
|
1472
|
-
manifest = CapacitorApp.#withIntentFilter(
|
|
1473
|
-
manifest,
|
|
1474
|
-
'<intent-filter android:autoVerify="true">',
|
|
1475
|
-
`<data android:scheme="https" android:host="${domain}" android:pathPrefix="${pathPrefix}" />`,
|
|
1476
|
-
);
|
|
1477
|
-
}
|
|
1478
|
-
if (manifest !== original) await writeFile(manifestPath, manifest);
|
|
1479
|
-
}
|
|
1480
|
-
static #withIntentFilter(manifest: string, open: string, data: string) {
|
|
1481
|
-
const filter = [
|
|
1482
|
-
` ${open}`,
|
|
1483
|
-
' <action android:name="android.intent.action.VIEW" />',
|
|
1484
|
-
' <category android:name="android.intent.category.DEFAULT" />',
|
|
1485
|
-
' <category android:name="android.intent.category.BROWSABLE" />',
|
|
1486
|
-
` ${data}`,
|
|
1487
|
-
" </intent-filter>",
|
|
1488
|
-
].join("\n");
|
|
1489
|
-
return manifest.replace(/(\s*<\/activity>)/, `\n${filter}$1`);
|
|
1490
|
-
}
|
|
1491
|
-
#setFeaturesInAndroid(features: string[]) {
|
|
1492
|
-
for (const feature of features) {
|
|
1493
|
-
if (this.#androidManifestNames("uses-feature").includes(feature)) {
|
|
1494
|
-
this.app.logger.info(`${feature} already exists in android`);
|
|
1495
|
-
return;
|
|
1496
|
-
}
|
|
1497
|
-
this.app.logger.info(`Adding ${feature} to android`);
|
|
1498
|
-
this.project.android
|
|
1499
|
-
.getAndroidManifest()
|
|
1500
|
-
.injectFragment("manifest", `<uses-feature android:name="${feature}" />`);
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
#setPermissionsInAndroid(permissions: string[]) {
|
|
1504
|
-
for (const permission of permissions) {
|
|
1505
|
-
if (this.#androidManifestNames("uses-permission").includes(`android.permission.${permission}`)) {
|
|
1506
|
-
this.app.logger.info(`${permission} already exists in android`);
|
|
1507
|
-
continue;
|
|
1508
|
-
}
|
|
1509
|
-
this.app.logger.info(`Adding ${permission} to android`);
|
|
1510
|
-
this.project.android
|
|
1511
|
-
.getAndroidManifest()
|
|
1512
|
-
.injectFragment("manifest", `<uses-permission android:name="android.permission.${permission}" />`);
|
|
1513
|
-
}
|
|
1514
|
-
}
|
|
1515
|
-
#androidManifestNames(tagName: "uses-feature" | "uses-permission") {
|
|
1516
|
-
const element = this.project.android.getAndroidManifest().getDocumentElement();
|
|
1517
|
-
if (!element) throw new Error("manifest not found");
|
|
1518
|
-
return Array.from(element.getElementsByTagName(tagName)).map((node) => node.getAttribute("android:name"));
|
|
1519
|
-
}
|
|
1520
|
-
}
|