peachsim 0.1.2625 → 0.1.2626

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.
Files changed (128) hide show
  1. package/cli/commands/diagnose-native.ts +717 -0
  2. package/cli/commands/perf-native.ts +120 -51
  3. package/dist-lib/agent-daemon-client.cjs +1 -1
  4. package/dist-lib/agent-events.cjs +1 -1
  5. package/dist-lib/attached-projects.cjs +1 -1
  6. package/dist-lib/auth/shared-session.cjs +1 -1
  7. package/dist-lib/backend-origin.cjs +1 -1
  8. package/dist-lib/beta.cjs +1 -1
  9. package/dist-lib/beta.mjs +2 -2
  10. package/dist-lib/bridge-constants.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.mjs +5 -5
  13. package/dist-lib/bridge-contract.cjs +1 -1
  14. package/dist-lib/bridge-contract.mjs +3 -3
  15. package/dist-lib/bundle-channel.cjs +87 -17
  16. package/dist-lib/capture-contract.cjs +1 -1
  17. package/dist-lib/capture-contract.mjs +3 -3
  18. package/dist-lib/cloud-contract.cjs +1 -1
  19. package/dist-lib/cloud-contract.mjs +3 -3
  20. package/dist-lib/cloud-test-args.cjs +1 -1
  21. package/dist-lib/cloud-test-args.mjs +2 -2
  22. package/dist-lib/cloud.cjs +1 -1
  23. package/dist-lib/cloud.mjs +7 -7
  24. package/dist-lib/config.cjs +1 -1
  25. package/dist-lib/config.mjs +5 -5
  26. package/dist-lib/detox/index.cjs +1 -1
  27. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  28. package/dist-lib/esm-chunks/{acorn-SHZZDBSI.mjs → acorn-JXJYSAIN.mjs} +3 -3
  29. package/dist-lib/esm-chunks/{chunk-JVEJLPJC.mjs → chunk-26TN2VTX.mjs} +2 -2
  30. package/dist-lib/esm-chunks/{chunk-RXXCTHJG.mjs → chunk-2NVWTTQ4.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-SRIRVPNX.mjs → chunk-2R77YMAI.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-ULHG6CND.mjs → chunk-4KZSU4Q6.mjs} +6 -6
  33. package/dist-lib/esm-chunks/{chunk-A4R4YGFJ.mjs → chunk-5STOTQGG.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-LJYNZ5HM.mjs → chunk-5TQNPFPN.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-Q5NI4L3Z.mjs → chunk-5UEXET5Y.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-M2FEKSK3.mjs → chunk-62JXISPM.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-RJWEWNAJ.mjs → chunk-7ASIV44B.mjs} +3 -3
  38. package/dist-lib/esm-chunks/{chunk-6PZI7TYE.mjs → chunk-AETFJFSQ.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-3XZGWT62.mjs → chunk-AVFNDICR.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-KA4AQDVF.mjs → chunk-BFQUJ4RC.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-7Z7YJ4FU.mjs → chunk-BSNIUHSI.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-2LDG7OD4.mjs → chunk-F6KLM535.mjs} +5 -5
  43. package/dist-lib/esm-chunks/{chunk-F4YHL4UM.mjs → chunk-HESCA2JF.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-OCCZJOSA.mjs → chunk-IYJG62ST.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-A66VNSO6.mjs → chunk-LBDHHUER.mjs} +80 -14
  46. package/dist-lib/esm-chunks/{chunk-XQBHCWS4.mjs → chunk-LWOZ3LUO.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-DVMKYLDN.mjs → chunk-T4ZKKV6P.mjs} +6 -6
  48. package/dist-lib/esm-chunks/{chunk-W4HQINQ6.mjs → chunk-UD7ON4ZV.mjs} +4 -4
  49. package/dist-lib/esm-chunks/{chunk-JRU2VXUU.mjs → chunk-V4CRDOYA.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-P542MMIN.mjs → chunk-WC43FELF.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{chunk-R4FFTWPL.mjs → chunk-XCUDQYYK.mjs} +1 -1
  52. package/dist-lib/esm-chunks/{chunk-Z6AH6AQC.mjs → chunk-YPBNNV6N.mjs} +1 -1
  53. package/dist-lib/esm-chunks/{metro-layout-parser-GJHR7FCR.mjs → metro-layout-parser-E34XATI4.mjs} +3 -3
  54. package/dist-lib/esm-chunks/{swift-package-prebuilt-UVRGKTD4.mjs → swift-package-prebuilt-73BSTPFQ.mjs} +12 -12
  55. package/dist-lib/esm-chunks/{swift-sdk-app-module-U3MUJ7QD.mjs → swift-sdk-app-module-L7AT6SCB.mjs} +16 -16
  56. package/dist-lib/esm-chunks/{swift-sdk-image-U4W7QMAT.mjs → swift-sdk-image-5NH574IM.mjs} +16 -16
  57. package/dist-lib/esm-chunks/{swift-sdk-image-producer-TFFZDNRK.mjs → swift-sdk-image-producer-YVZHH2LX.mjs} +5 -5
  58. package/dist-lib/expo-swift-bundle.cjs +87 -17
  59. package/dist-lib/expo-swift-metadata.cjs +1 -1
  60. package/dist-lib/expo-swift-metadata.mjs +7 -7
  61. package/dist-lib/home-paths.cjs +1 -1
  62. package/dist-lib/host/bridge-host.cjs +87 -17
  63. package/dist-lib/host/fetch-proxy-handler.cjs +71 -4
  64. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  65. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  66. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  67. package/dist-lib/host/websocket-proxy.cjs +1 -1
  68. package/dist-lib/index.cjs +1 -1
  69. package/dist-lib/kotlin-host.cjs +1 -1
  70. package/dist-lib/menu.cjs +1 -1
  71. package/dist-lib/menu.mjs +3 -3
  72. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  73. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  74. package/dist-lib/metro-production-bundle.cjs +1 -1
  75. package/dist-lib/metro-production-bundle.mjs +4 -4
  76. package/dist-lib/native-app-identity-project.cjs +1 -1
  77. package/dist-lib/native-app-identity-project.mjs +15 -15
  78. package/dist-lib/native-app-identity.cjs +1 -1
  79. package/dist-lib/native-app-identity.mjs +6 -6
  80. package/dist-lib/native-firebase-metadata.cjs +1 -1
  81. package/dist-lib/native-firebase-metadata.mjs +3 -3
  82. package/dist-lib/pdfium-raster.cjs +1 -1
  83. package/dist-lib/pdfium-raster.mjs +2 -2
  84. package/dist-lib/plist.cjs +1 -1
  85. package/dist-lib/plist.mjs +3 -3
  86. package/dist-lib/profiles.cjs +1 -1
  87. package/dist-lib/public-brand.cjs +1 -1
  88. package/dist-lib/public-origins-lib-esm.json +85 -85
  89. package/dist-lib/public-origins-lib.json +64 -64
  90. package/dist-lib/react-native-host-modules.cjs +1 -1
  91. package/dist-lib/react-native-host-modules.mjs +2 -2
  92. package/dist-lib/reap-browser.cjs +1 -1
  93. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  94. package/dist-lib/sdk.cjs +1 -1
  95. package/dist-lib/sdk.mjs +8 -8
  96. package/dist-lib/skills.cjs +87 -17
  97. package/dist-lib/swift-compile.cjs +68 -2
  98. package/dist-lib/swift-compile.mjs +12 -12
  99. package/dist-lib/swift-package.cjs +1 -1
  100. package/dist-lib/swift-package.mjs +3 -3
  101. package/dist-lib/swift-submit.cjs +1 -1
  102. package/dist-lib/swift-submit.mjs +6 -6
  103. package/dist-lib/swift-svg-raster.cjs +1 -1
  104. package/dist-lib/swift-svg-raster.mjs +2 -2
  105. package/dist-lib/swift-toolchain.cjs +1 -1
  106. package/dist-lib/swift.cjs +1 -1
  107. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  109. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  110. package/dist-lib/vendor/acorn.cjs +1 -1
  111. package/dist-lib/vendor/magic-string.cjs +1 -1
  112. package/dist-lib/vendor/stream-json.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase.cjs +1 -1
  118. package/dist-lib/vendor/terser.cjs +1 -1
  119. package/dist-lib/vendor/valibot.cjs +1 -1
  120. package/dist-lib/vendor/ws.cjs +1 -1
  121. package/dist-lib/vendor/zod.cjs +1 -1
  122. package/dist-lib/worklet-executable.cjs +1 -1
  123. package/dist-lib/worklet-executable.mjs +3 -3
  124. package/kotlin/sdk.tar.gz +0 -0
  125. package/package.json +1 -1
  126. package/src/react-native-core-build.ts +12 -12
  127. package/src/react-native-core.ts +3 -7
  128. package/src/swift-compiler-digest.ts +37 -10
@@ -0,0 +1,717 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import {
4
+ existsSync,
5
+ mkdtempSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ statSync,
10
+ } from 'node:fs'
11
+ import { homedir, tmpdir } from 'node:os'
12
+ import { basename, dirname, join, resolve } from 'node:path'
13
+ import { setTimeout } from 'node:timers/promises'
14
+ import { parseArgs } from 'node:util'
15
+ import {
16
+ type NativeProfileReport,
17
+ asNum,
18
+ asStr,
19
+ isRecord,
20
+ parseNativeReport,
21
+ parseReportEnvelope,
22
+ profileUUID,
23
+ records,
24
+ requestSimulatorProfile,
25
+ runningSimulatorApps,
26
+ symbolicateDiagnosticReports,
27
+ } from './perf-native'
28
+
29
+ type Row = Record<string, unknown>
30
+ type Target = {
31
+ kind: 'simulator' | 'phone'
32
+ device: string
33
+ bundleId: string
34
+ name: string
35
+ executable: string
36
+ }
37
+ type Incident = { at: number; summary: string }
38
+
39
+ const hostExecutable = 'PeachCoreHost'
40
+ const profilerDirectory = 'Library/Application Support/OneProfiler'
41
+
42
+ function record(value: unknown): Row | undefined {
43
+ return isRecord(value) ? value : undefined
44
+ }
45
+
46
+ function jsonCommand(command: string, args: string[]): Row | undefined {
47
+ const result = spawnSync(command, args, {
48
+ encoding: 'utf8',
49
+ timeout: 15_000,
50
+ maxBuffer: 16 * 1024 * 1024,
51
+ })
52
+ return result.status === 0 ? record(JSON.parse(result.stdout)) : undefined
53
+ }
54
+
55
+ function deviceQuery(args: string[]): Row | undefined {
56
+ return record(
57
+ jsonCommand('xcrun', ['devicectl', ...args, '--timeout', '8', '--json-output', '-'])
58
+ ?.result,
59
+ )
60
+ }
61
+
62
+ function appInfo(app: string): Row | undefined {
63
+ const info = join(app, 'Info.plist')
64
+ if (existsSync(info))
65
+ return jsonCommand('plutil', ['-convert', 'json', '-o', '-', info])
66
+ }
67
+
68
+ function simulators(): Target[] {
69
+ const list = jsonCommand('xcrun', ['simctl', 'list', 'devices', 'booted', '-j'])
70
+ return Object.values(record(list?.devices) ?? {})
71
+ .flatMap(records)
72
+ .flatMap((sim) => {
73
+ const device = asStr(sim.udid)
74
+ if (!device) return []
75
+ return runningSimulatorApps(device).flatMap((bundleId) => {
76
+ const container = spawnSync(
77
+ 'xcrun',
78
+ ['simctl', 'get_app_container', device, bundleId, 'app'],
79
+ { encoding: 'utf8', timeout: 5000 },
80
+ )
81
+ if (container.status !== 0) return []
82
+ const info = appInfo(container.stdout.trim())
83
+ if (info?.CFBundleExecutable !== hostExecutable) return []
84
+ return {
85
+ kind: 'simulator',
86
+ device,
87
+ bundleId,
88
+ name: asStr(sim.name),
89
+ executable: hostExecutable,
90
+ } satisfies Target
91
+ })
92
+ })
93
+ }
94
+
95
+ function phones(): Target[] {
96
+ return records(deviceQuery(['list', 'devices'])?.devices).flatMap((device) => {
97
+ const hw = record(device.hardwareProperties)
98
+ const connection = record(device.connectionProperties)
99
+ const id = asStr(device.identifier)
100
+ if (
101
+ !id ||
102
+ hw?.platform !== 'iOS' ||
103
+ hw.reality !== 'physical' ||
104
+ connection?.pairingState !== 'paired'
105
+ )
106
+ return []
107
+ const processes = deviceQuery(['device', 'info', 'processes', '--device', id])
108
+ if (!processes) return []
109
+ const executables = new Set(
110
+ records(processes.runningProcesses).map((proc) => asStr(proc.executable)),
111
+ )
112
+ const apps = deviceQuery(['device', 'info', 'apps', '--device', id])
113
+ return records(apps?.apps).flatMap((app) => {
114
+ const bundleId = asStr(app.bundleIdentifier)
115
+ const url = asStr(app.url)
116
+ if (
117
+ !bundleId ||
118
+ !url ||
119
+ !executables.has(url.replace(/\/?$/, '/') + hostExecutable)
120
+ )
121
+ return []
122
+ return {
123
+ kind: 'phone',
124
+ device: id,
125
+ bundleId,
126
+ name: asStr(record(device.deviceProperties)?.name),
127
+ executable: hostExecutable,
128
+ } satisfies Target
129
+ })
130
+ })
131
+ }
132
+
133
+ function runningTarget(directories: string[]): Target {
134
+ if (process.platform !== 'darwin')
135
+ throw new Error(
136
+ 'Live iOS diagnostics require macOS with Xcode. Use --telemetry for saved data.',
137
+ )
138
+ const targets = simulators()
139
+ const local = new Set(
140
+ directories.flatMap((dir) => {
141
+ const bundle = asStr(appInfo(join(dir, 'PeachReactHost.app'))?.CFBundleIdentifier)
142
+ return bundle ? [bundle] : []
143
+ }),
144
+ )
145
+ const matching = targets.filter((target) => local.has(target.bundleId))
146
+ if (matching.length === 1) return matching[0]!
147
+ if (!targets.length || (local.size && !matching.length)) {
148
+ const connected = phones()
149
+ const phone = connected.filter((target) => local.has(target.bundleId))
150
+ if (phone.length === 1) return phone[0]!
151
+ targets.push(...connected)
152
+ }
153
+ if (targets.length === 1) return targets[0]!
154
+ if (targets.length > 1)
155
+ throw new Error(
156
+ `Multiple One apps are running (${targets.map((target) => `${target.bundleId} on ${target.name}`).join(', ')}). Leave one running or use --telemetry.`,
157
+ )
158
+ throw new Error(
159
+ 'No running One iOS app found. Open the app on a simulator or paired iPhone, or use --telemetry.',
160
+ )
161
+ }
162
+
163
+ function copyDeviceFile(
164
+ device: string,
165
+ domain: string,
166
+ source: string,
167
+ destination: string,
168
+ bundleId?: string,
169
+ ) {
170
+ return (
171
+ spawnSync(
172
+ 'xcrun',
173
+ [
174
+ 'devicectl',
175
+ 'device',
176
+ 'copy',
177
+ 'from',
178
+ '--device',
179
+ device,
180
+ '--domain-type',
181
+ domain,
182
+ ...(bundleId ? ['--domain-identifier', bundleId] : []),
183
+ '--source',
184
+ source,
185
+ '--destination',
186
+ destination,
187
+ '--timeout',
188
+ '8',
189
+ ],
190
+ { stdio: 'ignore', timeout: 10_000 },
191
+ ).status === 0
192
+ )
193
+ }
194
+
195
+ async function liveReport(target: Target, seconds: number, scratch: string) {
196
+ const id = randomUUID()
197
+ const durationMs = Math.round(seconds * 1000)
198
+ let raw: string
199
+ if (target.kind === 'simulator') {
200
+ raw = await requestSimulatorProfile(
201
+ target.device,
202
+ target.bundleId,
203
+ {
204
+ id,
205
+ action: 'capture',
206
+ durationMs,
207
+ sampleJs: true,
208
+ react: true,
209
+ diagnose: true,
210
+ },
211
+ durationMs + 10_000,
212
+ )
213
+ } else {
214
+ execFileSync(
215
+ 'xcrun',
216
+ [
217
+ 'devicectl',
218
+ 'device',
219
+ 'process',
220
+ 'launch',
221
+ '--device',
222
+ target.device,
223
+ target.bundleId,
224
+ '--payload-url',
225
+ `one://__one_profiler/capture?id=${id}&durationMs=${durationMs}&diagnose=1`,
226
+ ],
227
+ { stdio: ['ignore', 'pipe', 'pipe'], timeout: 20_000 },
228
+ )
229
+ await setTimeout(durationMs + 1500)
230
+ const result = `result-${id}.json`
231
+ const local = join(scratch, result)
232
+ if (
233
+ !copyDeviceFile(
234
+ target.device,
235
+ 'appDataContainer',
236
+ `${profilerDirectory}/${result}`,
237
+ local,
238
+ target.bundleId,
239
+ )
240
+ )
241
+ throw new Error(
242
+ 'The iPhone profiler response could not be read. Use a development-signed app with accessible app data or pass --telemetry.',
243
+ )
244
+ raw = readFileSync(local, 'utf8')
245
+ }
246
+ const { ok, report, error } = parseReportEnvelope(raw)
247
+ if (!ok || !report) throw new Error(error || 'The profiler returned no capture.')
248
+ return report
249
+ }
250
+
251
+ function artifactRoots(input: string | undefined): string[] {
252
+ const cwd = process.cwd()
253
+ const roots = new Set([...(input ? [dirname(resolve(input))] : []), cwd])
254
+ for (let dir = cwd; ; dir = dirname(dir)) {
255
+ roots.add(join(dir, '.one/native'))
256
+ roots.add(join(dir, 'scripts/tmp/peach-core-closure'))
257
+ if (dirname(dir) === dir) break
258
+ }
259
+ for (const dir of ['build', 'dist', 'out']) roots.add(join(cwd, dir))
260
+ if (process.env.PEACH_CLOSURE_OUT) roots.add(resolve(process.env.PEACH_CLOSURE_OUT))
261
+ return [...roots].filter((path) =>
262
+ statSync(path, { throwIfNoEntry: false })?.isDirectory(),
263
+ )
264
+ }
265
+
266
+ function artifactDirectories(roots: string[]): string[] {
267
+ return [
268
+ ...new Set(
269
+ roots.flatMap((root) => [
270
+ root,
271
+ join(root, 'ios'),
272
+ join(root, 'ios-simulator'),
273
+ ...readdirSync(root, { withFileTypes: true })
274
+ .filter((entry) => entry.isDirectory() && entry.name.endsWith('.xcarchive'))
275
+ .map((entry) => join(root, entry.name)),
276
+ ]),
277
+ ),
278
+ ].filter((path) => statSync(path, { throwIfNoEntry: false })?.isDirectory())
279
+ }
280
+
281
+ function findSourceMaps(directories: string[], uuid: string) {
282
+ const names = [
283
+ `OneJavaScriptSourceMaps-${uuid.toUpperCase()}.json`,
284
+ `OneJavaScriptSourceMaps-${uuid.toLowerCase()}.json`,
285
+ ]
286
+ for (const directory of directories)
287
+ for (const name of names) {
288
+ const path = join(directory, name)
289
+ if (existsSync(path)) return path
290
+ }
291
+ return process.platform === 'darwin'
292
+ ? spawnSync('mdfind', ['-name', names[0]!], { encoding: 'utf8', timeout: 5000 })
293
+ .stdout?.split('\n')
294
+ .find((path) => names.includes(basename(path)) && existsSync(path))
295
+ : undefined
296
+ }
297
+
298
+ function crashReport(raw: string, target: Target, cutoff: number): Incident | undefined {
299
+ const split = raw.indexOf('\n')
300
+ if (split < 0) return
301
+ try {
302
+ const header = record(JSON.parse(raw.slice(0, split)))
303
+ if (header?.bundleID !== target.bundleId) return
304
+ const at = Date.parse(asStr(header.timestamp))
305
+ if (!Number.isFinite(at) || at < cutoff) return
306
+ const details = record(JSON.parse(raw.slice(split + 1)))
307
+ const path = asStr(details?.procPath)
308
+ if (
309
+ target.kind === 'simulator' &&
310
+ path.includes('/CoreSimulator/Devices/') &&
311
+ !path.includes(`/${target.device}/`)
312
+ )
313
+ return
314
+ const exception = record(details?.exception)
315
+ return {
316
+ at,
317
+ summary:
318
+ [asStr(exception?.type), asStr(exception?.signal)].filter(Boolean).join(' ') ||
319
+ 'App crashed',
320
+ }
321
+ } catch {
322
+ return
323
+ }
324
+ }
325
+
326
+ function recentCrashes(target: Target, cutoff: number, scratch: string) {
327
+ const incidents: Incident[] = []
328
+ const read = (file: string) => {
329
+ if ((statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0) < cutoff) return
330
+ const incident = crashReport(readFileSync(file, 'utf8'), target, cutoff)
331
+ if (incident) incidents.push(incident)
332
+ }
333
+ if (target.kind === 'simulator') {
334
+ const logs = join(homedir(), 'Library/Logs')
335
+ const directories = [
336
+ join(logs, 'DiagnosticReports'),
337
+ join(logs, 'CoreSimulator', target.device, 'CrashReporter', 'DiagnosticLogs'),
338
+ ]
339
+ for (const directory of directories) {
340
+ if (!existsSync(directory)) continue
341
+ for (const entry of readdirSync(directory, { withFileTypes: true }))
342
+ if (
343
+ entry.isFile() &&
344
+ entry.name.startsWith(target.executable + '-') &&
345
+ entry.name.endsWith('.ips')
346
+ )
347
+ read(join(directory, entry.name))
348
+ }
349
+ return { checked: true, incidents }
350
+ }
351
+ const result = deviceQuery([
352
+ 'device',
353
+ 'info',
354
+ 'files',
355
+ '--device',
356
+ target.device,
357
+ '--domain-type',
358
+ 'systemCrashLogs',
359
+ '--no-recurse',
360
+ ])
361
+ if (!Array.isArray(result?.files)) return { checked: false, incidents }
362
+ const names = records(result.files)
363
+ .map((file) => asStr(file.relativePath) || asStr(file.name))
364
+ .filter((name) => name.startsWith(target.executable + '-') && name.endsWith('.ips'))
365
+ .sort()
366
+ .reverse()
367
+ .slice(0, 10)
368
+ let checked = true
369
+ for (const name of names) {
370
+ const local = join(scratch, basename(name))
371
+ if (copyDeviceFile(target.device, 'systemCrashLogs', name, local)) read(local)
372
+ else checked = false
373
+ }
374
+ return { checked, incidents }
375
+ }
376
+
377
+ function readTelemetry(file: string) {
378
+ const reports: { report: NativeProfileReport; at: number }[] = []
379
+ const incidents: Incident[] = []
380
+ for (const [index, line] of readFileSync(file, 'utf8').split('\n').entries()) {
381
+ if (!line.trim()) continue
382
+ let row: Row | undefined
383
+ try {
384
+ row = record(JSON.parse(line))
385
+ } catch {
386
+ throw new Error(`Invalid JSON in ${file} at line ${index + 1}.`)
387
+ }
388
+ if (!row) continue
389
+ const details = record(row.details) ?? row
390
+ const name = asStr(row.name)
391
+ const at = asNum(row.tsMs) || Date.parse(asStr(row.utc) || asStr(row.timestamp))
392
+ if (
393
+ profileUUID.test(asStr(details.executableUUID)) &&
394
+ (name === 'perf.one_profiler' || 'spans' in details || 'worstStall' in details)
395
+ ) {
396
+ const report = parseNativeReport(details)!
397
+ if (!report.budget && Array.isArray(details.alarms))
398
+ report.budget = { alarms: details.alarms }
399
+ reports.push({
400
+ report,
401
+ at: report.startWallMs ? report.startWallMs + report.durationMs : at,
402
+ })
403
+ } else if (
404
+ Number.isFinite(at) &&
405
+ /(?:^|[._-])(?:crash|error|fatal)(?:$|[._-])/i.test(name)
406
+ ) {
407
+ incidents.push({
408
+ at,
409
+ summary: [name, asStr(details.message).split('\n', 1)[0]?.slice(0, 160)]
410
+ .filter(Boolean)
411
+ .join(' '),
412
+ })
413
+ }
414
+ }
415
+ if (!reports.length) throw new Error(`No One profiler snapshots found in ${file}.`)
416
+ return { reports, incidents }
417
+ }
418
+
419
+ function spanRates(reports: NativeProfileReport[]) {
420
+ const groups = new Map<
421
+ string,
422
+ {
423
+ route: string
424
+ target: string
425
+ duration: number
426
+ busy: number
427
+ frames: number
428
+ frameDuration: number
429
+ }
430
+ >()
431
+ for (const report of reports) {
432
+ for (const span of report.spans) {
433
+ const kind = asStr(span.kind)
434
+ const duration = asNum(span.durationMs)
435
+ if ((kind !== 'scroll' && kind !== 'idle') || duration <= 0) continue
436
+ const route = asStr(span.route) || report.route || 'unknown'
437
+ const target = kind === 'scroll' ? asStr(span.target) || route : ''
438
+ const key = JSON.stringify([route, target])
439
+ const group = groups.get(key) ?? {
440
+ route,
441
+ target,
442
+ duration: 0,
443
+ busy: 0,
444
+ frames: 0,
445
+ frameDuration: 0,
446
+ }
447
+ group.duration += duration
448
+ group.busy += asNum(span.mainThreadBusyMs)
449
+ const frames = asNum(span.frames)
450
+ const fps = asNum(span.fps)
451
+ if (frames > 0 && fps > 0) {
452
+ group.frames += frames
453
+ group.frameDuration += frames / fps
454
+ }
455
+ groups.set(key, group)
456
+ }
457
+ }
458
+ return [...groups.values()].map(
459
+ ({ route, target, duration, busy, frames, frameDuration }) => ({
460
+ route,
461
+ target,
462
+ busyMsPerSec: (busy * 1000) / duration,
463
+ fps: frameDuration > 0 ? frames / frameDuration : null,
464
+ }),
465
+ )
466
+ }
467
+
468
+ function summarize(reports: NativeProfileReport[]) {
469
+ const rates = spanRates(reports)
470
+ const idle = rates.filter((rate) => !rate.target)
471
+ let idleSeconds = 0
472
+ let idleBusyMs = 0
473
+ const alarms = new Map<string, { title: string; detail: string; windows: number }>()
474
+ for (const report of reports) {
475
+ const state = record(report.budget?.idle)
476
+ const seconds = asNum(state?.seconds)
477
+ idleSeconds += seconds
478
+ idleBusyMs += seconds * asNum(state?.busyMsPerSec)
479
+ for (const alarm of records(report.budget?.alarms)) {
480
+ const kind = asStr(alarm.kind)
481
+ if (!kind) continue
482
+ alarms.set(kind, {
483
+ title: asStr(alarm.title) || kind,
484
+ detail: asStr(alarm.detail),
485
+ windows: (alarms.get(kind)?.windows ?? 0) + 1,
486
+ })
487
+ }
488
+ }
489
+ const byDuration = (a: Row, b: Row) => asNum(b.durationMs) - asNum(a.durationMs)
490
+ return {
491
+ scroll: rates.filter((rate) => rate.target),
492
+ idle,
493
+ idleBusyMsPerSec: idleSeconds > 0 ? idleBusyMs / idleSeconds : null,
494
+ budgetWindows: reports.filter((report) => Array.isArray(report.budget?.alarms))
495
+ .length,
496
+ alarms: [...alarms.values()],
497
+ stallCount: reports.reduce((sum, report) => sum + report.turnsOver16ms, 0),
498
+ stalls: reports
499
+ .map((report) => report.worstStall)
500
+ .filter(isRecord)
501
+ .sort(byDuration)
502
+ .slice(0, 3),
503
+ slowBridgeCount: reports.reduce((sum, report) => sum + report.slowBridgeTotal, 0),
504
+ slowBridgeCalls: reports
505
+ .flatMap((report) => report.slowBridgeCalls)
506
+ .sort((a, b) => byDuration(a, b) || asNum(b.bytes) - asNum(a.bytes))
507
+ .slice(0, 3),
508
+ }
509
+ }
510
+
511
+ function printDiagnosis(result: {
512
+ source: string
513
+ captureError?: string
514
+ performance: ReturnType<typeof summarize>
515
+ crashes: ReturnType<typeof recentCrashes>
516
+ missingSymbols: string[]
517
+ }) {
518
+ const { performance: perf, crashes } = result
519
+ const lines = [`One diagnostics for ${result.source}`]
520
+ if (result.captureError) {
521
+ lines.push(`Capture failed. ${result.captureError}`)
522
+ } else {
523
+ const rate = (busy: number) => `${busy.toFixed(1)} ms/s busy`
524
+ const fps = (value: number | null) =>
525
+ value === null ? '' : `${value.toFixed(1)} FPS, `
526
+ for (const scroll of perf.scroll) {
527
+ const idle = perf.idle.find((row) => row.route === scroll.route)
528
+ const comparison = idle ? ` · idle ${fps(idle.fps)}${rate(idle.busyMsPerSec)}` : ''
529
+ lines.push(
530
+ ` ${scroll.route} · ${scroll.target} scroll ${fps(scroll.fps)}${rate(scroll.busyMsPerSec)}${comparison}`,
531
+ )
532
+ }
533
+ if (!perf.scroll.length) lines.push(' No completed scrolls in this window.')
534
+ for (const idle of perf.idle)
535
+ if (!perf.scroll.some((scroll) => scroll.route === idle.route))
536
+ lines.push(` ${idle.route} idle ${fps(idle.fps)}${rate(idle.busyMsPerSec)}`)
537
+ if (perf.idleBusyMsPerSec !== null)
538
+ lines.push(` Idle across the capture averaged ${rate(perf.idleBusyMsPerSec)}.`)
539
+ lines.push('')
540
+ if (perf.alarms.length) {
541
+ lines.push('Budget alarms')
542
+ for (const alarm of perf.alarms) lines.push(` ${alarm.title} · ${alarm.detail}`)
543
+ } else {
544
+ lines.push(perf.budgetWindows ? 'No budget alarms.' : 'Budget data unavailable.')
545
+ }
546
+ const frames = (row: Row) => {
547
+ const stack = Array.isArray(row.stack)
548
+ ? row.stack.filter((frame): frame is string => typeof frame === 'string')
549
+ : []
550
+ const indexes = new Set(
551
+ stack
552
+ .slice(-3)
553
+ .map((_, index) => stack.length - 3 + index)
554
+ .filter((index) => index >= 0),
555
+ )
556
+ for (const layer of ['JS:', 'Bridge:', 'Native:']) {
557
+ const index = stack.findLastIndex((frame) => frame.startsWith(layer))
558
+ if (index >= 0) indexes.add(index)
559
+ }
560
+ for (const index of [...indexes].sort((a, b) => a - b))
561
+ lines.push(` ${stack[index]}`)
562
+ }
563
+ if (perf.stalls.length) {
564
+ lines.push(
565
+ '',
566
+ perf.stallCount
567
+ ? `Longest stalls (${perf.stallCount} turns over 16 ms)`
568
+ : 'Longest stalls',
569
+ )
570
+ for (const stall of perf.stalls) {
571
+ lines.push(
572
+ ` ${asNum(stall.durationMs).toFixed(1)} ms in ${asStr(stall.phase) || 'unknown phase'} on ${asStr(stall.route) || 'unknown route'}`,
573
+ )
574
+ frames(stall)
575
+ }
576
+ } else {
577
+ lines.push('No main-thread stalls recorded.')
578
+ }
579
+ if (perf.slowBridgeCalls.length) {
580
+ lines.push(
581
+ '',
582
+ `Slow bridge calls (${Math.max(perf.slowBridgeCount, perf.slowBridgeCalls.length)} recorded)`,
583
+ )
584
+ for (const call of perf.slowBridgeCalls)
585
+ lines.push(
586
+ ` ${asStr(call.op)} took ${asNum(call.durationMs).toFixed(1)} ms and moved ${(asNum(call.bytes) / 1024).toFixed(1)} KB on ${asStr(call.route) || 'unknown route'}`,
587
+ )
588
+ } else {
589
+ lines.push('No slow bridge calls recorded.')
590
+ }
591
+ }
592
+ if (crashes.incidents.length) {
593
+ lines.push('', 'Recent crashes and errors')
594
+ for (const incident of crashes.incidents.slice(0, 3))
595
+ lines.push(` ${new Date(incident.at).toISOString()} · ${incident.summary}`)
596
+ } else {
597
+ lines.push(
598
+ crashes.checked ? 'No recent crashes or errors found.' : 'Crash logs unavailable.',
599
+ )
600
+ }
601
+ for (const missing of result.missingSymbols) lines.push(missing)
602
+ console.log(lines.join('\n'))
603
+ }
604
+
605
+ function seconds(value: string, flag: string): number {
606
+ const match = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(value)
607
+ const scale = new Map([
608
+ ['m', 60],
609
+ ['h', 3600],
610
+ ['d', 86400],
611
+ ])
612
+ const parsed = Number(match?.[1]) * (scale.get(match?.[2] ?? '') ?? 1)
613
+ if (!Number.isFinite(parsed) || parsed <= 0)
614
+ throw new Error(`${flag} requires a positive duration, such as 10s.`)
615
+ return parsed
616
+ }
617
+
618
+ export async function runDiagnoseNative(args: string[]): Promise<number> {
619
+ const { values } = parseArgs({
620
+ args,
621
+ options: {
622
+ telemetry: { type: 'string' },
623
+ since: { type: 'string' },
624
+ capture: { type: 'string' },
625
+ json: { type: 'boolean' },
626
+ help: { type: 'boolean', short: 'h' },
627
+ },
628
+ })
629
+ if (values.help) {
630
+ console.log(`Usage: one diagnose [--telemetry <jsonl> | --capture <seconds>] [--since <duration>] [--json]
631
+
632
+ Without flags, sample a running One iOS app for six seconds.
633
+ --since limits saved telemetry or live crash logs (for example, 30m).`)
634
+ return 0
635
+ }
636
+ if (values.telemetry !== undefined && values.capture !== undefined)
637
+ throw new Error(
638
+ '--capture applies to a running app. Use --telemetry on its own to read saved data.',
639
+ )
640
+ const lookbackMs =
641
+ values.since === undefined ? undefined : seconds(values.since, '--since') * 1000
642
+ const duration = values.capture === undefined ? 6 : seconds(values.capture, '--capture')
643
+ if (duration * 1000 > 2_147_000_000 || duration * 1000 < 1)
644
+ throw new Error('--capture duration is outside the supported range.')
645
+ const reports: NativeProfileReport[] = []
646
+ let source: string
647
+ let captureError: string | undefined
648
+ let crashes: ReturnType<typeof recentCrashes>
649
+ const directories = artifactDirectories(artifactRoots(values.telemetry))
650
+ if (values.telemetry !== undefined) {
651
+ source = basename(values.telemetry)
652
+ const telemetry = readTelemetry(values.telemetry)
653
+ const end = telemetry.reports.reduce(
654
+ (latest, row) => Math.max(latest, row.at || 0),
655
+ 0,
656
+ )
657
+ if (lookbackMs !== undefined && !end)
658
+ throw new Error('--since requires timestamps in the saved telemetry.')
659
+ const cutoff = lookbackMs === undefined ? -Infinity : end - lookbackMs
660
+ for (const row of telemetry.reports.sort((a, b) => a.at - b.at))
661
+ if (row.at >= cutoff || (lookbackMs === undefined && !Number.isFinite(row.at)))
662
+ reports.push(row.report)
663
+ crashes = {
664
+ checked: true,
665
+ incidents: telemetry.incidents.filter((incident) => incident.at >= cutoff),
666
+ }
667
+ } else {
668
+ const target = runningTarget(directories)
669
+ source = `${target.bundleId} on ${target.name}`
670
+ const scratch = mkdtempSync(join(tmpdir(), 'one-diagnose-'))
671
+ try {
672
+ try {
673
+ reports.push(await liveReport(target, duration, scratch))
674
+ } catch (error) {
675
+ captureError =
676
+ error instanceof Error ? error.message.split('\n')[0] : String(error)
677
+ }
678
+ try {
679
+ crashes = recentCrashes(target, Date.now() - (lookbackMs ?? 86_400_000), scratch)
680
+ } catch {
681
+ crashes = { checked: false, incidents: [] }
682
+ }
683
+ } finally {
684
+ rmSync(scratch, { recursive: true, force: true })
685
+ }
686
+ }
687
+
688
+ const groups = new Map<string, NativeProfileReport[]>()
689
+ for (const report of reports) {
690
+ const uuid = report.executableUUID.toUpperCase()
691
+ const group = groups.get(uuid) ?? []
692
+ group.push(report)
693
+ groups.set(uuid, group)
694
+ }
695
+ const missingSymbols: string[] = []
696
+ for (const [uuid, group] of groups) {
697
+ if (!profileUUID.test(uuid)) continue
698
+ const path = findSourceMaps(directories, uuid)
699
+ const symbols = symbolicateDiagnosticReports(group, uuid, path, directories)
700
+ const missing = [!path && 'JavaScript source maps', !symbols && 'dSYM'].filter(
701
+ Boolean,
702
+ )
703
+ if (missing.length)
704
+ missingSymbols.push(`Missing ${missing.join(' and ')} for ${uuid}.`)
705
+ }
706
+ crashes.incidents.sort((a, b) => b.at - a.at)
707
+ const result = {
708
+ source,
709
+ captureError,
710
+ performance: summarize(reports),
711
+ crashes,
712
+ missingSymbols,
713
+ }
714
+ if (values.json) console.log(JSON.stringify(result, null, 2))
715
+ else printDiagnosis(result)
716
+ return captureError ? 1 : 0
717
+ }