peachsim 0.1.2430 → 0.1.2432

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 +16786 -6994
  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,198 @@
1
+ // Xcodeproj 1.28's Config, the xcconfig model CocoaPods generates and its
2
+ // post_install hooks edit (MIT, Eloy Durán and the Xcodeproj team).
3
+
4
+ const LINKER_KEYS = [
5
+ 'simple',
6
+ 'frameworks',
7
+ 'weak_frameworks',
8
+ 'libraries',
9
+ 'arg_files',
10
+ 'force_load',
11
+ ] as const
12
+ type LinkerKey = (typeof LINKER_KEYS)[number]
13
+
14
+ const INHERITED = ['$(inherited)', '${inherited}']
15
+
16
+ // Shellwords.shellsplit
17
+ export function shellsplit(line: string): string[] {
18
+ const words: string[] = []
19
+ let field = ''
20
+ const scan = /\s*(?:([^\s\\'"]+)|'([^']*)'|"((?:[^"\\]|\\.)*)"|(\\.?)|(\S))(\s)?/sy
21
+ let index = 0
22
+ while (index < line.length) {
23
+ scan.lastIndex = index
24
+ const match = scan.exec(line)
25
+ if (!match || match[0].length === 0) break
26
+ index = scan.lastIndex
27
+ const [, word, single, double, escaped, garbage, separator] = match
28
+ if (garbage !== undefined) throw new Error(`Unmatched quote: ${JSON.stringify(line)}`)
29
+ field +=
30
+ word ??
31
+ single ??
32
+ (double !== undefined
33
+ ? double.replace(/\\([$`"\\\n])/g, '$1')
34
+ : (escaped ?? '').replace(/\\(.)/gs, '$1'))
35
+ // ruby's `(\s|\z)?` also ends a word at the end of the line; an optional group never matches empty here
36
+ if (separator !== undefined || index === line.length) {
37
+ words.push(field)
38
+ field = ''
39
+ }
40
+ }
41
+ return words
42
+ }
43
+
44
+ const KEY_VALUE = /^([^=[]+(?:\[[^\]]*(?:=[^\]]*)?\])*)\s*=(.*)$/
45
+
46
+ export class XcodeConfig {
47
+ attributes = new Map<string, string>()
48
+ includes: string[] = []
49
+ readonly otherLinkerFlags: Record<LinkerKey, Set<string>> = {
50
+ simple: new Set(),
51
+ frameworks: new Set(),
52
+ weak_frameworks: new Set(),
53
+ libraries: new Set(),
54
+ arg_files: new Set(),
55
+ force_load: new Set(),
56
+ }
57
+
58
+ constructor(settings: Record<string, string> | Map<string, string> = {}) {
59
+ this.merge(settings)
60
+ }
61
+
62
+ /** Config.new(path): a file's assignments, `$(inherited)` resolved against earlier lines. */
63
+ static parse(content: string): XcodeConfig {
64
+ const config = new XcodeConfig()
65
+ const hash = new Map<string, string>()
66
+ for (const line of content.split('\n')) {
67
+ const uncommented = line.split('//')[0]!
68
+ const include = /#include\??\s*"(.+)"/.exec(uncommented)
69
+ if (include) {
70
+ config.includes.push(
71
+ include[1]!.endsWith('.xcconfig') ? include[1]! : `${include[1]}.xcconfig`,
72
+ )
73
+ continue
74
+ }
75
+ const match = KEY_VALUE.exec(uncommented)
76
+ if (!match) continue
77
+ const key = match[1]!.trim()
78
+ const value = match[2]!
79
+ .trim()
80
+ .replace(/\$\(inherited\)|\$\{inherited\}/g, (m) => hash.get(key) ?? m)
81
+ hash.set(key, value)
82
+ }
83
+ config.merge(hash)
84
+ return config
85
+ }
86
+
87
+ merge(other: XcodeConfig | Record<string, string> | Map<string, string>): void {
88
+ if (other instanceof XcodeConfig) {
89
+ this.#mergeAttributes(other.attributes)
90
+ for (const key of LINKER_KEYS)
91
+ for (const flag of other.otherLinkerFlags[key])
92
+ this.otherLinkerFlags[key].add(flag)
93
+ return
94
+ }
95
+ this.#mergeAttributes(other instanceof Map ? other : new Map(Object.entries(other)))
96
+ const flags = this.attributes.get('OTHER_LDFLAGS')
97
+ if (flags === undefined) return
98
+ this.attributes.delete('OTHER_LDFLAGS')
99
+ const parsed = parseLinkerFlags(flags)
100
+ for (const key of LINKER_KEYS)
101
+ for (const flag of parsed[key]) this.otherLinkerFlags[key].add(flag)
102
+ }
103
+
104
+ #mergeAttributes(attributes: Map<string, string>): void {
105
+ for (const [key, incoming] of attributes) {
106
+ const existing = this.attributes.get(key)
107
+ if (existing === undefined) {
108
+ this.attributes.set(key, incoming)
109
+ continue
110
+ }
111
+ const v1 = existing.trim()
112
+ const v2 = incoming.trim()
113
+ const split1 = shellsplit(v1)
114
+ const split2 = shellsplit(v2)
115
+ const merged =
116
+ split2.every((word) => split1.includes(word)) || startsWith(split1, split2)
117
+ ? v1
118
+ : startsWith(split2, split1)
119
+ ? v2
120
+ : `${v1} ${v2}`
121
+ this.attributes.set(key, merged)
122
+ }
123
+ }
124
+
125
+ toHash(): Map<string, string> {
126
+ const list = [...this.otherLinkerFlags.simple].sort()
127
+ const modifiers: [LinkerKey, string][] = [
128
+ ['libraries', '-l'],
129
+ ['frameworks', '-framework '],
130
+ ['weak_frameworks', '-weak_framework '],
131
+ ['arg_files', '@'],
132
+ ]
133
+ for (const [key, modifier] of modifiers)
134
+ list.push(
135
+ ...[...this.otherLinkerFlags[key]].sort().map((flag) => `${modifier}"${flag}"`),
136
+ )
137
+ list.push(
138
+ ...[...this.otherLinkerFlags.force_load]
139
+ .sort()
140
+ .map((flag) => `-force_load ${flag}`),
141
+ )
142
+ const result = new Map(this.attributes)
143
+ if (list.length > 0) result.set('OTHER_LDFLAGS', list.join(' '))
144
+ for (const [key, value] of result)
145
+ if (INHERITED.includes(value.trim())) result.delete(key)
146
+ return result
147
+ }
148
+
149
+ toString(): string {
150
+ const includes = this.includes.map((file) => `#include "${file}"`)
151
+ const settings = [...this.toHash()]
152
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
153
+ .map(([key, value]) => `${key} = ${value}`.trim())
154
+ return `${[...includes, ...settings].join('\n')}\n`
155
+ }
156
+
157
+ dup(): XcodeConfig {
158
+ return new XcodeConfig(this.toHash())
159
+ }
160
+ }
161
+
162
+ const startsWith = (words: string[], prefix: string[]) =>
163
+ prefix.every((word, index) => words[index] === word)
164
+
165
+ function parseLinkerFlags(flags: string): Record<LinkerKey, string[]> {
166
+ const result: Record<LinkerKey, string[]> = {
167
+ simple: [],
168
+ frameworks: [],
169
+ weak_frameworks: [],
170
+ libraries: [],
171
+ arg_files: [],
172
+ force_load: [],
173
+ }
174
+ const tokens = shellsplit(flags.trim()).flatMap((word) =>
175
+ /^-l./s.test(word)
176
+ ? ['-l', word.slice(2)]
177
+ : /^@./s.test(word)
178
+ ? ['@', word.slice(1)]
179
+ : [word],
180
+ )
181
+ const keys: Record<string, LinkerKey> = {
182
+ '-framework': 'frameworks',
183
+ '-weak_framework': 'weak_frameworks',
184
+ '-l': 'libraries',
185
+ '@': 'arg_files',
186
+ '-force_load': 'force_load',
187
+ }
188
+ let key: LinkerKey | null = null
189
+ for (const token of tokens) {
190
+ const next = keys[token]
191
+ if (next) key = next
192
+ else if (key) {
193
+ result[key].push(token)
194
+ key = null
195
+ } else result.simple.push(token)
196
+ }
197
+ return result
198
+ }
@@ -672,9 +672,17 @@ module Pod
672
672
  end
673
673
 
674
674
  def module_name
675
- attributes_hash['module_name'] || name.split('/').first.gsub(/^([0-9])/, '_\1').gsub(/[^a-zA-Z0-9_]/, '_').gsub(/_+/, '_')
675
+ attributes_hash['module_name'] ||
676
+ c99ext_identifier(attributes_hash['header_dir']) ||
677
+ c99ext_identifier(attributes_hash['name'])
676
678
  end
677
679
 
680
+ def c99ext_identifier(name)
681
+ return nil if name.nil?
682
+ name.gsub(/^([0-9])/, '_\1').gsub(/[^a-zA-Z0-9_]/, '_').gsub(/_+/, '_')
683
+ end
684
+ private :c99ext_identifier
685
+
678
686
  def homepage
679
687
  attributes_hash['homepage']
680
688
  end
@@ -993,6 +1001,8 @@ const HOST_PROBES = new Map([
993
1001
  ['xcrun --sdk iphonesimulator --show-sdk-version', `${NATIVE_GRAPH_SDK_VERSION}\n`],
994
1002
  ['xcodebuild -version', `Xcode ${NATIVE_GRAPH_SDK_VERSION}\n`],
995
1003
  ['/usr/sbin/sysctl -n hw.optional.arm64 2>&1', '1\n'],
1004
+ // peach compiles without ccache
1005
+ ['command -v ccache', ''],
996
1006
  ])
997
1007
 
998
1008
  // peach builds React Native's core, Hermes, their C++ dependencies and One
@@ -1005,6 +1015,22 @@ const SOURCE_BUILD_ENV = {
1005
1015
  ONE_PREBUILT_IOS: '0',
1006
1016
  }
1007
1017
 
1018
+ /** `find <dir> -name "<file>"`, which React Native's post_install runs for the app's Info.plist files. */
1019
+ function findNamed(command: string, cwd: string): string | null {
1020
+ const match = /^find (\S+) -name "([^"*?[\]\\]+)"$/.exec(command.trim())
1021
+ if (!match) return null
1022
+ const found: string[] = []
1023
+ const walk = (dir: string) => {
1024
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1025
+ const at = path.join(dir, entry.name)
1026
+ if (entry.name === match[2]) found.push(at)
1027
+ if (entry.isDirectory()) walk(at)
1028
+ }
1029
+ }
1030
+ walk(path.resolve(cwd, match[1]!))
1031
+ return found.map((file) => `${file}\n`).join('')
1032
+ }
1033
+
1008
1034
  /**
1009
1035
  * an interpreter with cocoapods-core's Pod module and React Native's pod
1010
1036
  * helpers loaded for `app`, with `env` as ENV. evaluated Ruby may write only
@@ -1023,8 +1049,8 @@ export function cocoapodsInterpreter(
1023
1049
  ),
1024
1050
  ),
1025
1051
  shell: (command, cwd) => {
1026
- const probe = HOST_PROBES.get(command.trim())
1027
- return probe === undefined
1052
+ const probe = HOST_PROBES.get(command.trim()) ?? findNamed(command, cwd)
1053
+ return probe === null
1028
1054
  ? nodeShell(command, cwd, interp.host.env, interp.host.writable)
1029
1055
  : { stdout: probe, status: 0 }
1030
1056
  },
@@ -13,13 +13,16 @@ import {
13
13
  childEnv,
14
14
  equal,
15
15
  hashKey,
16
+ insideRoots,
16
17
  RFloat,
17
18
  RHash,
18
19
  RModule,
19
20
  RObject,
21
+ RRegexp,
20
22
  RString,
21
23
  RSymbol,
22
24
  RubyVersion,
25
+ rubyRegexp,
23
26
  str,
24
27
  sym,
25
28
  toInspect,
@@ -551,15 +554,16 @@ export function installStdlib(interp: Interpreter) {
551
554
  // a podspec may rewrite its own package, as some copy vendored sources in while CocoaPods evaluates them
552
555
  const writable = (value: Value | undefined, what: string) => {
553
556
  const target = resolve(text(interp, value))
554
- if (!host.writable.some((root) => target === root || target.startsWith(`${root}/`)))
557
+ if (!insideRoots(target, host.writable))
555
558
  throw new UnsupportedRuby(`${what} writes ${target} outside the podspec's package`)
556
559
  return target
557
560
  }
558
- def(file, 'write', (c) => {
559
- const content = text(interp, c.args[1])
560
- fs.writeFileSync(writable(c.args[0], 'File.write'), content)
561
- return Buffer.byteLength(content)
562
- })
561
+ for (const owner of [interp.classes.IO!, file])
562
+ def(owner, 'write', (c) => {
563
+ const content = text(interp, c.args[1])
564
+ fs.writeFileSync(writable(c.args[0], 'File.write'), content)
565
+ return Buffer.byteLength(content)
566
+ })
563
567
  for (const name of ['delete', 'unlink'])
564
568
  def(file, name, (c) => {
565
569
  for (const target of c.args) fs.rmSync(writable(target, `File.${name}`))
@@ -685,6 +689,42 @@ export function installStdlib(interp: Interpreter) {
685
689
  fs.symlinkSync(text(interp, c.args[0]), target)
686
690
  return null
687
691
  })
692
+ // FileUtils.symbolic_modes_to_i for the r, w and x permissions
693
+ const WHO_MASKS: Record<string, number> = { u: 0o4700, g: 0o2070, o: 0o1007, a: 0o7777 }
694
+ const PERMISSION_MASKS: Record<string, number> = { r: 0o444, w: 0o222, x: 0o111 }
695
+ const symbolicMode = (spec: string, current: number) =>
696
+ spec.split(',').reduce((mode, clause) => {
697
+ const [who = '', ...actions] = clause.split(/([=+-])/)
698
+ if (actions.length === 0) throw new UnsupportedRuby(`FileUtils.chmod('${spec}')`)
699
+ const whoMask = [...(who || 'a')].reduce((mask, c) => {
700
+ if (!Object.hasOwn(WHO_MASKS, c))
701
+ throw new UnsupportedRuby(`FileUtils.chmod('${spec}')`)
702
+ return mask | WHO_MASKS[c]!
703
+ }, 0)
704
+ for (let i = 0; i < actions.length; i += 2) {
705
+ const permission = [...(actions[i + 1] ?? '')].reduce((mask, c) => {
706
+ if (!Object.hasOwn(PERMISSION_MASKS, c))
707
+ throw new UnsupportedRuby(`FileUtils.chmod('${spec}')`)
708
+ return mask | PERMISSION_MASKS[c]!
709
+ }, 0)
710
+ const op = actions[i]
711
+ if (op === '=') mode = (mode & ~whoMask) | (whoMask & permission)
712
+ else if (op === '+') mode |= whoMask & permission
713
+ else mode &= ~(whoMask & permission)
714
+ }
715
+ return mode
716
+ }, current & 0o7777)
717
+ def(fileUtils, 'chmod', (c) => {
718
+ const mode = c.args[0] ?? null
719
+ for (const target of targets(c.args[1], 'FileUtils.chmod'))
720
+ fs.chmodSync(
721
+ target,
722
+ typeof mode === 'number'
723
+ ? mode
724
+ : symbolicMode(text(interp, mode), fs.statSync(target).mode),
725
+ )
726
+ return c.args[1] ?? null
727
+ })
688
728
  def(fileUtils, 'touch', (c) => {
689
729
  for (const target of targets(c.args[0], 'FileUtils.touch')) {
690
730
  const now = new Date()
@@ -706,6 +746,7 @@ export function installStdlib(interp: Interpreter) {
706
746
  stdout: result.stdout ?? '',
707
747
  stderr: result.stderr ?? '',
708
748
  status: result.status ?? 1,
749
+ pid: result.pid,
709
750
  }
710
751
  }
711
752
  const processStatus = (code: number) => {
@@ -714,6 +755,8 @@ export function installStdlib(interp: Interpreter) {
714
755
  interp.globals.set('$?', status)
715
756
  return status
716
757
  }
758
+ // commands run to completion, so Process.wait finds their status here
759
+ const finished = new Map<number, RObject>()
717
760
  const open3 = interp.defineModule('Open3', object)
718
761
  for (const name of ['capture2', 'capture2e', 'capture3'])
719
762
  def(open3, name, (c) => {
@@ -733,12 +776,14 @@ export function installStdlib(interp: Interpreter) {
733
776
  const command = c.args[0]
734
777
  const result = Array.isArray(command)
735
778
  ? runArgv(command.map((a) => text(interp, a)))
736
- : host.shell(text(interp, command ?? null), host.cwd)
737
- processStatus(result.status)
779
+ : { ...host.shell(text(interp, command ?? null), host.cwd), pid: null }
780
+ const status = processStatus(result.status)
781
+ if (result.pid !== null) finished.set(result.pid, status)
782
+ const pipe = interp.constIn(interp.classes.IO!, 'FinishedPipe', null, '-')
738
783
  const io = interp.callMethod(
739
- interp.object.consts.get('StringIO') ?? null,
784
+ pipe,
740
785
  'new',
741
- [str(result.stdout)],
786
+ [str(result.stdout), result.pid],
742
787
  null,
743
788
  null,
744
789
  null,
@@ -747,6 +792,40 @@ export function installStdlib(interp: Interpreter) {
747
792
  return c.block ? interp.callProc(c.block, [io]) : io
748
793
  })
749
794
 
795
+ const regexp = object.consts.get('Regexp')
796
+ if (!(regexp instanceof RModule)) throw new Error('the interpreter defines no Regexp')
797
+ // Regexp.escape escapes what is special in a pattern and spells out whitespace
798
+ const REGEXP_ESCAPES: Record<string, string> = {
799
+ ' ': '\\ ',
800
+ '\t': '\\t',
801
+ '\n': '\\n',
802
+ '\r': '\\r',
803
+ '\f': '\\f',
804
+ '\v': '\\v',
805
+ }
806
+ const escapeRegexp = (source: string) =>
807
+ source.replace(/[[\]{}()|\-*.\\?+^$#\s]/g, (ch) =>
808
+ Object.hasOwn(REGEXP_ESCAPES, ch)
809
+ ? REGEXP_ESCAPES[ch]!
810
+ : /\s/.test(ch)
811
+ ? ch
812
+ : `\\${ch}`,
813
+ )
814
+ for (const name of ['escape', 'quote'])
815
+ def(regexp, name, (c) => str(escapeRegexp(text(interp, c.args[0]))))
816
+ // Regexp.union of strings, matched literally, and patterns, by their source
817
+ def(regexp, 'union', (c) => {
818
+ const parts = c.args.length === 1 && Array.isArray(c.args[0]) ? c.args[0] : c.args
819
+ if (parts.length === 1 && parts[0] instanceof RRegexp) return parts[0]
820
+ const sources = parts.map((part) => {
821
+ if (!(part instanceof RRegexp)) return escapeRegexp(text(interp, part))
822
+ if (part.re.flags !== 'm')
823
+ throw new UnsupportedRuby(`Regexp.union of /${part.source}/ with options`)
824
+ return `(?:${part.source})`
825
+ })
826
+ return rubyRegexp(sources.length ? sources.join('|') : '(?!)', false, false, false)
827
+ })
828
+
750
829
  // JSON
751
830
  const json = interp.defineModule('JSON', object)
752
831
  const parserError = interp.defineModule(
@@ -1097,6 +1176,17 @@ export function installStdlib(interp: Interpreter) {
1097
1176
  const processModule = interp.defineModule('Process', object)
1098
1177
  processModule.consts.set('Status', interp.classes.ProcessStatus!)
1099
1178
  def(processModule, 'pid', () => process.pid)
1179
+ def(processModule, 'wait', (c) => {
1180
+ const pid = c.args[0]
1181
+ const status = typeof pid === 'number' ? finished.get(pid) : undefined
1182
+ if (typeof pid !== 'number' || !status)
1183
+ throw new UnsupportedRuby(
1184
+ `Process.wait(${interp.toS(pid ?? null)}) on no finished command`,
1185
+ )
1186
+ finished.delete(pid)
1187
+ interp.globals.set('$?', status)
1188
+ return pid
1189
+ })
1100
1190
  interp.defineNative(
1101
1191
  interp.classes.ProcessStatus!,
1102
1192
  'success?',
@@ -1156,6 +1246,17 @@ class StringIO
1156
1246
  end
1157
1247
  end
1158
1248
 
1249
+ class IO
1250
+ # what IO.popen returns: a command that already ran, with its output and pid
1251
+ class FinishedPipe < StringIO
1252
+ attr_reader :pid
1253
+ def initialize(string, pid)
1254
+ super(string)
1255
+ @pid = pid
1256
+ end
1257
+ end
1258
+ end
1259
+
1159
1260
  module Singleton
1160
1261
  def self.included(base)
1161
1262
  base.extend(SingletonClassMethods)
@@ -122,6 +122,7 @@ export class RModule {
122
122
  cvars = new Map<string, Value>()
123
123
  ivars = new Map<string, Value>()
124
124
  includes: RModule[] = []
125
+ prepends: RModule[] = []
125
126
  meta: RModule | null = null
126
127
  data: unknown = null
127
128
  frozen = false
@@ -628,6 +629,10 @@ export class Interpreter {
628
629
  }
629
630
  }
630
631
  for (let m: RModule | null = module; m; m = m.superclass) {
632
+ for (const prepended of [...m.prepends].reverse()) {
633
+ add(prepended)
634
+ includeChain(prepended)
635
+ }
631
636
  add(m)
632
637
  includeChain(m)
633
638
  if (m.meta === null && m.name.startsWith('#<Class:') && !m.superclass) {
@@ -840,7 +845,7 @@ export class Interpreter {
840
845
  : target instanceof RObject
841
846
  ? this.singletonOf(target)
842
847
  : this.unsupported(node, env.frame.file, 'singleton class of a value')
843
- return this.moduleBody(node.body, meta, target, env)
848
+ return this.moduleBody(node.body, meta, meta, env)
844
849
  }
845
850
  if (node instanceof N.BeginNode) return this.evBegin(node, env)
846
851
  if (node instanceof N.RescueModifierNode) {
@@ -3627,10 +3632,12 @@ function hashMethod(
3627
3632
  for (const [k, v] of self.entries()) pairBlock(k, v)
3628
3633
  return self
3629
3634
  case 'each_key':
3630
- for (const [k] of self.entries()) interp.callProc(block!, [k])
3635
+ if (!block) break
3636
+ for (const [k] of self.entries()) interp.callProc(block, [k])
3631
3637
  return self
3632
3638
  case 'each_value':
3633
- for (const [, v] of self.entries()) interp.callProc(block!, [v])
3639
+ if (!block) break
3640
+ for (const [, v] of self.entries()) interp.callProc(block, [v])
3634
3641
  return self
3635
3642
  case 'map':
3636
3643
  case 'collect':
@@ -4278,7 +4285,14 @@ function kernelMethod(
4278
4285
  .filter((x) => !(x instanceof RHash))
4279
4286
  .map((x) => interp.toS(x))
4280
4287
  .join(' ')
4281
- const result = interp.host.shell(command, interp.host.cwd)
4288
+ const options = call.args.find((x) => x instanceof RHash)
4289
+ const chdir = options instanceof RHash ? options.get(sym('chdir')) : undefined
4290
+ const result = interp.host.shell(
4291
+ command,
4292
+ chdir === undefined || chdir === null
4293
+ ? interp.host.cwd
4294
+ : path.resolve(interp.host.cwd, interp.toS(chdir)),
4295
+ )
4282
4296
  const status = new RObject(interp.classes.ProcessStatus!)
4283
4297
  status.data = result.status
4284
4298
  interp.globals.set('$?', status)
@@ -4597,9 +4611,13 @@ function moduleMethod(
4597
4611
  for (const m of call.args) {
4598
4612
  if (!(m instanceof RModule))
4599
4613
  interp.raise('TypeError', 'wrong argument type (expected Module)')
4600
- if (!self.includes.includes(m)) self.includes.push(m)
4614
+ const into = call.name === 'prepend' ? self.prepends : self.includes
4615
+ if (!into.includes(m)) into.push(m)
4601
4616
  interp.hierarchyChanged()
4602
- const hook = interp.findMethod(interp.metaOf(m), 'included')
4617
+ const hook = interp.findMethod(
4618
+ interp.metaOf(m),
4619
+ call.name === 'prepend' ? 'prepended' : 'included',
4620
+ )
4603
4621
  if (hook) interp.invoke(hook, m, [self], null, null, env, call.node)
4604
4622
  }
4605
4623
  return self
@@ -4773,6 +4791,14 @@ function objectMethod(
4773
4791
  switch (call.name) {
4774
4792
  case 'nil?':
4775
4793
  return self === null
4794
+ case 'blank?':
4795
+ case 'present?': {
4796
+ // ActiveSupport's Object#blank?, which CocoaPods loads
4797
+ const blank = interp.respondTo(self, 'empty?', false)
4798
+ ? truthy(interp.callMethod(self, 'empty?', [], null, null, null, null))
4799
+ : !truthy(self)
4800
+ return call.name === 'blank?' ? blank : !blank
4801
+ }
4776
4802
  case 'class':
4777
4803
  return interp.classOf(self)
4778
4804
  case 'is_a?':
@@ -5297,6 +5323,20 @@ export function childEnv(env: Map<string, string>): NodeJS.ProcessEnv {
5297
5323
  return result
5298
5324
  }
5299
5325
 
5326
+ /** whether `target` lies in one of `roots`, comparing real paths, as a symlinked temporary directory reaches the same files. */
5327
+ export function insideRoots(target: string, roots: readonly string[]): boolean {
5328
+ let existing = target
5329
+ while (!fs.existsSync(existing)) existing = path.dirname(existing)
5330
+ const real = path.join(
5331
+ fs.realpathSync.native(existing),
5332
+ path.relative(existing, target),
5333
+ )
5334
+ return roots.some((root) => {
5335
+ const canonical = fs.realpathSync.native(root)
5336
+ return real === canonical || real.startsWith(`${canonical}/`)
5337
+ })
5338
+ }
5339
+
5300
5340
  /** runs `command` like backticks when each step is `cd` or a script runner (`node`, `bun`), which resolve packages as the podspec expects. */
5301
5341
  export function nodeShell(
5302
5342
  command: string,
@@ -5308,14 +5348,18 @@ export function nodeShell(
5308
5348
  const echo = /^echo '([^'\\]*)' > (\S+)$/.exec(command.trim())
5309
5349
  if (echo) {
5310
5350
  const target = path.resolve(cwd, echo[2]!)
5311
- if (!writable.some((root) => target === root || target.startsWith(`${root}/`)))
5351
+ if (!insideRoots(target, writable))
5312
5352
  throw new UnsupportedRuby(`shell command \`${command}\` writes outside the package`)
5313
5353
  fs.writeFileSync(target, `${echo[1]}\n`)
5314
5354
  return { stdout: '', status: 0 }
5315
5355
  }
5316
5356
  const steps = command.split(/&&|;/).map((step) => step.trim().split(/\s+/)[0])
5357
+ // a package's own script, which install hooks run in the package
5358
+ const script =
5359
+ steps.length === 1 && steps[0]!.includes('/') ? path.resolve(cwd, steps[0]!) : null
5317
5360
  if (
5318
- !steps.every((program) => program === 'node' || program === 'bun' || program === 'cd')
5361
+ !steps.every((program) => program === 'node' || program === 'bun' || program === 'cd') &&
5362
+ !(script && fs.existsSync(script) && insideRoots(script, writable))
5319
5363
  )
5320
5364
  throw new UnsupportedRuby(`shell command \`${command}\``)
5321
5365
  const result = spawnSync('/bin/sh', ['-c', command], {
@@ -0,0 +1,75 @@
1
+ import { crc32, deflateSync, inflateRawSync } from 'node:zlib'
2
+ import { PNG } from 'pngjs'
3
+
4
+ const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
5
+
6
+ function dataChunk(bytes: Uint8Array): Buffer {
7
+ const chunk = Buffer.alloc(bytes.length + 12)
8
+ chunk.writeUInt32BE(bytes.length)
9
+ chunk.write('IDAT', 4, 'ascii')
10
+ chunk.set(bytes, 8)
11
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, -4)), chunk.length - 4)
12
+ return chunk
13
+ }
14
+
15
+ export function normalizeSwiftCatalogPng(png: Buffer): Buffer {
16
+ if (
17
+ !png.subarray(0, 8).equals(pngSignature) ||
18
+ png.toString('ascii', 12, 16) !== 'CgBI'
19
+ )
20
+ return png
21
+
22
+ const chunks: Buffer[] = [pngSignature]
23
+ const compressed: Buffer[] = []
24
+ let scanlineBytes = 0
25
+ let ended = false
26
+ for (let offset = 8; offset + 12 <= png.length; ) {
27
+ const size = png.readUInt32BE(offset)
28
+ const end = offset + size + 12
29
+ if (end > png.length) throw new Error('truncated Swift catalog PNG chunk')
30
+ const name = png.toString('ascii', offset + 4, offset + 8)
31
+ const chunk = png.subarray(offset, end)
32
+ const body = chunk.subarray(8, -4)
33
+ offset = end
34
+ if (name === 'IHDR') {
35
+ if (size !== 13 || body[8] !== 8 || body[9] !== 6 || body[12] !== 0)
36
+ throw new Error('unsupported Swift catalog CgBI pixel format')
37
+ const width = body.readUInt32BE(0)
38
+ const height = body.readUInt32BE(4)
39
+ if (width === 0 || height === 0 || width * height > 16_777_216)
40
+ throw new Error('Swift catalog CgBI dimensions exceed the image limit')
41
+ scanlineBytes = (width * 4 + 1) * height
42
+ }
43
+ if (name === 'IDAT') {
44
+ compressed.push(body)
45
+ } else if (name === 'IEND') {
46
+ if (!scanlineBytes || !compressed.length)
47
+ throw new Error('Swift catalog CgBI has no pixel data')
48
+ // apple stores the filtered scanlines in raw deflate, without a zlib header.
49
+ const scanlines = inflateRawSync(Buffer.concat(compressed), {
50
+ maxOutputLength: scanlineBytes,
51
+ })
52
+ if (scanlines.length !== scanlineBytes)
53
+ throw new Error('Swift catalog CgBI has incomplete scanlines')
54
+ chunks.push(dataChunk(deflateSync(scanlines)), chunk)
55
+ ended = true
56
+ break
57
+ } else if (name !== 'CgBI' && name !== 'iDOT') {
58
+ chunks.push(chunk)
59
+ }
60
+ }
61
+ if (!ended) throw new Error('truncated Swift catalog CgBI')
62
+
63
+ const decoded = PNG.sync.read(Buffer.concat(chunks))
64
+ for (let i = 0; i < decoded.data.length; i += 4) {
65
+ const blue = decoded.data[i]!
66
+ const green = decoded.data[i + 1]!
67
+ const red = decoded.data[i + 2]!
68
+ const alpha = decoded.data[i + 3]!
69
+ const scale = alpha === 0 ? 0 : 255 / alpha
70
+ decoded.data[i] = Math.min(255, Math.round(red * scale))
71
+ decoded.data[i + 1] = Math.min(255, Math.round(green * scale))
72
+ decoded.data[i + 2] = Math.min(255, Math.round(blue * scale))
73
+ }
74
+ return PNG.sync.write(decoded)
75
+ }