-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapple.ts
More file actions
522 lines (466 loc) · 15.8 KB
/
apple.ts
File metadata and controls
522 lines (466 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import assert from "node:assert/strict";
import path from "node:path";
import fs from "node:fs";
import cp from "node:child_process";
import {
Option,
oraPromise,
prettyPath,
} from "@react-native-node-api/cli-utils";
import {
AppleTriplet as Triplet,
createAppleFramework,
createXCframework,
dereferenceDirectory,
} from "react-native-node-api";
import type { Platform } from "./types.js";
import * as cmakeFileApi from "cmake-file-api";
import { toDefineArguments } from "../helpers.js";
import {
getCmakeJSVariables,
getWeakNodeApiVariables,
} from "../weak-node-api.js";
import * as z from "zod";
const XcodeListOutput = z.object({
project: z.object({
configurations: z.array(z.string()),
name: z.string(),
schemes: z.array(z.string()),
targets: z.array(z.string()),
}),
});
function listXcodeProject(cwd: string): z.infer<typeof XcodeListOutput> {
const result = cp.spawnSync("xcodebuild", ["-list", "-json"], {
encoding: "utf-8",
cwd,
});
assert.equal(
result.status,
0,
`Failed to run xcodebuild -list: ${result.stderr}`,
);
const parsed = JSON.parse(result.stdout) as unknown;
return XcodeListOutput.parse(parsed);
}
type XcodeSDKName =
| "iphoneos"
| "iphonesimulator"
| "catalyst"
| "xros"
| "xrsimulator"
| "appletvos"
| "appletvsimulator"
| "macosx";
const XCODE_SDK_NAMES = {
"x86_64-apple-darwin": "macosx",
"arm64-apple-darwin": "macosx",
"arm64;x86_64-apple-darwin": "macosx",
"arm64-apple-ios": "iphoneos",
"arm64-apple-ios-sim": "iphonesimulator",
"x86_64-apple-ios-sim": "iphonesimulator",
"arm64;x86_64-apple-ios-sim": "iphonesimulator",
// "x86_64-apple-tvos": "appletvos",
"arm64-apple-tvos": "appletvos",
"x86_64-apple-tvos-sim": "appletvsimulator",
"arm64-apple-tvos-sim": "appletvsimulator",
"arm64;x86_64-apple-tvos-sim": "appletvsimulator",
"arm64-apple-visionos": "xros",
"arm64-apple-visionos-sim": "xrsimulator",
"x86_64-apple-visionos-sim": "xrsimulator",
"arm64;x86_64-apple-visionos-sim": "xrsimulator",
} satisfies Record<Triplet, XcodeSDKName>;
type CMakeSystemName = "Darwin" | "iOS" | "tvOS" | "watchOS" | "visionOS";
const CMAKE_SYSTEM_NAMES = {
"x86_64-apple-darwin": "Darwin",
"arm64-apple-darwin": "Darwin",
"arm64;x86_64-apple-darwin": "Darwin",
"arm64-apple-ios": "iOS",
"arm64-apple-ios-sim": "iOS",
"x86_64-apple-ios-sim": "iOS",
"arm64;x86_64-apple-ios-sim": "iOS",
// "x86_64-apple-tvos": "appletvos",
"arm64-apple-tvos": "tvOS",
"arm64-apple-tvos-sim": "tvOS",
"x86_64-apple-tvos-sim": "tvOS",
"arm64;x86_64-apple-tvos-sim": "tvOS",
"arm64-apple-visionos": "visionOS",
"x86_64-apple-visionos-sim": "visionOS",
"arm64-apple-visionos-sim": "visionOS",
"arm64;x86_64-apple-visionos-sim": "visionOS",
} satisfies Record<Triplet, CMakeSystemName>;
const DESTINATION_BY_TRIPLET = {
"x86_64-apple-darwin": "generic/platform=macOS",
"arm64-apple-darwin": "generic/platform=macOS",
"arm64;x86_64-apple-darwin": "generic/platform=macOS",
"arm64-apple-ios": "generic/platform=iOS",
"arm64-apple-ios-sim": "generic/platform=iOS Simulator",
"x86_64-apple-ios-sim": "generic/platform=iOS Simulator",
"arm64;x86_64-apple-ios-sim": "generic/platform=iOS Simulator",
"arm64-apple-tvos": "generic/platform=tvOS",
// "x86_64-apple-tvos": "generic/platform=tvOS",
"x86_64-apple-tvos-sim": "generic/platform=tvOS Simulator",
"arm64-apple-tvos-sim": "generic/platform=tvOS Simulator",
"arm64;x86_64-apple-tvos-sim": "generic/platform=tvOS Simulator",
"arm64-apple-visionos": "generic/platform=visionOS",
"arm64-apple-visionos-sim": "generic/platform=visionOS Simulator",
"x86_64-apple-visionos-sim": "generic/platform=visionOS Simulator",
"arm64;x86_64-apple-visionos-sim": "generic/platform=visionOS Simulator",
} satisfies Record<Triplet, string>;
type AppleArchitecture = "arm64" | "x86_64" | "arm64;x86_64";
export const APPLE_ARCHITECTURES = {
"x86_64-apple-darwin": "x86_64",
"arm64-apple-darwin": "arm64",
"arm64;x86_64-apple-darwin": "arm64;x86_64",
"arm64-apple-ios": "arm64",
"arm64-apple-ios-sim": "arm64",
"x86_64-apple-ios-sim": "x86_64",
"arm64;x86_64-apple-ios-sim": "arm64;x86_64",
// "x86_64-apple-tvos": "x86_64",
"arm64-apple-tvos": "arm64",
"arm64-apple-tvos-sim": "arm64",
"x86_64-apple-tvos-sim": "x86_64",
"arm64;x86_64-apple-tvos-sim": "arm64;x86_64",
"arm64-apple-visionos": "arm64",
"x86_64-apple-visionos-sim": "x86_64",
"arm64-apple-visionos-sim": "arm64",
"arm64;x86_64-apple-visionos-sim": "arm64;x86_64",
} satisfies Record<Triplet, AppleArchitecture>;
const xcframeworkExtensionOption = new Option(
"--xcframework-extension",
"Don't rename the xcframework to .apple.node",
).default(false);
const appleBundleIdentifierOption = new Option(
"--apple-bundle-identifier <id>",
"Unique CFBundleIdentifier used for Apple framework artifacts",
).default(undefined, "com.callstackincubator.node-api.{libraryName}");
type AppleOpts = {
xcframeworkExtension: boolean;
appleBundleIdentifier?: string;
};
function getBuildPath(baseBuildPath: string, triplet: Triplet) {
return path.join(baseBuildPath, triplet.replace(/;/g, "_"));
}
async function readCmakeSharedLibraryTarget(
buildPath: string,
configuration: string,
target: string[],
) {
const targets = await cmakeFileApi.readCurrentTargetsDeep(
buildPath,
configuration,
"2.0",
);
const sharedLibraries = targets.filter(
({ type, name }) =>
type === "SHARED_LIBRARY" &&
(target.length === 0 || target.includes(name)),
);
assert.equal(
sharedLibraries.length,
1,
"Expected exactly one shared library",
);
const [sharedLibrary] = sharedLibraries;
return sharedLibrary;
}
async function getCompilerPath(
name: "clang" | "clang++",
{ buildBinPath, ccachePath }: { buildBinPath: string; ccachePath: string },
) {
const result = path.join(buildBinPath, name);
if (!fs.existsSync(result)) {
await fs.promises.symlink(ccachePath, result);
}
return result;
}
export const platform: Platform<Triplet[], AppleOpts> = {
id: "apple",
name: "Apple",
triplets: [
"arm64-apple-darwin",
"x86_64-apple-darwin",
"arm64;x86_64-apple-darwin",
"arm64-apple-ios",
"arm64-apple-ios-sim",
"x86_64-apple-ios-sim",
"arm64;x86_64-apple-ios-sim",
"arm64-apple-tvos",
"x86_64-apple-tvos-sim",
"arm64-apple-tvos-sim",
"arm64;x86_64-apple-tvos-sim",
"arm64-apple-visionos",
"x86_64-apple-visionos-sim",
"arm64-apple-visionos-sim",
"arm64;x86_64-apple-visionos-sim",
],
defaultTriplets(mode) {
if (mode === "all") {
return [
"arm64;x86_64-apple-darwin",
"arm64-apple-ios",
"arm64;x86_64-apple-ios-sim",
"arm64-apple-tvos",
"arm64;x86_64-apple-tvos-sim",
"arm64-apple-visionos",
"arm64;x86_64-apple-visionos-sim",
];
} else if (mode === "current-development") {
// We're applying a heuristic to determine the current simulators
// TODO: Run a command to probe the currently running simulators instead
return ["arm64;x86_64-apple-ios-sim"];
} else {
throw new Error(`Unexpected mode: ${mode as string}`);
}
},
amendCommand(command) {
return command
.addOption(xcframeworkExtensionOption)
.addOption(appleBundleIdentifierOption);
},
async configure(
triplets,
{ source, build, define, weakNodeApiLinkage, cmakeJs, ccachePath },
) {
// When using ccache, we're creating symlinks for the clang and clang++ binaries to the ccache binary
// This is needed for ccache to understand it's being invoked as clang and clang++ respectively.
const buildBinPath = path.join(build, "bin");
await fs.promises.mkdir(buildBinPath, { recursive: true });
const compilerDefinitions = ccachePath
? {
CMAKE_XCODE_ATTRIBUTE_CC: await getCompilerPath("clang", {
buildBinPath,
ccachePath,
}),
CMAKE_XCODE_ATTRIBUTE_CXX: await getCompilerPath("clang++", {
buildBinPath,
ccachePath,
}),
CMAKE_XCODE_ATTRIBUTE_LD: await getCompilerPath("clang", {
buildBinPath,
ccachePath,
}),
CMAKE_XCODE_ATTRIBUTE_LDPLUSPLUS: await getCompilerPath("clang++", {
buildBinPath,
ccachePath,
}),
}
: {};
// Ideally, we would generate a single Xcode project supporting all architectures / platforms
// However, CMake's Xcode generator does not support that well, so we generate one project per triplet
// Specifically, the linking of weak-node-api breaks, since the sdk / arch specific framework
// from the xcframework is picked at configure time, not at build time.
// See https://gitlab.kitware.com/cmake/cmake/-/issues/21752#note_1717047 for more information.
await Promise.all(
triplets.map(async ({ triplet, spawn }) => {
const buildPath = getBuildPath(build, triplet);
// We want to use the CMake File API to query information later
// TODO: Or do we?
await cmakeFileApi.createSharedStatelessQuery(
buildPath,
"codemodel",
"2",
);
await spawn("cmake", [
"-S",
source,
"-B",
buildPath,
"-G",
"Xcode",
...toDefineArguments([
...define,
weakNodeApiLinkage ? getWeakNodeApiVariables("apple") : {},
cmakeJs ? getCmakeJSVariables("apple") : {},
compilerDefinitions,
{
CMAKE_SYSTEM_NAME: CMAKE_SYSTEM_NAMES[triplet],
CMAKE_OSX_SYSROOT: XCODE_SDK_NAMES[triplet],
CMAKE_OSX_ARCHITECTURES: APPLE_ARCHITECTURES[triplet],
// Passing a linker flag to increase the header pad size to allow renaming the install name when linking it into the app.
CMAKE_SHARED_LINKER_FLAGS: "-Wl,-headerpad_max_install_names",
// Setting the output directories works around an issue with Xcode generator
// where an unexpanded variable would emitted in the artifact paths.
// This is okay, since we're generating per triplet build directories anyway.
// https://gitlab.kitware.com/cmake/cmake/-/issues/24161
CMAKE_LIBRARY_OUTPUT_DIRECTORY: path.join(buildPath, "out"),
CMAKE_ARCHIVE_OUTPUT_DIRECTORY: path.join(buildPath, "out"),
},
]),
]);
}),
);
},
async build(
{ spawn, triplet },
{ build, target, configuration, appleBundleIdentifier },
) {
// We expect the final application to sign these binaries
if (target.length > 1) {
throw new Error("Building for multiple targets is not supported yet");
}
const buildPath = getBuildPath(build, triplet);
const sharedLibrary = await readCmakeSharedLibraryTarget(
buildPath,
configuration,
target,
);
const isFramework = sharedLibrary.nameOnDisk?.includes(".framework/");
if (isFramework) {
const { project } = listXcodeProject(buildPath);
const schemes = project.schemes.filter(
(scheme) => scheme !== "ALL_BUILD" && scheme !== "ZERO_CHECK",
);
assert(
schemes.length === 1,
`Expected exactly one buildable scheme, got ${schemes.join(", ")}`,
);
const [scheme] = schemes;
if (target.length === 1) {
assert.equal(
scheme,
target[0],
"Expected the only scheme to match the requested target",
);
}
await spawn(
"xcodebuild",
[
"archive",
"-scheme",
scheme,
"-configuration",
configuration,
"-destination",
DESTINATION_BY_TRIPLET[triplet],
],
buildPath,
);
await spawn(
"xcodebuild",
[
"install",
"-scheme",
scheme,
"-configuration",
configuration,
"-destination",
DESTINATION_BY_TRIPLET[triplet],
],
buildPath,
);
} else {
await spawn("cmake", [
"--build",
buildPath,
"--config",
configuration,
...(target.length > 0 ? ["--target", ...target] : []),
"--",
// Skip code-signing (needed when building free dynamic libraries)
// TODO: Make this configurable
"CODE_SIGNING_ALLOWED=NO",
]);
// Create a framework
const { artifacts } = sharedLibrary;
assert(
artifacts && artifacts.length === 1,
"Expected exactly one artifact",
);
const [artifact] = artifacts;
await createAppleFramework({
libraryPath: path.join(buildPath, artifact.path),
versioned: triplet.endsWith("-darwin"),
bundleIdentifier: appleBundleIdentifier,
});
}
},
isSupportedByHost: function (): boolean | Promise<boolean> {
return process.platform === "darwin";
},
async postBuild(
outputPath,
triplets,
{ configuration, autoLink, xcframeworkExtension, target, build, strip },
) {
const libraryNames = new Set<string>();
const frameworkPaths: string[] = [];
for (const { spawn, triplet } of triplets) {
const buildPath = getBuildPath(build, triplet);
assert(fs.existsSync(buildPath), `Expected a directory at ${buildPath}`);
const sharedLibrary = await readCmakeSharedLibraryTarget(
buildPath,
configuration,
target,
);
const { artifacts } = sharedLibrary;
assert(
artifacts && artifacts.length === 1,
"Expected exactly one artifact",
);
const [artifact] = artifacts;
const artifactPath = path.join(buildPath, artifact.path);
if (strip) {
// -r: All relocation entries.
// -S: All symbol table entries.
// -T: All text relocation entries.
// -x: All local symbols.
await spawn("strip", ["-rSTx", artifactPath]);
}
libraryNames.add(sharedLibrary.name);
// Locate the path of the framework, if a free dynamic library was built
if (artifact.path.includes(".framework/")) {
frameworkPaths.push(path.dirname(artifactPath));
} else {
const libraryName = path.basename(
artifact.path,
path.extname(artifact.path),
);
const frameworkPath = path.join(
buildPath,
path.dirname(artifact.path),
`${libraryName}.framework`,
);
assert(
fs.existsSync(frameworkPath),
`Expected to find a framework at: ${frameworkPath}`,
);
frameworkPaths.push(frameworkPath);
}
}
// Make sure none of the frameworks are symlinks
// We do this before creating an xcframework to avoid symlink paths being invalidated
// as the xcframework might be moved to a different location
await Promise.all(
frameworkPaths.map(async (frameworkPath) => {
const stat = await fs.promises.lstat(frameworkPath);
if (stat.isSymbolicLink()) {
await dereferenceDirectory(frameworkPath);
}
}),
);
const extension = xcframeworkExtension ? ".xcframework" : ".apple.node";
assert(
libraryNames.size === 1,
"Expected all libraries to have the same name",
);
const [libraryName] = libraryNames;
// Create the xcframework
const xcframeworkOutputPath = path.resolve(
outputPath,
`${libraryName}${extension}`,
);
await oraPromise(
createXCframework({
outputPath: xcframeworkOutputPath,
frameworkPaths,
autoLink,
}),
{
text: `Assembling XCFramework (${libraryName})`,
successText: `XCFramework (${libraryName}) assembled into ${prettyPath(xcframeworkOutputPath)}`,
failText: ({ message }) =>
`Failed to assemble XCFramework (${libraryName}): ${message}`,
},
);
},
};