peachsim 0.1.2430 → 0.1.2431

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 (104) hide show
  1. package/cli/commands/preview.ts +2 -1
  2. package/cli/outbound-endpoints.ts +10 -2
  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 +1 -1
  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 +1 -1
  13. package/dist-lib/bridge-contract.cjs +1 -1
  14. package/dist-lib/bridge-contract.mjs +1 -1
  15. package/dist-lib/bundle-channel.cjs +15765 -5973
  16. package/dist-lib/capture-contract.cjs +1 -1
  17. package/dist-lib/capture-contract.mjs +1 -1
  18. package/dist-lib/cloud-contract.cjs +1 -1
  19. package/dist-lib/cloud-contract.mjs +1 -1
  20. package/dist-lib/cloud-test-args.cjs +1 -1
  21. package/dist-lib/cloud-test-args.mjs +1 -1
  22. package/dist-lib/cloud.cjs +1 -1
  23. package/dist-lib/cloud.mjs +1 -1
  24. package/dist-lib/config.cjs +1 -1
  25. package/dist-lib/config.mjs +1 -1
  26. package/dist-lib/detox/index.cjs +1 -1
  27. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  28. package/dist-lib/expo-swift-bundle.cjs +14638 -4888
  29. package/dist-lib/expo-swift-metadata.cjs +1 -1
  30. package/dist-lib/expo-swift-metadata.mjs +1 -1
  31. package/dist-lib/home-paths.cjs +1 -1
  32. package/dist-lib/host/bridge-host.cjs +15464 -5754
  33. package/dist-lib/host/fetch-proxy-handler.cjs +3204 -54
  34. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  35. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  36. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  37. package/dist-lib/host/websocket-proxy.cjs +1 -1
  38. package/dist-lib/index.cjs +3541 -391
  39. package/dist-lib/jump-to-source-babel.cjs +1 -1
  40. package/dist-lib/jump-to-source-native.cjs +1 -1
  41. package/dist-lib/kotlin-host.cjs +1 -1
  42. package/dist-lib/menu.cjs +1 -1
  43. package/dist-lib/menu.mjs +1 -1
  44. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  46. package/dist-lib/metro-production-bundle.cjs +1 -1
  47. package/dist-lib/metro-production-bundle.mjs +1 -1
  48. package/dist-lib/metro.cjs +3437 -287
  49. package/dist-lib/native-app-identity-project.cjs +2 -2
  50. package/dist-lib/native-app-identity-project.mjs +2 -2
  51. package/dist-lib/native-app-identity.cjs +1 -1
  52. package/dist-lib/native-app-identity.mjs +1 -1
  53. package/dist-lib/native-firebase-metadata.cjs +1 -1
  54. package/dist-lib/native-firebase-metadata.mjs +1 -1
  55. package/dist-lib/pdfium-raster.cjs +1 -1
  56. package/dist-lib/pdfium-raster.mjs +1 -1
  57. package/dist-lib/plist.cjs +1 -1
  58. package/dist-lib/plist.mjs +1 -1
  59. package/dist-lib/profiles.cjs +1 -1
  60. package/dist-lib/public-brand.cjs +1 -1
  61. package/dist-lib/public-origins-lib-esm.json +24 -24
  62. package/dist-lib/public-origins-lib.json +172 -79
  63. package/dist-lib/react-native-host-modules.cjs +1 -1
  64. package/dist-lib/react-native-host-modules.mjs +1 -1
  65. package/dist-lib/reap-browser.cjs +1 -1
  66. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  67. package/dist-lib/sdk.cjs +1 -1
  68. package/dist-lib/sdk.mjs +1 -1
  69. package/dist-lib/skills.cjs +16782 -6989
  70. package/dist-lib/swift-compile.cjs +2 -2
  71. package/dist-lib/swift-compile.mjs +2 -2
  72. package/dist-lib/swift-package.cjs +1 -1
  73. package/dist-lib/swift-package.mjs +1 -1
  74. package/dist-lib/swift-submit.cjs +1 -1
  75. package/dist-lib/swift-submit.mjs +1 -1
  76. package/dist-lib/swift-toolchain.cjs +1 -1
  77. package/dist-lib/swift.cjs +1 -1
  78. package/dist-lib/vite-swift.cjs +74 -6
  79. package/dist-lib/vite.cjs +3331 -181
  80. package/dist-lib/worklet-executable.cjs +1 -1
  81. package/dist-lib/worklet-executable.mjs +1 -1
  82. package/package.json +1 -1
  83. package/src/expo-native-workspace.ts +23 -63
  84. package/src/pbx-table.ts +200 -0
  85. package/src/pod-sources.ts +628 -0
  86. package/src/podfile-cocoapods.ts +40 -3
  87. package/src/pods-analysis.ts +488 -0
  88. package/src/pods-build-settings.ts +1015 -0
  89. package/src/pods-files.ts +478 -0
  90. package/src/pods-install.ts +475 -0
  91. package/src/pods-integration.ts +778 -0
  92. package/src/pods-post-install.ts +1811 -0
  93. package/src/pods-project.ts +2416 -0
  94. package/src/pods-scripts.ts +409 -0
  95. package/src/pods-targets.ts +757 -0
  96. package/src/pods-xcconfig.ts +198 -0
  97. package/src/podspec-cocoapods.ts +29 -3
  98. package/src/podspec-ruby-stdlib.ts +111 -10
  99. package/src/podspec-ruby.ts +52 -8
  100. package/src/swift-catalog-png.ts +75 -0
  101. package/src/swift-host.ts +4 -3
  102. package/src/swift-root-lock.ts +0 -10
  103. package/src/swift-source-pods.ts +29 -73
  104. package/src/turbo-source.ts +16 -37
