-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathcheckMacAttachFileRuntime.ts
More file actions
348 lines (311 loc) · 11.2 KB
/
Copy pathcheckMacAttachFileRuntime.ts
File metadata and controls
348 lines (311 loc) · 11.2 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
#!/usr/bin/env bun
import { spawnSync } from "node:child_process";
import * as fs from "node:fs/promises";
import { Dirent } from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import sharp from "sharp";
import packageJson from "../package.json";
import { resolveMacPackagedAppNames } from "../src/common/compat/macPackagedApp";
const { productFilename: EXECUTABLE_NAME, appBundleName: APP_NAME } = resolveMacPackagedAppNames(
packageJson.build
);
type MacAppArchitecture = "x64" | "arm64";
const MAC_APP_RUNTIME_PACKAGES: Record<MacAppArchitecture, { binding: string; libvips: string }> = {
x64: { binding: "sharp-darwin-x64", libvips: "sharp-libvips-darwin-x64" },
arm64: { binding: "sharp-darwin-arm64", libvips: "sharp-libvips-darwin-arm64" },
};
const RELEASE_DIR = path.join(process.cwd(), "release");
const APP_ASAR_UNPACKED_NODE_MODULES = [
["node_modules", "sharp"],
["node_modules", "@img"],
] as const;
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
async function listDirectoryEntries(dirPath: string): Promise<Dirent[]> {
try {
return await fs.readdir(dirPath, { withFileTypes: true });
} catch {
return [];
}
}
async function findAppBundles(rootDir: string): Promise<{ matches: string[]; seen: string[] }> {
const matches: string[] = [];
const seen: string[] = [];
async function walk(dirPath: string): Promise<void> {
const entries = await listDirectoryEntries(dirPath);
for (const entry of entries) {
const entryPath = path.join(dirPath, entry.name);
if (entry.isDirectory() && entry.name.endsWith(".app")) {
seen.push(entryPath);
// Compare the stored readdir name, not a case-folded stat path.
if (entry.name === APP_NAME) {
matches.push(entryPath);
}
continue;
}
if (entry.isDirectory()) {
await walk(entryPath);
}
}
}
await walk(rootDir);
return { matches, seen };
}
async function chooseDefaultAppBundle(): Promise<string> {
const { matches: appBundles, seen } = await findAppBundles(RELEASE_DIR);
assert(
appBundles.length > 0,
`No ${APP_NAME} found under ${RELEASE_DIR}. Run make dist-mac first. Stored .app names: ${
seen.length > 0 ? seen.join(", ") : "(none)"
}`
);
const preferredSuffixes =
process.arch === "arm64"
? [
path.join("release", "mac-arm64", APP_NAME),
path.join("release", "mac", APP_NAME),
path.join("release", "mac-universal", APP_NAME),
path.join("release", "mac-x64", APP_NAME),
]
: [
path.join("release", "mac-x64", APP_NAME),
path.join("release", "mac", APP_NAME),
path.join("release", "mac-universal", APP_NAME),
path.join("release", "mac-arm64", APP_NAME),
];
for (const suffix of preferredSuffixes) {
const match = appBundles.find((appBundle) => appBundle.endsWith(suffix));
if (match != null) {
return match;
}
}
return appBundles.sort()[0]!;
}
async function findFileMatching(rootDir: string, pattern: RegExp): Promise<string | null> {
async function walk(dirPath: string): Promise<string | null> {
const entries = await listDirectoryEntries(dirPath);
for (const entry of entries) {
const entryPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
const nestedMatch = await walk(entryPath);
if (nestedMatch != null) {
return nestedMatch;
}
continue;
}
if (pattern.test(entry.name)) {
return entryPath;
}
}
return null;
}
return await walk(rootDir);
}
async function verifyUnpackedSharpAssets(
appBundlePath: string,
architectures: readonly MacAppArchitecture[]
): Promise<void> {
const unpackedRoot = path.join(appBundlePath, "Contents", "Resources", "app.asar.unpacked");
for (const segments of APP_ASAR_UNPACKED_NODE_MODULES) {
const requiredPath = path.join(unpackedRoot, ...segments);
const stat = await fs.stat(requiredPath).catch(() => null);
assert(stat?.isDirectory(), `Missing unpacked runtime directory: ${requiredPath}`);
}
const unpackedImgDir = path.join(unpackedRoot, "node_modules", "@img");
// Issue #3338: checking for any sharp binary let the x64 app ship with only arm64 assets.
for (const architecture of architectures) {
const runtimePackages = MAC_APP_RUNTIME_PACKAGES[architecture];
const bindingDir = path.join(unpackedImgDir, runtimePackages.binding);
const bindingStat = await fs.stat(bindingDir).catch(() => null);
assert(
bindingStat?.isDirectory(),
`Missing ${architecture} sharp binding directory: ${bindingDir}`
);
const sharpBinaryPath = await findFileMatching(
bindingDir,
new RegExp(`${runtimePackages.binding}\\.node$`)
);
assert(
sharpBinaryPath != null,
`Missing ${architecture} sharp native binary under ${bindingDir}`
);
const libvipsDir = path.join(unpackedImgDir, runtimePackages.libvips);
const libvipsStat = await fs.stat(libvipsDir).catch(() => null);
assert(libvipsStat?.isDirectory(), `Missing ${architecture} libvips directory: ${libvipsDir}`);
const libvipsPath = await findFileMatching(libvipsDir, /libvips-cpp\..*\.dylib$/);
assert(libvipsPath != null, `Missing ${architecture} libvips dylib under ${libvipsDir}`);
console.log(`[attach-file-smoke] ${architecture} sharp binary: ${sharpBinaryPath}`);
console.log(`[attach-file-smoke] ${architecture} libvips dylib: ${libvipsPath}`);
}
}
async function createFixtureImages(
tempDir: string
): Promise<{ pngPath: string; jpegPath: string }> {
const pngPath = path.join(tempDir, "oversized.png");
const jpegPath = path.join(tempDir, "rotated.jpg");
await sharp({
create: {
width: 9001,
height: 10,
channels: 3,
background: { r: 255, g: 0, b: 0 },
},
})
.png()
.toFile(pngPath);
await sharp({
create: {
width: 10,
height: 9001,
channels: 3,
background: { r: 255, g: 0, b: 0 },
},
})
.jpeg()
.withMetadata({ orientation: 6 })
.toFile(jpegPath);
return { pngPath, jpegPath };
}
async function resolvePackagedMacExecutable(appBundlePath: string): Promise<string> {
const macOsDir = path.join(appBundlePath, "Contents", "MacOS");
const entries = await listDirectoryEntries(macOsDir);
const names = entries.map((entry) => entry.name);
const match = entries.find((entry) => entry.name === EXECUTABLE_NAME);
assert(
match != null,
`Expected Contents/MacOS/${EXECUTABLE_NAME} in ${appBundlePath}, found: ${
names.length > 0 ? names.join(", ") : "(empty)"
}`
);
return path.join(macOsDir, match.name);
}
async function getPackagedAppArchitectures(appBundlePath: string): Promise<MacAppArchitecture[]> {
const executablePath = await resolvePackagedMacExecutable(appBundlePath);
const result = spawnSync("lipo", ["-archs", executablePath], {
encoding: "utf8",
timeout: 10_000,
});
if (result.error != null) {
throw result.error;
}
if (result.signal != null) {
throw new Error(`lipo was terminated by signal ${result.signal} for ${executablePath}`);
}
assert(
result.status === 0,
`lipo failed for ${executablePath} with exit code ${result.status}: ${result.stderr.trim()}`
);
const architectures = result.stdout
.trim()
.split(/\s+/)
.map((architecture): MacAppArchitecture | null => {
if (architecture === "x86_64") {
return "x64";
}
if (architecture === "arm64") {
return "arm64";
}
return null;
})
.filter((architecture): architecture is MacAppArchitecture => architecture != null);
const uniqueArchitectures = [...new Set(architectures)];
assert(
uniqueArchitectures.length > 0,
`No supported macOS architecture found in ${executablePath}. lipo reported: ${result.stdout.trim()}`
);
return uniqueArchitectures;
}
async function runPackagedSmokeApp(
appBundlePath: string,
fixturePaths: { pngPath: string; jpegPath: string }
): Promise<void> {
const executablePath = await resolvePackagedMacExecutable(appBundlePath);
const tempMuxRoot = path.join(path.dirname(fixturePaths.pngPath), "mux-root");
const result = spawnSync(executablePath, [], {
cwd: process.cwd(),
encoding: "utf8",
timeout: 60_000,
env: {
...process.env,
CI: process.env.CI ?? "true",
CMUX_ALLOW_MULTIPLE_INSTANCES: "1",
MUX_ROOT: tempMuxRoot,
MUX_ATTACH_FILE_SMOKE_TEST_PNG_PATH: fixturePaths.pngPath,
MUX_ATTACH_FILE_SMOKE_TEST_JPEG_PATH: fixturePaths.jpegPath,
},
});
if ((result.stdout?.trim().length ?? 0) > 0) {
console.log(result.stdout.trim());
}
if ((result.stderr?.trim().length ?? 0) > 0) {
console.error(result.stderr.trim());
}
if (result.error != null) {
throw result.error;
}
if (result.signal != null) {
throw new Error(`Packaged attach-file smoke test was terminated by signal ${result.signal}`);
}
assert(
result.status === 0,
`Packaged attach-file smoke test failed with exit code ${result.status}`
);
}
async function main(): Promise<void> {
assert(process.platform === "darwin", "checkMacAttachFileRuntime.ts only runs on macOS");
const requestedAppBundle = process.argv[2];
let appBundles: string[];
let smokeAppBundle: string;
if (requestedAppBundle != null) {
appBundles = [requestedAppBundle];
smokeAppBundle = requestedAppBundle;
} else {
const { matches, seen } = await findAppBundles(RELEASE_DIR);
assert(
matches.length > 0,
`No ${APP_NAME} found under ${RELEASE_DIR}. Run make dist-mac first. Stored .app names: ${
seen.length > 0 ? seen.join(", ") : "(none)"
}`
);
appBundles = matches;
smokeAppBundle = await chooseDefaultAppBundle();
}
const verifiedArchitectures = new Set<MacAppArchitecture>();
for (const appBundlePath of appBundles) {
const appStat = await fs.stat(appBundlePath).catch(() => null);
assert(appStat?.isDirectory(), `macOS app bundle not found: ${appBundlePath}`);
const architectures = await getPackagedAppArchitectures(appBundlePath);
console.log(
`[attach-file-smoke] verifying app bundle ${appBundlePath} (${architectures.join(", ")})`
);
await verifyUnpackedSharpAssets(appBundlePath, architectures);
for (const architecture of architectures) {
verifiedArchitectures.add(architecture);
}
}
if (requestedAppBundle == null) {
for (const requiredArchitecture of ["x64", "arm64"] as const) {
assert(
verifiedArchitectures.has(requiredArchitecture),
`Missing ${requiredArchitecture} macOS app bundle under ${RELEASE_DIR}. Verified architectures: ${
verifiedArchitectures.size > 0 ? [...verifiedArchitectures].join(", ") : "(none)"
}`
);
}
}
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "mux-attach-file-smoke-"));
try {
const fixturePaths = await createFixtureImages(tempDir);
await runPackagedSmokeApp(smokeAppBundle, fixturePaths);
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
}
void main().catch((error) => {
console.error("[attach-file-smoke] failed:", error);
process.exitCode = 1;
});