@@ -0,0 +1,628 @@
1
+ // a resolved pod's sources as `pod install` leaves them: cocoapods-downloader
2
+ // 2.1 fetches the source into a scratch directory, then CocoaPods 1.17's
3
+ // Downloader::Cache#copy_and_clean drops .git, runs the prepare_command and
4
+ // removes every file no subspec on any platform uses (Sandbox::PodDirCleaner).
5
+ import { spawn } from 'node:child_process'
6
+ import { createHash, randomUUID } from 'node:crypto'
7
+ import fs from 'node:fs'
8
+ import os from 'node:os'
9
+ import path from 'node:path'
10
+ import { rnxHomeDir } from './home-paths'
11
+
12
+ const COCOAPODS_VERSION = '1.17.0'
13
+ // Http#user_agent_argument passes curl the single argument "-A '<agent>'", so
14
+ // the quotes reach the wire
15
+ const USER_AGENT = `'CocoaPods/${COCOAPODS_VERSION} cocoapods-downloader/2.1'`
16
+ const PLATFORMS = ['osx', 'ios', 'tvos', 'visionos', 'watchos']
17
+ const HEADER_EXTENSIONS = [
18
+ '.h',
19
+ '.hh',
20
+ '.hpp',
21
+ '.ipp',
22
+ '.tpp',
23
+ '.hxx',
24
+ '.def',
25
+ '.inl',
26
+ '.inc',
27
+ ]
28
+ const SOURCE_EXTENSIONS = [
29
+ '.m',
30
+ '.mm',
31
+ '.i',
32
+ '.c',
33
+ '.cc',
34
+ '.cxx',
35
+ '.cpp',
36
+ '.c++',
37
+ '.swift',
38
+ ...HEADER_EXTENSIONS,
39
+ ]
40
+ const SOURCE_FILES_PATTERN = `*{${SOURCE_EXTENSIONS.join(',')}}`
41
+ const STRATEGIES = ['git', 'hg', 'http', 'scp', 'svn']
42
+ const OPTIONS: Record<string, string[]> = {
43
+ git: ['commit', 'tag', 'branch', 'submodules'],
44
+ http: ['type', 'flatten', 'sha1', 'sha256', 'headers'],
45
+ }
46
+ const ARCHIVE_TYPES = ['zip', 'tgz', 'tar', 'tbz', 'txz', 'dmg']
47
+
48
+ type Json = Record<string, unknown>
49
+
50
+ const object = (value: unknown): value is Json =>
51
+ typeof value === 'object' && value !== null && !Array.isArray(value)
52
+
53
+ export async function podSourceRoot(spec: Json): Promise<string> {
54
+ const name = String(spec.name)
55
+ const source = spec.source
56
+ if (!object(source)) throw new Error(`${name}: the podspec has no source`)
57
+ const strategies = STRATEGIES.filter((key) => key in source)
58
+ if (strategies.length !== 1)
59
+ throw new Error(`${name}: unsupported download strategy ${JSON.stringify(source)}`)
60
+ const strategy = strategies[0]!
61
+ const allowed = OPTIONS[strategy]
62
+ if (!allowed)
63
+ throw new Error(`${name}: Peach fetches :git and :http pod sources, not :${strategy}`)
64
+ const url = String(source[strategy])
65
+ const options: Json = Object.fromEntries(
66
+ Object.entries(source).filter(([key]) => key !== strategy),
67
+ )
68
+ const unrecognized = Object.keys(options).filter((key) => !allowed.includes(key))
69
+ if (unrecognized.length > 0)
70
+ throw new Error(
71
+ `${name}: unrecognized ${strategy} source options ${unrecognized.join(', ')}`,
72
+ )
73
+
74
+ const base = path.join(rnxHomeDir(), 'pod-sources')
75
+ const digest = createHash('sha256')
76
+ .update(canonicalJson(source))
77
+ .digest('hex')
78
+ .slice(0, 16)
79
+ const root = path.join(base, name, `${String(spec.version)}-${digest}`)
80
+ if (fs.existsSync(root)) return root
81
+ const stage = path.join(base, '.staging', randomUUID())
82
+ fs.mkdirSync(stage, { recursive: true })
83
+ try {
84
+ if (strategy === 'git') await downloadGit(name, url, options, stage)
85
+ else await downloadHttp(name, url, options, stage)
86
+ removeGitEntries(stage)
87
+ await prepare(name, spec, stage)
88
+ clean(spec, stage, platformNames)
89
+ fs.mkdirSync(path.dirname(root), { recursive: true })
90
+ publish(stage, root)
91
+ } finally {
92
+ fs.rmSync(stage, { recursive: true, force: true })
93
+ }
94
+ return root
95
+ }
96
+
97
+ function canonicalJson(value: unknown): string {
98
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
99
+ if (object(value))
100
+ return `{${Object.keys(value)
101
+ .sort()
102
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
103
+ .join(',')}}`
104
+ return JSON.stringify(value)
105
+ }
106
+
107
+ function publish(stage: string, root: string) {
108
+ try {
109
+ fs.renameSync(stage, root)
110
+ } catch (error) {
111
+ // another process published the same pod first
112
+ if (fs.existsSync(root)) return
113
+ throw error
114
+ }
115
+ }
116
+
117
+ function run(
118
+ pod: string,
119
+ command: string,
120
+ args: string[],
121
+ { label, ...options }: { label?: string; cwd?: string; env?: NodeJS.ProcessEnv } = {},
122
+ ): Promise<string> {
123
+ return new Promise((resolve, reject) => {
124
+ const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] })
125
+ const stdout: Buffer[] = []
126
+ const stderr: Buffer[] = []
127
+ child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk))
128
+ child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk))
129
+ child.on('error', reject)
130
+ child.on('close', (code) => {
131
+ const output = Buffer.concat([...stdout, ...stderr]).toString()
132
+ if (code === 0) resolve(output)
133
+ else
134
+ reject(
135
+ new Error(
136
+ `${pod}: ${label ?? [command, ...args].join(' ')} exited ${code}\n${output.slice(-8000)}`,
137
+ ),
138
+ )
139
+ })
140
+ })
141
+ }
142
+
143
+ async function downloadGit(pod: string, url: string, options: Json, target: string) {
144
+ const text = (key: string) => (options[key] == null ? undefined : String(options[key]))
145
+ let branch = text('branch')
146
+ let commit = text('commit')
147
+ const tag = text('tag')
148
+ for (const value of [url, branch, commit, tag])
149
+ if (value?.startsWith('--') || value?.includes(' --'))
150
+ throw new Error(`${pod}: unsafe git source input ${JSON.stringify(options)}`)
151
+ if (branch) {
152
+ // Git.preprocess_options pins a branch to the commit it names now
153
+ const output = await run(pod, 'git', ['ls-remote', '--', url, branch])
154
+ const match = new RegExp(
155
+ `([a-z0-9]*)\\trefs/(heads|tags)/${branch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`,
156
+ ).exec(output)
157
+ if (match) {
158
+ commit = match[1]
159
+ branch = undefined
160
+ }
161
+ }
162
+ const submodules = async () => {
163
+ if (options.submodules)
164
+ await run(pod, 'git', [
165
+ '-C',
166
+ target,
167
+ 'submodule',
168
+ 'update',
169
+ '--init',
170
+ '--recursive',
171
+ ])
172
+ }
173
+ const clone = async (shallow: boolean): Promise<void> => {
174
+ const args = ['clone', url, target, '--template=']
175
+ if (shallow && !commit) args.push('--single-branch', '--depth', '1')
176
+ const ref = tag ?? branch
177
+ if (ref) args.push('--branch', ref)
178
+ const cloned = await run(pod, 'git', args).then(
179
+ () => true,
180
+ (error: unknown) => {
181
+ if (
182
+ shallow &&
183
+ error instanceof Error &&
184
+ /^fatal:.*does not support (--depth|shallow capabilities)$/im.test(
185
+ error.message,
186
+ )
187
+ )
188
+ return false
189
+ throw error
190
+ },
191
+ )
192
+ if (!cloned) return clone(false)
193
+ await submodules()
194
+ }
195
+ await clone(true)
196
+ if (commit) {
197
+ await run(pod, 'git', ['-C', target, 'checkout', '--quiet', commit])
198
+ await submodules()
199
+ }
200
+ }
201
+
202
+ async function downloadHttp(pod: string, url: string, options: Json, target: string) {
203
+ const type =
204
+ options.type == null ? typeFromUrl(new URL(url).pathname) : String(options.type)
205
+ if (!type || !ARCHIVE_TYPES.includes(type))
206
+ throw new Error(`${pod}: unsupported file type: ${type ?? 'none'} (${url})`)
207
+ if (type === 'dmg')
208
+ throw new Error(`${pod}: Peach does not mount .dmg pod sources (${url})`)
209
+ const archive = path.join(target, `file.${type}`)
210
+ const algorithm = options.sha256 ? 'sha256' : options.sha1 ? 'sha1' : null
211
+ const digest = await downloadFile(
212
+ pod,
213
+ url,
214
+ stringList(options.headers),
215
+ archive,
216
+ algorithm,
217
+ )
218
+ const expected = algorithm ? String(options[algorithm]) : null
219
+ if (expected !== null && digest !== expected)
220
+ throw new Error(
221
+ `${pod}: Verification checksum was incorrect, expected ${expected}, got ${digest}`,
222
+ )
223
+ if (type === 'zip') await run(pod, 'unzip', [archive, '-d', target])
224
+ else await run(pod, 'tar', ['xf', archive, '-C', target])
225
+ const flatten = 'flatten' in options ? Boolean(options.flatten) : type !== 'zip'
226
+ const contents = fs
227
+ .readdirSync(target)
228
+ .filter((entry) => entry !== path.basename(archive))
229
+ if (flatten && contents.length === 1) {
230
+ const entry = path.join(target, contents[0]!)
231
+ if (fs.statSync(entry).isDirectory()) {
232
+ const moved = `${entry}.tmp`
233
+ fs.renameSync(entry, moved)
234
+ for (const child of fs.readdirSync(moved))
235
+ fs.renameSync(path.join(moved, child), path.join(target, child))
236
+ fs.rmSync(moved, { recursive: true, force: true })
237
+ }
238
+ }
239
+ fs.rmSync(archive, { force: true })
240
+ }
241
+
242
+ function typeFromUrl(pathname: string): string | null {
243
+ if (/\.zip$/.test(pathname)) return 'zip'
244
+ if (/\.(tgz|tar\.gz)$/.test(pathname)) return 'tgz'
245
+ if (/\.tar$/.test(pathname)) return 'tar'
246
+ if (/\.(tbz|tar\.bz2)$/.test(pathname)) return 'tbz'
247
+ if (/\.(txz|tar\.xz)$/.test(pathname)) return 'txz'
248
+ if (/\.dmg$/.test(pathname)) return 'dmg'
249
+ return null
250
+ }
251
+
252
+ const RETRY_STATUSES = [408, 429, 500, 502, 503, 504]
253
+
254
+ // curl -f -L --netrc-optional --retry 2, as Http#download_file runs it
255
+ async function downloadFile(
256
+ pod: string,
257
+ url: string,
258
+ headers: string[],
259
+ file: string,
260
+ algorithm: 'sha256' | 'sha1' | null,
261
+ ): Promise<string | null> {
262
+ const request = new Headers({ 'User-Agent': USER_AGENT })
263
+ const credentials = netrcCredentials(new URL(url).hostname)
264
+ if (credentials)
265
+ request.set(
266
+ 'Authorization',
267
+ `Basic ${Buffer.from(`${credentials.login}:${credentials.password}`).toString('base64')}`,
268
+ )
269
+ for (const header of headers) {
270
+ const colon = header.indexOf(':')
271
+ if (colon > 0)
272
+ request.set(header.slice(0, colon).trim(), header.slice(colon + 1).trim())
273
+ }
274
+ let response: Response | null = null
275
+ for (let attempt = 0; attempt <= 2; attempt++) {
276
+ if (attempt > 0)
277
+ await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** (attempt - 1)))
278
+ response = await fetch(url, { headers: request, redirect: 'follow' }).catch(
279
+ (error: unknown) => {
280
+ if (attempt === 2) throw new Error(`${pod}: GET ${url} failed: ${String(error)}`)
281
+ return null
282
+ },
283
+ )
284
+ if (response && !RETRY_STATUSES.includes(response.status)) break
285
+ }
286
+ if (!response?.ok || !response.body)
287
+ throw new Error(`${pod}: GET ${url} failed with HTTP ${response?.status ?? 'error'}`)
288
+ const hash = algorithm ? createHash(algorithm) : null
289
+ const handle = await fs.promises.open(file, 'w')
290
+ try {
291
+ const reader = response.body.getReader()
292
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
293
+ hash?.update(chunk.value)
294
+ await handle.write(chunk.value)
295
+ }
296
+ } finally {
297
+ await handle.close()
298
+ }
299
+ return hash ? hash.digest('hex') : null
300
+ }
301
+
302
+ type NetrcEntry = { machine: string | null; login: string; password: string }
303
+
304
+ function netrcCredentials(host: string): NetrcEntry | null {
305
+ const file = path.join(os.homedir(), '.netrc')
306
+ if (!fs.existsSync(file)) return null
307
+ const tokens = fs.readFileSync(file, 'utf8').split(/\s+/).filter(Boolean)
308
+ let current: NetrcEntry | null = null
309
+ const entries: NetrcEntry[] = []
310
+ for (let i = 0; i < tokens.length; i++) {
311
+ const token = tokens[i]
312
+ if (token === 'machine' || token === 'default') {
313
+ current = {
314
+ machine: token === 'machine' ? (tokens[++i] ?? '') : null,
315
+ login: '',
316
+ password: '',
317
+ }
318
+ entries.push(current)
319
+ } else if (current && token === 'login') current.login = tokens[++i] ?? ''
320
+ else if (current && token === 'password') current.password = tokens[++i] ?? ''
321
+ }
322
+ return (
323
+ entries.find((entry) => entry.machine === host) ??
324
+ entries.find((entry) => entry.machine === null) ??
325
+ null
326
+ )
327
+ }
328
+
329
+ // rsync -a --exclude=.git, which drops every entry named .git at any depth
330
+ function removeGitEntries(directory: string) {
331
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
332
+ const full = path.join(directory, entry.name)
333
+ if (entry.name === '.git') fs.rmSync(full, { recursive: true, force: true })
334
+ else if (entry.isDirectory()) removeGitEntries(full)
335
+ }
336
+ }
337
+
338
+ // ActiveSupport's String#strip_heredoc
339
+ function stripHeredoc(text: string): string {
340
+ const indents = text.match(/^[ \t]*(?=\S)/gm) ?? []
341
+ const indent = indents.length > 0 ? indents.reduce((a, b) => (b < a ? b : a)) : ''
342
+ return indent ? text.replace(new RegExp(`^${indent}`, 'gm'), '') : text
343
+ }
344
+
345
+ const chomp = (text: string) => text.replace(/(\r\n|\r|\n)$/, '')
346
+
347
+ // Installer::PodSourcePreparer#run_prepare_command
348
+ async function prepare(pod: string, spec: Json, directory: string) {
349
+ if (typeof spec.prepare_command !== 'string') return
350
+ const command = chomp(stripHeredoc(chomp(stripHeredoc(spec.prepare_command))))
351
+ const env: NodeJS.ProcessEnv = { ...process.env, COCOAPODS_VERSION }
352
+ delete env.CDPATH
353
+ await run(pod, 'bash', ['-c', `\nset -e\n${command}`], {
354
+ label: 'prepare_command',
355
+ cwd: directory,
356
+ env,
357
+ })
358
+ }
359
+
360
+ type SpecNode = { hash: Json; parent: SpecNode | null; name: string }
361
+
362
+ function specNodes(root: Json): SpecNode[] {
363
+ const nodes: SpecNode[] = []
364
+ const visit = (hash: Json, parent: SpecNode | null) => {
365
+ const node = {
366
+ hash,
367
+ parent,
368
+ name: parent ? `${parent.name}/${String(hash.name)}` : String(hash.name),
369
+ }
370
+ nodes.push(node)
371
+ for (const key of ['subspecs', 'testspecs', 'appspecs'])
372
+ for (const child of Array.isArray(hash[key]) ? hash[key] : [])
373
+ if (object(child)) visit(child, node)
374
+ }
375
+ visit(root, null)
376
+ return nodes
377
+ }
378
+
379
+ function platformNames(node: SpecNode): string[] {
380
+ const platforms = node.hash.platforms
381
+ const names =
382
+ typeof platforms === 'string'
383
+ ? [platforms]
384
+ : Array.isArray(platforms)
385
+ ? platforms.map(String)
386
+ : object(platforms)
387
+ ? Object.keys(platforms)
388
+ : []
389
+ if (names.length > 0) return names
390
+ return node.parent ? platformNames(node.parent) : PLATFORMS
391
+ }
392
+
393
+ const stringList = (value: unknown): string[] =>
394
+ value == null
395
+ ? []
396
+ : Array.isArray(value)
397
+ ? value.filter((v) => v != null).map(String)
398
+ : [String(value)]
399
+
400
+ // Specification::Consumer#value_for_attribute for the attributes FileAccessor reads
401
+ function listValue(node: SpecNode, platform: string, attribute: string): string[] {
402
+ const own = (hash: Json) => stringList(hash[attribute])
403
+ const platformHash = node.hash[platform]
404
+ return [...own(node.hash), ...(object(platformHash) ? own(platformHash) : [])]
405
+ }
406
+
407
+ function bundleValue(node: SpecNode, platform: string, attribute: string): string[][] {
408
+ const bundles = new Map<string, string[]>()
409
+ const platformHash = node.hash[platform]
410
+ for (const hash of [node.hash, object(platformHash) ? platformHash : {}]) {
411
+ const value = hash[attribute]
412
+ if (!object(value)) continue
413
+ for (const [key, patterns] of Object.entries(value)) {
414
+ const paths = object(patterns) ? stringList(patterns.paths) : stringList(patterns)
415
+ bundles.set(key, [...(bundles.get(key) ?? []), ...paths])
416
+ }
417
+ }
418
+ return [...bundles.values()]
419
+ }
420
+
421
+ // a scalar attribute that subspecs inherit (prefix_header_file, module_map)
422
+ function inheritedPath(
423
+ node: SpecNode,
424
+ platform: string,
425
+ attribute: string,
426
+ ): string | null {
427
+ const platformHash = node.hash[platform]
428
+ const value =
429
+ (object(platformHash) ? platformHash[attribute] : undefined) ?? node.hash[attribute]
430
+ if (value != null) return typeof value === 'string' ? value : null
431
+ return node.parent ? inheritedPath(node.parent, platform, attribute) : null
432
+ }
433
+
434
+ type Tree = { files: string[]; dirs: string[]; dirSet: Set<string> }
435
+
436
+ // Sandbox::PathList#read_file_system: **/* with dotfiles, symlinked
437
+ // directories listed but not entered
438
+ function readTree(root: string): Tree {
439
+ const files: string[] = []
440
+ const dirs: string[] = []
441
+ const walk = (relative: string) => {
442
+ for (const entry of fs.readdirSync(path.join(root, relative), {
443
+ withFileTypes: true,
444
+ })) {
445
+ const child = relative ? `${relative}/${entry.name}` : entry.name
446
+ const full = path.join(root, child)
447
+ if (entry.isDirectory()) {
448
+ dirs.push(child)
449
+ walk(child)
450
+ } else if (
451
+ entry.isSymbolicLink() &&
452
+ fs.existsSync(full) &&
453
+ fs.statSync(full).isDirectory()
454
+ )
455
+ dirs.push(child)
456
+ else files.push(child)
457
+ }
458
+ }
459
+ walk('')
460
+ const byUpper = (a: string, b: string) => {
461
+ const x = a.toUpperCase()
462
+ const y = b.toUpperCase()
463
+ return x < y ? -1 : x > y ? 1 : 0
464
+ }
465
+ files.sort(byUpper)
466
+ dirs.sort(byUpper)
467
+ return { files, dirs, dirSet: new Set(dirs.map((dir) => dir.toLowerCase())) }
468
+ }
469
+
470
+ // PathList#dir_glob_equivalent_patterns
471
+ function expandPattern(pattern: string): string[] {
472
+ const expanded = pattern.replaceAll('/**/', '{/**/,/}')
473
+ let patterns = [expanded]
474
+ for (const set of new Set(expanded.match(/\{[^}]*\}/g) ?? [])) {
475
+ const values = set.replace(/[{}]/g, '').split(',')
476
+ while (values.length > 0 && values.at(-1) === '') values.pop()
477
+ patterns = patterns.flatMap((old) =>
478
+ values.map((value) => old.replaceAll(set, value)),
479
+ )
480
+ }
481
+ return patterns
482
+ }
483
+
484
+ // File.fnmatch(pattern, path, File::FNM_CASEFOLD | File::FNM_PATHNAME)
485
+ function fnmatchRegex(pattern: string): RegExp {
486
+ const segments = pattern.split('/')
487
+ let source = ''
488
+ for (let i = 0; i < segments.length; i++) {
489
+ const segment = segments[i]!
490
+ if (segment === '**' && i < segments.length - 1) {
491
+ source += '(?:(?!\\.)[^/]*/)*'
492
+ while (segments[i + 1] === '**' && i + 1 < segments.length - 1) i++
493
+ continue
494
+ }
495
+ const first = segment[0] === '\\' ? segment[1] : segment[0]
496
+ if (first !== '.') source += '(?!\\.)'
497
+ for (let j = 0; j < segment.length; j++) {
498
+ const char = segment[j]!
499
+ if (char === '*') source += '[^/]*'
500
+ else if (char === '?') source += '[^/]'
501
+ else if (char === '\\' && j + 1 < segment.length)
502
+ source += escapeRegex(segment[++j]!)
503
+ else if (char === '[' && bracketEnd(segment, j) > 0) {
504
+ const end = bracketEnd(segment, j)
505
+ const negate = segment[j + 1] === '!' || segment[j + 1] === '^'
506
+ const body = segment.slice(j + (negate ? 2 : 1), end).replace(/[\\^]/g, '\\$&')
507
+ source += `[${negate ? '^/' : ''}${body}]`
508
+ j = end
509
+ } else source += escapeRegex(char)
510
+ }
511
+ if (i < segments.length - 1) source += '/'
512
+ }
513
+ return new RegExp(`^${source}$`, 'i')
514
+ }
515
+
516
+ const bracketEnd = (segment: string, open: number) =>
517
+ segment.indexOf(
518
+ ']',
519
+ segment[open + 1] === '!' || segment[open + 1] === '^' ? open + 2 : open + 1,
520
+ )
521
+
522
+ const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
523
+
524
+ type GlobOptions = { dirPattern?: string; exclude?: string[]; includeDirs: boolean }
525
+
526
+ // PathList#relative_glob
527
+ function relativeGlob(tree: Tree, patterns: string[], options: GlobOptions): string[] {
528
+ if (patterns.length === 0) return []
529
+ const full = options.includeDirs ? [...tree.files, ...tree.dirs] : tree.files
530
+ const exact = new Set(full)
531
+ let list = patterns.flatMap((pattern) => {
532
+ if (exact.has(pattern)) return [pattern]
533
+ let expanded = pattern
534
+ if (options.dirPattern && tree.dirSet.has(pattern.toLowerCase().replace(/\/$/, '')))
535
+ expanded = `${pattern.endsWith('/') ? pattern : `${pattern}/`}${options.dirPattern}`
536
+ const regexes = expandPattern(expanded).map(fnmatchRegex)
537
+ return full.filter((file) => regexes.some((regex) => regex.test(file)))
538
+ })
539
+ if (options.exclude) {
540
+ const excluded = new Set(
541
+ relativeGlob(tree, options.exclude, {
542
+ dirPattern: '**/*',
543
+ includeDirs: options.includeDirs,
544
+ }),
545
+ )
546
+ list = list.filter((file) => !excluded.has(file))
547
+ }
548
+ return list
549
+ }
550
+
551
+ // Sandbox::PodDirCleaner#clean!, keeping FileAccessor.all_files of each spec on the
552
+ // platforms `platforms` gives it
553
+ function clean(spec: Json, root: string, platforms: (node: SpecNode) => string[]) {
554
+ const tree = readTree(root)
555
+ const used = new Set<string>()
556
+ const glob = (patterns: string[], options: GlobOptions) =>
557
+ relativeGlob(tree, patterns, options).forEach((file) => used.add(`${root}/${file}`))
558
+ const first = (pattern: string) =>
559
+ relativeGlob(tree, [pattern], { includeDirs: false })[0]
560
+ const readme = first('readme{*,.*}')
561
+ if (readme) used.add(`${root}/${readme}`)
562
+ const license =
563
+ object(spec.license) && typeof spec.license.file === 'string'
564
+ ? path.join(root, spec.license.file)
565
+ : null
566
+ if (license && fs.existsSync(license)) used.add(license)
567
+ else {
568
+ const found = first('licen{c,s}e{*,.*}')
569
+ if (found) used.add(`${root}/${found}`)
570
+ }
571
+ for (const node of specNodes(spec))
572
+ for (const platform of platforms(node)) {
573
+ const exclude = listValue(node, platform, 'exclude_files')
574
+ const attribute = (name: string, includeDirs: boolean, dirPattern?: string) =>
575
+ glob(listValue(node, platform, name), { dirPattern, exclude, includeDirs })
576
+ attribute('vendored_frameworks', true)
577
+ attribute('vendored_libraries', false)
578
+ attribute('preserve_paths', true)
579
+ attribute('resources', true)
580
+ attribute('source_files', false, SOURCE_FILES_PATTERN)
581
+ for (const key of ['resource_bundles', 'on_demand_resources'])
582
+ for (const patterns of bundleValue(node, platform, key))
583
+ glob(patterns, { exclude, includeDirs: true })
584
+ for (const key of ['prefix_header_file', 'module_map']) {
585
+ const file = inheritedPath(node, platform, key)
586
+ if (file) used.add(path.join(root, file))
587
+ }
588
+ }
589
+
590
+ // every path shares the staging root, whose name is unique, so Ruby's
591
+ // substring test between two paths reduces to a prefix test
592
+ const lowered = [...used].map((file) => file.toLowerCase()).sort()
593
+ const usedSet = new Set(lowered)
594
+ const keeps = (candidate: string) => {
595
+ if (candidate.endsWith('.') || usedSet.has(candidate)) return true
596
+ let low = 0
597
+ let high = lowered.length
598
+ while (low < high) {
599
+ const mid = (low + high) >> 1
600
+ if (lowered[mid]! < candidate) low = mid + 1
601
+ else high = mid
602
+ }
603
+ if (lowered[low]?.startsWith(candidate)) return true
604
+ for (let end = root.length; end < candidate.length; end++)
605
+ if (usedSet.has(candidate.slice(0, end))) return true
606
+ return false
607
+ }
608
+ for (const entry of [...tree.dirs, ...tree.files]) {
609
+ const full = `${root}/${entry}`
610
+ if (!keeps(full.toLowerCase())) fs.rmSync(full, { recursive: true, force: true })
611
+ }
612
+ }
613
+
614
+ /**
615
+ * PodSourceInstaller#clean_installation: drops what no spec an install builds uses. `used` lists
616
+ * those specs by platform; file attributes are not inherited, so a parent counts only when built.
617
+ */
618
+ export function cleanInstalledPod(
619
+ spec: Json,
620
+ root: string,
621
+ used: { platform: string; specs: string[] }[],
622
+ ) {
623
+ clean(spec, root, (node) =>
624
+ used
625
+ .filter((entry) => entry.specs.includes(node.name))
626
+ .map((entry) => entry.platform),
627
+ )
628
+ }