peachsim 0.1.1716 → 0.1.1728

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 (234) hide show
  1. package/README.md +21 -3
  2. package/cli/app-bundle-resources.ts +2 -1
  3. package/cli/app-fonts.ts +4 -4
  4. package/cli/app-splash.ts +4 -4
  5. package/cli/app-stubs.ts +17 -0
  6. package/cli/command-registry.ts +1 -0
  7. package/cli/commands/control.ts +82 -822
  8. package/cli/commands/daemon.ts +8 -0
  9. package/cli/commands/detox.ts +3 -0
  10. package/cli/commands/doctor.ts +19 -2
  11. package/cli/commands/inspect/actions.ts +74 -14
  12. package/cli/commands/inspect/core.ts +5 -1
  13. package/cli/commands/inspect/settling.ts +5 -2
  14. package/cli/commands/inspect/wait-ready.ts +6 -0
  15. package/cli/commands/inspect.ts +48 -45
  16. package/cli/commands/kotlin.ts +12 -2
  17. package/cli/commands/package.ts +750 -0
  18. package/cli/commands/serve.ts +6 -0
  19. package/cli/commands/shell-url.ts +834 -0
  20. package/cli/commands/swift.ts +42 -102
  21. package/cli/commands/test.ts +20 -0
  22. package/cli/commands/upload.ts +1 -1
  23. package/cli/device-option.ts +1 -1
  24. package/cli/main.ts +13 -1
  25. package/cli/native-input.ts +199 -0
  26. package/cli/outbound-endpoints.ts +26 -1
  27. package/cli/packaged-app-launcher.ts +95 -0
  28. package/cli/scene-video.ts +13 -6
  29. package/detox/index.ts +187 -23
  30. package/dist-lib/agent-daemon-client.cjs +1 -1
  31. package/dist-lib/agent-events.cjs +1 -1
  32. package/dist-lib/attached-projects.cjs +1 -1
  33. package/dist-lib/auth/shared-session.cjs +1 -1
  34. package/dist-lib/backend-origin.cjs +1 -1
  35. package/dist-lib/beta.cjs +1 -1
  36. package/dist-lib/beta.mjs +1 -1
  37. package/dist-lib/bridge-constants.cjs +1 -1
  38. package/dist-lib/bridge-contract-input.cjs +1 -1
  39. package/dist-lib/bridge-contract-input.mjs +1 -1
  40. package/dist-lib/bridge-contract.cjs +1 -1
  41. package/dist-lib/bridge-contract.mjs +1 -1
  42. package/dist-lib/bundle-channel.cjs +38000 -31658
  43. package/dist-lib/capture-contract.cjs +1 -1
  44. package/dist-lib/capture-contract.mjs +1 -1
  45. package/dist-lib/cloud-contract.cjs +1 -1
  46. package/dist-lib/cloud-contract.mjs +1 -1
  47. package/dist-lib/cloud-test-args.cjs +1 -1
  48. package/dist-lib/cloud-test-args.mjs +1 -1
  49. package/dist-lib/cloud.cjs +1 -1
  50. package/dist-lib/cloud.mjs +1 -1
  51. package/dist-lib/config.cjs +1 -1
  52. package/dist-lib/config.mjs +1 -1
  53. package/dist-lib/detox/index.cjs +184 -60
  54. package/dist-lib/dev-bundle-resolution.cjs +14 -13
  55. package/dist-lib/expo-swift-bundle.cjs +18199 -11834
  56. package/dist-lib/expo-swift-metadata.cjs +4 -1
  57. package/dist-lib/expo-swift-metadata.mjs +3 -1
  58. package/dist-lib/home-paths.cjs +21 -2
  59. package/dist-lib/host/bridge-host.cjs +26509 -23850
  60. package/dist-lib/host/fetch-proxy-handler.cjs +221 -222
  61. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  62. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  63. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  64. package/dist-lib/host/websocket-proxy.cjs +1 -1
  65. package/dist-lib/index.cjs +876 -389
  66. package/dist-lib/jump-to-source-babel.cjs +1 -1
  67. package/dist-lib/jump-to-source-native.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +127 -16
  69. package/dist-lib/menu.cjs +7 -1
  70. package/dist-lib/menu.mjs +7 -1
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +1 -1
  75. package/dist-lib/metro.cjs +883 -404
  76. package/dist-lib/native-app-identity-project.cjs +694 -280
  77. package/dist-lib/native-app-identity-project.mjs +490 -83
  78. package/dist-lib/native-app-identity.cjs +13 -2
  79. package/dist-lib/native-app-identity.mjs +13 -2
  80. package/dist-lib/native-firebase-metadata.cjs +1 -1
  81. package/dist-lib/native-firebase-metadata.mjs +1 -1
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +1 -1
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +28 -23
  87. package/dist-lib/public-origins-lib.json +392 -224
  88. package/dist-lib/react-native-host-modules.cjs +32 -2
  89. package/dist-lib/react-native-host-modules.mjs +32 -2
  90. package/dist-lib/reap-browser.cjs +12 -4
  91. package/dist-lib/scripts/dev-server-scanner.cjs +15 -8
  92. package/dist-lib/sdk.cjs +17 -7
  93. package/dist-lib/sdk.mjs +16 -7
  94. package/dist-lib/skills.cjs +61838 -47851
  95. package/dist-lib/swift-compile.cjs +583 -360
  96. package/dist-lib/swift-compile.mjs +496 -275
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +1 -1
  99. package/dist-lib/swift-submit.cjs +2 -2
  100. package/dist-lib/swift-submit.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +105 -17
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vite-swift.cjs +4453 -2231
  104. package/dist-lib/vite.cjs +230 -228
  105. package/dist-lib/worklet-executable.cjs +1 -1
  106. package/dist-lib/worklet-executable.mjs +1 -1
  107. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +17 -8
  108. package/dist-types/packages/peach-engine/src/engine/canvaskit-renderer.d.ts +1 -0
  109. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +7 -5
  110. package/dist-types/packages/peach-engine/src/engine/memory-counts.d.ts +3 -1
  111. package/dist-types/packages/peach-engine/src/engine/node.d.ts +1 -11
  112. package/dist-types/packages/peach-engine/src/engine/types.d.ts +3 -0
  113. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +9 -0
  114. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  115. package/dist-types/packages/peach-engine/src/render-worker/native-ui-commandContract.d.ts +1 -1
  116. package/dist-types/packages/peach-engine/src/render-worker/shell-protocol.d.ts +4 -0
  117. package/dist-types/packages/peach-engine/src/render-worker/tree-sync-port.d.ts +1 -1
  118. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +23 -1
  119. package/dist-types/packages/peach-engine/src/shell-events.d.ts +1 -0
  120. package/dist-types/packages/peach-globals/src/audioBridgeContract.d.ts +5 -0
  121. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  122. package/dist-types/packages/peach-globals/src/keyboardBridgeContract.d.ts +11 -0
  123. package/dist-types/packages/peach-globals/src/shellBridgeContract.d.ts +1 -0
  124. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +9 -2
  125. package/package.json +1 -1
  126. package/runtime-companion.json +1 -1
  127. package/scripts/dev-server-scanner.ts +12 -25
  128. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASFoundation.h +52 -0
  129. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASWebAuthenticationSession.h +128 -0
  130. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASWebAuthenticationSessionCallback.h +35 -0
  131. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/AuthenticationServices.h +3 -0
  132. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Modules/module.modulemap +5 -0
  133. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHTTPMessage.h +724 -0
  134. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +4 -0
  135. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetworkDefs.h +27 -0
  136. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Modules/module.modulemap +5 -0
  137. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CFURL.h +1301 -0
  138. package/sdk/ios/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.h +2 -0
  139. package/sdk/ios/System/Library/Frameworks/CoreLocation.framework/Headers/CLLocationManager.h +21 -50
  140. package/sdk/ios/System/Library/Frameworks/CoreLocation.framework/Headers/CLRegion.h +6 -6
  141. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +75 -9
  142. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h +12 -0
  143. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIInterface.h +23 -0
  144. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h +7 -9
  145. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIOrientation.h +14 -0
  146. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIStringDrawing.h +12 -0
  147. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIView.h +14 -0
  148. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIViewAnimating.h +12 -0
  149. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h +16 -0
  150. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIWindow.h +2 -0
  151. package/sdk/ios/usr/include/ConditionalMacros.h +619 -0
  152. package/sdk/ios/usr/include/module.modulemap +1 -0
  153. package/sdk/ios/usr/include/objc/objc-sync.h +59 -0
  154. package/sdk/ios/usr/include/os.modulemap +5 -0
  155. package/sdk/ios/usr/include/sys/cdefs.h +5 -0
  156. package/sdk/ios/usr/include/sys/ioccom.h +99 -0
  157. package/sdk/ios/usr/include/sys/syslog.h +236 -0
  158. package/sdk/ios/usr/include/syslog.h +24 -0
  159. package/sdk/ios/wasm/include/fcntl.h +4 -2
  160. package/sdk/ios/wasm/include/stdio.h +24 -0
  161. package/sdk/ios/wasm/include/stdlib.h +32 -7
  162. package/sdk/ios/wasm/include/sys/file.h +7 -0
  163. package/sdk/ios/wasm/include/sys/ioctl.h +6 -0
  164. package/sdk/ios/wasm/include/sys/syscall.h +9 -0
  165. package/sdk/ios/wasm/include/sys/time.h +10 -0
  166. package/sdk/ios/wasm/include/unistd.h +12 -3
  167. package/sdk/native-hashes.json +1 -0
  168. package/skills/contrast/SKILL.md +2 -1
  169. package/skills/peach-test/SKILL.md +7 -3
  170. package/src/admitted-mac-build.ts +3 -0
  171. package/src/android-app-identity.ts +18 -0
  172. package/src/android-root-module.ts +9 -9
  173. package/src/appPackageContract.ts +81 -0
  174. package/src/bridge-contract.ts +50 -0
  175. package/src/bundle-channel.mjs +21 -4
  176. package/src/dev-bundle-resolution.ts +7 -27
  177. package/src/dom-source-reference.ts +15 -0
  178. package/src/expo-discovery-cache.ts +127 -23
  179. package/src/expo-manifest-body.ts +33 -0
  180. package/src/expo-native-workspace.ts +38 -13
  181. package/src/expo-swift-host.ts +264 -62
  182. package/src/expoSwiftContract.ts +3 -0
  183. package/src/generated/swift-c-predefines.json +1 -1
  184. package/src/home-paths.ts +35 -1
  185. package/src/host/app-package-handler.ts +47 -0
  186. package/src/host/bridge-host.ts +3 -0
  187. package/src/host/staged-host-files.ts +18 -0
  188. package/src/index.ts +3 -0
  189. package/src/kotlin-host.ts +21 -18
  190. package/src/kotlin-instance-source.ts +126 -0
  191. package/src/menu.ts +7 -0
  192. package/src/native-app-identity-project.ts +7 -2
  193. package/src/native-app-identity.ts +11 -0
  194. package/src/native-firebase-config.ts +24 -1
  195. package/src/nitro-adapter.lock.json +268 -268
  196. package/src/nitro-bundle.ts +8 -0
  197. package/src/nitro-compile.ts +35 -9
  198. package/src/nitro-dependencies.ts +21 -19
  199. package/src/nitro-source.ts +4 -0
  200. package/src/nitroContract.ts +7 -0
  201. package/src/react-native-bridge-modules.ts +68 -42
  202. package/src/react-native-host-modules.ts +31 -1
  203. package/src/reactNativeConfigurationContract.ts +14 -0
  204. package/src/reap-browser.ts +15 -3
  205. package/src/sdk.ts +5 -0
  206. package/src/settingsContract.ts +27 -1
  207. package/src/sim-client.ts +4 -1
  208. package/src/storageSnapshotContract.ts +3 -0
  209. package/src/swift-compile.ts +221 -41
  210. package/src/swift-coverage/provenance.ts +1 -0
  211. package/src/swift-coverage/xcode-asset-symbols.ts +922 -0
  212. package/src/swift-coverage/xcode-assets.ts +89 -131
  213. package/src/swift-coverage/xcode.ts +1 -1
  214. package/src/swift-cxx-reachable.ts +2 -1
  215. package/src/swift-distribution.lock.json +14 -13
  216. package/src/swift-host.ts +95 -22
  217. package/src/swift-icu.ts +1 -1
  218. package/src/swift-link-roots.ts +118 -0
  219. package/src/swift-objc-compile.ts +144 -22
  220. package/src/swift-objc-import.ts +6 -0
  221. package/src/swift-objc-standin.ts +2 -14
  222. package/src/swift-package-manifest.ts +14 -6
  223. package/src/swift-packages.ts +75 -11
  224. package/src/swift-pdf-raster.ts +1 -0
  225. package/src/swift-root-lock.ts +17 -1
  226. package/src/swift-source-pods.ts +2 -10
  227. package/src/swift-standin-emit.ts +592 -57
  228. package/src/swift-standins.ts +430 -49
  229. package/src/swift-submit.ts +3 -1
  230. package/src/swift-toolchain.ts +140 -17
  231. package/src/turbo-codegen-intake.ts +91 -0
  232. package/src/vite-plugin-one.ts +13 -9
  233. package/src/vite-plugin.ts +28 -15
  234. package/src/xcode-project.ts +223 -22
@@ -0,0 +1,922 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { extname, join } from 'node:path'
3
+
4
+ // writes the GeneratedAssetSymbols.swift that xcode's actool writes for an
5
+ // iphonesimulator build, byte for byte, from the catalogs alone, so it runs on
6
+ // any host. every rule here was read from actool 27.1 (25098) output; catalog
7
+ // content whose output was not observed is refused with the asset and the
8
+ // reason, never guessed.
9
+ export const assetSymbolsReproduce = 'actool 27.1 (25098)'
10
+
11
+ export type AssetDevice = 'iphone' | 'ipad'
12
+
13
+ export type AssetSymbolSettings = {
14
+ // IPHONEOS_DEPLOYMENT_TARGET; below 17 adds the backwards deployment shims
15
+ deployment: string
16
+ devices: AssetDevice[]
17
+ // the swift extensions on NSColor, UIColor, Color and friends
18
+ extensions: boolean
19
+ }
20
+
21
+ class Refusal extends Error {}
22
+
23
+ const refuse = (path: string, reason: string): never => {
24
+ throw new Refusal(`Generated asset symbols are unproven for ${path}: ${reason}`)
25
+ }
26
+
27
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
28
+ typeof value === 'object' && value !== null && !Array.isArray(value)
29
+
30
+ type Kind = 'color' | 'image'
31
+
32
+ type Asset = {
33
+ kind: Kind
34
+ name: string
35
+ included: boolean
36
+ thinnable: boolean
37
+ source: string
38
+ }
39
+
40
+ type Scope = {
41
+ namespaces: Map<string, Scope>
42
+ // keyed by kind and name
43
+ assets: Map<string, Asset>
44
+ source: string
45
+ }
46
+
47
+ const scope = (source: string): Scope => ({
48
+ namespaces: new Map(),
49
+ assets: new Map(),
50
+ source,
51
+ })
52
+
53
+ // asset types that write no symbols, whatever they hold
54
+ const silentTypes = new Set([
55
+ 'appiconset',
56
+ 'brandassets',
57
+ 'dataset',
58
+ 'iconset',
59
+ 'iconstack',
60
+ 'iconstackgroup',
61
+ 'launchimage',
62
+ 'stickerpack',
63
+ 'stickersiconset',
64
+ 'textureset',
65
+ ])
66
+
67
+ // image stacks write the images in their layers, under the stack and layer
68
+ // names; only stacks whose layer images miss every target device are proven
69
+ const stackTypes = new Set(['imagestack', 'solidimagestack'])
70
+
71
+ // asset types whose symbols were never observed
72
+ const unprovenTypes = new Set([
73
+ 'arobject',
74
+ 'arreferenceimage',
75
+ 'arresourcegroup',
76
+ 'complicationset',
77
+ 'cubetextureset',
78
+ 'gcdashboardimage',
79
+ 'gcleaderboard',
80
+ 'gcleaderboardset',
81
+ 'glyphset',
82
+ 'iconbadgeset',
83
+ 'iconstacklayer',
84
+ 'imagestacklayer',
85
+ 'mipmapset',
86
+ 'modelset',
87
+ 'sidebariconset',
88
+ 'solidimagestacklayer',
89
+ 'sticker',
90
+ 'stickerframeset',
91
+ 'stickersequence',
92
+ ])
93
+
94
+ const knownTypes = new Set([
95
+ 'colorset',
96
+ 'imageset',
97
+ 'symbolset',
98
+ 'spriteatlas',
99
+ ...silentTypes,
100
+ ...stackTypes,
101
+ ...unprovenTypes,
102
+ ])
103
+
104
+ const imageExtensions = new Set([
105
+ 'png',
106
+ 'jpg',
107
+ 'jpeg',
108
+ 'jpe',
109
+ 'heic',
110
+ 'heif',
111
+ 'pdf',
112
+ 'svg',
113
+ ])
114
+
115
+ // what a key may hold: any value, a type, or the values actool accepts. an
116
+ // image rendition whose value is outside its list is dropped, so values never
117
+ // observed are refused; an unknown compression type stops actool.
118
+ type Rule = 'any' | 'string' | 'boolean' | 'object' | 'objects' | readonly string[]
119
+ const compressionTypes = [
120
+ 'automatic',
121
+ 'lossless',
122
+ 'lossy',
123
+ 'gpu-optimized-best',
124
+ 'gpu-optimized-smallest',
125
+ ]
126
+ const renditionRules: Record<string, Rule> = {
127
+ appearances: 'objects',
128
+ locale: 'string',
129
+ platform: 'string',
130
+ resizing: 'object',
131
+ 'alignment-insets': 'object',
132
+ 'compression-type': compressionTypes,
133
+ 'display-gamut': ['sRGB', 'display-P3'],
134
+ 'minimum-system-version': 'string',
135
+ 'matching-style': 'string',
136
+ 'template-rendering-intent': 'string',
137
+ size: 'string',
138
+ role: 'string',
139
+ orientation: 'string',
140
+ extent: 'string',
141
+ }
142
+ const setRules: Record<string, Rule> = {
143
+ localizable: 'any',
144
+ 'auto-scaling': 'string',
145
+ 'symbol-rendering-intent': 'string',
146
+ 'provides-namespace': 'any',
147
+ 'on-demand-resource-tags': 'any',
148
+ 'template-rendering-intent': 'string',
149
+ 'preserves-vector-representation': 'any',
150
+ }
151
+ // keys the inclusion rules below check themselves
152
+ const inclusionRules: Record<string, Rule> = {
153
+ idiom: 'any',
154
+ subtype: 'any',
155
+ unassigned: 'any',
156
+ }
157
+ const rules: Record<
158
+ 'colorset' | 'imageset' | 'symbolset',
159
+ { entry: Record<string, Rule>; set: Record<string, Rule> }
160
+ > = {
161
+ // colors check none of the image traits
162
+ colorset: {
163
+ entry: {
164
+ ...renditionRules,
165
+ ...inclusionRules,
166
+ color: 'any',
167
+ scale: 'string',
168
+ 'language-direction': 'string',
169
+ 'width-class': 'string',
170
+ 'height-class': 'string',
171
+ memory: 'string',
172
+ 'graphics-feature-set': 'string',
173
+ 'screen-width': 'string',
174
+ },
175
+ set: setRules,
176
+ },
177
+ imageset: {
178
+ entry: {
179
+ ...renditionRules,
180
+ ...inclusionRules,
181
+ filename: 'any',
182
+ scale: ['1x', '2x', '3x'],
183
+ 'language-direction': ['left-to-right', 'right-to-left'],
184
+ 'width-class': ['compact', 'regular', 'unspecified'],
185
+ 'height-class': ['compact', 'regular'],
186
+ memory: ['1GB', '2GB', '3GB', '4GB', '6GB', '8GB', '12GB', '16GB'],
187
+ 'graphics-feature-set': [
188
+ ...Array.from({ length: 10 }, (_, i) => `apple${i + 1}`),
189
+ 'metal1v2',
190
+ 'metal2v2',
191
+ 'metal3v1',
192
+ 'metal3v2',
193
+ 'metal4v1',
194
+ ],
195
+ 'screen-width': 'string',
196
+ },
197
+ // an image whose vector flag is not a boolean is dropped
198
+ set: {
199
+ ...setRules,
200
+ 'preserves-vector-representation': 'boolean',
201
+ 'compression-type': compressionTypes,
202
+ },
203
+ },
204
+ symbolset: {
205
+ entry: { idiom: 'any', filename: 'any' },
206
+ set: { 'symbol-rendering-intent': 'any' },
207
+ },
208
+ }
209
+ const listKeys = { colorset: 'colors', imageset: 'images', symbolset: 'symbols' } as const
210
+
211
+ const checkRules = (
212
+ file: string,
213
+ object: Record<string, unknown>,
214
+ ruleSet: Record<string, Rule>,
215
+ ) => {
216
+ for (const [key, value] of Object.entries(object)) {
217
+ const rule = ruleSet[key]
218
+ if (!rule) return refuse(file, `the "${key}" key is unproven`)
219
+ const fits =
220
+ rule === 'any' ||
221
+ (rule === 'object'
222
+ ? isRecord(value)
223
+ : rule === 'objects'
224
+ ? Array.isArray(value) && value.every(isRecord)
225
+ : typeof rule === 'string'
226
+ ? typeof value === rule
227
+ : typeof value === 'string' && rule.includes(value))
228
+ if (!fits) refuse(file, `the ${key} value ${JSON.stringify(value)} is unproven`)
229
+ }
230
+ }
231
+
232
+ // subtypes that keep a rendition; the other observed subtypes drop it
233
+ const keepsSubtype = (colors: boolean, idiom: string, subtype: string) =>
234
+ colors
235
+ ? idiom === 'ipad' && subtype === 'mac-catalyst'
236
+ : (idiom === 'iphone' && ['retina4', '667h', '736h', '2436h'].includes(subtype)) ||
237
+ (idiom === 'ipad' && ['1366h', 'mac-catalyst'].includes(subtype))
238
+ const observedSubtypes = new Set([
239
+ 'retina4',
240
+ '667h',
241
+ '736h',
242
+ '2436h',
243
+ '1366h',
244
+ '38mm',
245
+ 'mac-catalyst',
246
+ ])
247
+
248
+ const readContents = (file: string) => {
249
+ if (!existsSync(file)) return null
250
+ let json: unknown
251
+ try {
252
+ json = JSON.parse(readFileSync(file, 'utf8'))
253
+ } catch {
254
+ return refuse(file, 'it is not valid JSON')
255
+ }
256
+ return isRecord(json) ? json : refuse(file, 'it is not a JSON object')
257
+ }
258
+
259
+ const checkKeys = (file: string, object: Record<string, unknown>, keys: Set<string>) => {
260
+ for (const key of Object.keys(object))
261
+ if (!keys.has(key)) refuse(file, `the "${key}" key is unproven`)
262
+ }
263
+
264
+ // whether a folder provides a namespace
265
+ function folderNamespace(file: string) {
266
+ const json = readContents(file)
267
+ if (!json) return false
268
+ checkKeys(file, json, new Set(['info', 'properties']))
269
+ if (json.properties === undefined) return false
270
+ if (!isRecord(json.properties)) return refuse(file, 'its properties are not an object')
271
+ checkKeys(file, json.properties, new Set(['provides-namespace']))
272
+ const provides = json.properties['provides-namespace']
273
+ if (provides !== undefined && typeof provides !== 'boolean')
274
+ refuse(file, 'provides-namespace is not a boolean')
275
+ return provides === true
276
+ }
277
+
278
+ // whether a set reaches the build, and whether some target device lacks it
279
+ function assetState(
280
+ dir: string,
281
+ type: 'colorset' | 'imageset' | 'symbolset',
282
+ devices: AssetDevice[],
283
+ ) {
284
+ const file = join(dir, 'Contents.json')
285
+ const json = readContents(file)
286
+ if (!json) return { included: false, thinnable: false }
287
+ const list = listKeys[type]
288
+ checkKeys(file, json, new Set(['info', 'properties', list]))
289
+ let tagged = false
290
+ if (json.properties !== undefined) {
291
+ if (!isRecord(json.properties))
292
+ return refuse(file, 'its properties are not an object')
293
+ checkRules(file, json.properties, rules[type].set)
294
+ const tags = json.properties['on-demand-resource-tags']
295
+ if (
296
+ tags !== undefined &&
297
+ !(Array.isArray(tags) && tags.every((tag) => typeof tag === 'string'))
298
+ )
299
+ refuse(file, 'on-demand-resource-tags is not a list of names')
300
+ tagged = Array.isArray(tags) && tags.length > 0
301
+ }
302
+ const entries = json[list] ?? []
303
+ if (!Array.isArray(entries)) return refuse(file, `${list} is not a list`)
304
+ const files = new Set(
305
+ readdirSync(dir, { withFileTypes: true })
306
+ .filter((entry) => entry.isFile())
307
+ .map((entry) => entry.name),
308
+ )
309
+ const covered = new Set<AssetDevice>()
310
+ let included = false
311
+ for (const entry of entries) {
312
+ if (!isRecord(entry)) return refuse(file, `an entry in ${list} is not an object`)
313
+ checkRules(file, entry, rules[type].entry)
314
+ const idiom = entry.idiom
315
+ if (idiom === undefined || idiom === null) continue
316
+ if (typeof idiom !== 'string') return refuse(file, 'an idiom is not a string')
317
+ if (type === 'symbolset' && idiom !== 'universal')
318
+ return refuse(file, `the "${idiom}" symbol idiom is unproven`)
319
+ if (entry.unassigned === true) continue
320
+ if (entry.unassigned !== undefined && entry.unassigned !== false)
321
+ refuse(file, 'unassigned is not a boolean')
322
+ // other idioms never reach an iphonesimulator build
323
+ const device = idiom === 'iphone' || idiom === 'ipad' ? idiom : null
324
+ if (idiom !== 'universal' && idiom !== 'car' && !(device && devices.includes(device)))
325
+ continue
326
+ if (entry.subtype !== undefined) {
327
+ const subtype = entry.subtype
328
+ if (typeof subtype !== 'string') return refuse(file, 'a subtype is not a string')
329
+ if (!keepsSubtype(type === 'colorset', idiom, subtype)) {
330
+ if (observedSubtypes.has(subtype)) continue
331
+ refuse(file, `the "${subtype}" subtype is unproven`)
332
+ }
333
+ }
334
+ if (type === 'colorset') {
335
+ if (entry.color === undefined) continue
336
+ if (!isRecord(entry.color)) return refuse(file, 'a color is not an object')
337
+ if (Object.keys(entry.color).length === 0) continue
338
+ } else {
339
+ if (entry['screen-width'] !== undefined) continue
340
+ const name = entry.filename
341
+ if (name === undefined) continue
342
+ if (typeof name !== 'string') return refuse(file, 'a filename is not a string')
343
+ if (!files.has(name) || !imageExtensions.has(extname(name).slice(1).toLowerCase()))
344
+ continue
345
+ }
346
+ included = true
347
+ if (idiom === 'universal') for (const each of devices) covered.add(each)
348
+ else if (device) covered.add(device)
349
+ }
350
+ return {
351
+ included,
352
+ thinnable:
353
+ included &&
354
+ (devices.some((each) => !covered.has(each)) || (type !== 'colorset' && tagged)),
355
+ }
356
+ }
357
+
358
+ function addAsset(into: Scope, asset: Asset) {
359
+ const key = `${asset.kind}:${asset.name}`
360
+ const known = into.assets.get(key)
361
+ if (!known) {
362
+ into.assets.set(key, asset)
363
+ return
364
+ }
365
+ // the same name in two folders or catalogs: actool keeps one of them
366
+ if (known.included !== asset.included || known.thinnable !== asset.thinnable)
367
+ refuse(asset.source, `${known.source} has the same name and differs`)
368
+ }
369
+
370
+ // a stack whose layers hold no image for a target device writes nothing;
371
+ // sets beside the layers and colors inside them never write symbols
372
+ function checkStack(dir: string, type: string, devices: AssetDevice[]) {
373
+ const sets = (parent: string, allowed: string[]) =>
374
+ readdirSync(parent, { withFileTypes: true }).flatMap((entry) => {
375
+ if (entry.name.startsWith('.') || entry.isFile()) return []
376
+ const path = join(parent, entry.name)
377
+ const extension = extname(entry.name)
378
+ if (!entry.isDirectory() || !allowed.includes(extension))
379
+ return refuse(
380
+ path,
381
+ `image stack content other than ${allowed.join(', ')} is unproven`,
382
+ )
383
+ return [{ path, extension }]
384
+ })
385
+ for (const layer of sets(dir, [`.${type}layer`, '.imageset', '.colorset'])) {
386
+ if (layer.extension !== `.${type}layer`) continue
387
+ for (const set of sets(layer.path, ['.imageset', '.colorset']))
388
+ if (
389
+ set.extension === '.imageset' &&
390
+ assetState(set.path, 'imageset', devices).included
391
+ )
392
+ refuse(set.path, 'an image stack layer image for a target device is unproven')
393
+ }
394
+ }
395
+
396
+ function walk(dir: string, into: Scope, devices: AssetDevice[]) {
397
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
398
+ if (entry.name.startsWith('.') || entry.isFile()) continue
399
+ const path = join(dir, entry.name)
400
+ if (!entry.isDirectory()) return refuse(path, 'it is neither a file nor a directory')
401
+ const extension = extname(entry.name).slice(1)
402
+ const type = extension.toLowerCase()
403
+ const base = entry.name.slice(0, entry.name.length - extension.length - 1)
404
+ if (type !== extension && knownTypes.has(type))
405
+ return refuse(path, 'its type extension is not lowercase')
406
+ if (type === 'colorset' || type === 'imageset' || type === 'symbolset') {
407
+ addAsset(into, {
408
+ kind: type === 'colorset' ? 'color' : 'image',
409
+ name: base,
410
+ ...assetState(path, type, devices),
411
+ source: path,
412
+ })
413
+ continue
414
+ }
415
+ if (silentTypes.has(type)) continue
416
+ if (stackTypes.has(type)) {
417
+ checkStack(path, type, devices)
418
+ continue
419
+ }
420
+ if (unprovenTypes.has(type)) return refuse(path, `${type} assets are unproven`)
421
+ const name = type === 'spriteatlas' ? base : entry.name
422
+ if (!folderNamespace(join(path, 'Contents.json'))) {
423
+ walk(path, into, devices)
424
+ continue
425
+ }
426
+ const child = into.namespaces.get(name) ?? scope(path)
427
+ into.namespaces.set(name, child)
428
+ walk(path, child, devices)
429
+ }
430
+ }
431
+
432
+ const hasKind = (into: Scope, kind: Kind): boolean =>
433
+ [...into.assets.values()].some((asset) => asset.kind === kind && asset.included) ||
434
+ [...into.namespaces.values()].some((child) => hasKind(child, kind))
435
+
436
+ const swiftKeywords = new Set(
437
+ 'precedencegroup associatedtype fileprivate fallthrough extension typealias subscript continue internal Protocol protocol operator rethrows private default public static switch return throws repeat struct deinit import guard while where false catch break defer super class inout throw func Type case else true Self self enum init nil var for let Any try if in do as is _'.split(
438
+ ' ',
439
+ ),
440
+ )
441
+ // a symbol as swift spells it, which warnings quote too
442
+ const spelled = (text: string) => (swiftKeywords.has(text) ? `\`${text}\`` : text)
443
+
444
+ // words split at non-alphanumerics, digit runs, a lower-to-upper step, and
445
+ // before the last capital of a capital run that starts a word
446
+ function words(name: string) {
447
+ const out: string[] = []
448
+ let word = ''
449
+ for (let i = 0; i < name.length; i++) {
450
+ const char = name[i]!
451
+ if (!/[A-Za-z0-9]/.test(char)) {
452
+ if (word) out.push(word)
453
+ word = ''
454
+ continue
455
+ }
456
+ const prev = word.at(-1)
457
+ const next = name[i + 1] ?? ''
458
+ const digit = /[0-9]/.test(char)
459
+ if (
460
+ prev &&
461
+ (digit !== /[0-9]/.test(prev) ||
462
+ (/[A-Z]/.test(char) && /[a-z]/.test(prev)) ||
463
+ (/[A-Z]/.test(char) && /[A-Z]/.test(prev) && /[a-z]/.test(next)))
464
+ ) {
465
+ out.push(word)
466
+ word = ''
467
+ }
468
+ word += char
469
+ }
470
+ if (word) out.push(word)
471
+ while (out.length > 1 && /^(?:color|image)$/i.test(out.at(-1)!)) out.pop()
472
+ return out
473
+ }
474
+
475
+ // the swift identifier actool derives from an asset or namespace name; an
476
+ // asset's first word is lowered, a namespace's is capitalized
477
+ function symbol(name: string, namespace: boolean) {
478
+ const list = words(name)
479
+ if (!list.length) return ''
480
+ const capital = (word: string) => word[0]!.toUpperCase() + word.slice(1)
481
+ let text = list.some((word) => /[a-z]/.test(word))
482
+ ? namespace
483
+ ? list.map(capital).join('')
484
+ : list[0]!.toLowerCase() + list.slice(1).map(capital).join('')
485
+ : list.join('_')
486
+ if (/^[0-9]/.test(text)) text = `_${text}`
487
+ return text
488
+ }
489
+
490
+ // a swift string literal's escapes; other control characters become \u{..}
491
+ const escapes: Record<string, string> = {
492
+ '\\': '\\\\',
493
+ '"': '\\"',
494
+ "'": "\\'",
495
+ '\t': '\\t',
496
+ '\n': '\\n',
497
+ '\r': '\\r',
498
+ }
499
+ const escape = (name: string) =>
500
+ Array.from(name, (char) => {
501
+ const code = char.charCodeAt(0)
502
+ return (
503
+ escapes[char] ??
504
+ (code < 0x20 || code === 0x7f ? `\\u{${code.toString(16).toUpperCase()}}` : char)
505
+ )
506
+ }).join('')
507
+
508
+ type Member =
509
+ | { type: 'warning'; text: string; namespace: boolean }
510
+ | { type: 'namespace'; path: string; symbol: string; members: Member[] }
511
+ | { type: 'asset'; path: string; name: string; symbol: string; thinnable: boolean }
512
+
513
+ // one resource section's members for a scope, in actool's order: names sorted
514
+ // by code unit, a repeated symbol warning after the first owner
515
+ function members(
516
+ into: Scope,
517
+ kind: Kind,
518
+ prefix: string,
519
+ settings: AssetSymbolSettings,
520
+ ): Member[] {
521
+ const entries = [
522
+ ...[...into.namespaces].flatMap(([name, child]) =>
523
+ hasKind(child, kind) ? [{ name, child, asset: null }] : [],
524
+ ),
525
+ ...[...into.assets.values()].flatMap((asset) =>
526
+ asset.kind === kind && asset.included
527
+ ? [{ name: asset.name, child: null, asset }]
528
+ : [],
529
+ ),
530
+ ].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
531
+ const namespaces = new Set<string>()
532
+ const assets = new Set<string>()
533
+ const out: Member[] = []
534
+ for (const entry of entries) {
535
+ const path = `${prefix}${entry.name}`
536
+ const source = entry.child ? entry.child.source : entry.asset.source
537
+ if (Array.from(entry.name).some((char) => char.charCodeAt(0) > 0x7f))
538
+ refuse(source, 'its name is not ASCII')
539
+ const named = (text: string) => `The \\"${escape(path)}\\" ${text}`
540
+ if (entry.child) {
541
+ const text = symbol(entry.name, true)
542
+ if (!text)
543
+ out.push({
544
+ type: 'warning',
545
+ namespace: true,
546
+ text: named(
547
+ 'namespace resolves to an empty symbol. Try renaming the namespace.',
548
+ ),
549
+ })
550
+ else if (namespaces.has(text))
551
+ out.push({
552
+ type: 'warning',
553
+ namespace: true,
554
+ text: named(
555
+ `namespace resolves to the symbol \\"${spelled(text)}\\" which already exists. Try renaming the namespace.`,
556
+ ),
557
+ })
558
+ else {
559
+ namespaces.add(text)
560
+ out.push({
561
+ type: 'namespace',
562
+ path,
563
+ symbol: spelled(text),
564
+ members: members(entry.child, kind, `${path}/`, settings),
565
+ })
566
+ }
567
+ continue
568
+ }
569
+ const asset = entry.asset
570
+ const text = symbol(entry.name, false)
571
+ // without extensions actool leaves thinnable assets out; how they take
572
+ // part in symbol warnings was not observed
573
+ const omitted = !settings.extensions && asset.thinnable
574
+ const warn = (reason: string) => {
575
+ if (omitted)
576
+ refuse(
577
+ source,
578
+ 'a thinnable asset without symbol extensions resolves to an unusable symbol',
579
+ )
580
+ out.push({
581
+ type: 'warning',
582
+ namespace: false,
583
+ text: named(`${kind} asset name resolves to ${reason}. Try renaming the asset.`),
584
+ })
585
+ }
586
+ // a disallowed symbol still claims its name
587
+ if (!text) warn('an empty symbol')
588
+ else if (assets.has(text))
589
+ warn(`the symbol \\"${spelled(text)}\\" which already exists`)
590
+ else if (assets.add(text) && text === 'all') warn('a disallowed symbol \\"all\\"')
591
+ else if (!omitted)
592
+ out.push({
593
+ type: 'asset',
594
+ path,
595
+ name: entry.name,
596
+ symbol: spelled(text),
597
+ thinnable: asset.thinnable,
598
+ })
599
+ if (
600
+ omitted &&
601
+ [...into.assets.values()].some(
602
+ (other) =>
603
+ other !== asset &&
604
+ other.kind === kind &&
605
+ other.included &&
606
+ symbol(other.name, false) === text,
607
+ )
608
+ )
609
+ refuse(source, 'a thinnable asset without symbol extensions shares its symbol')
610
+ }
611
+ return out
612
+ }
613
+
614
+ // a namespace and an asset that share a name or a symbol in one scope come out
615
+ // as a dropped asset or a duplicate declaration
616
+ function checkScope(into: Scope) {
617
+ const assets = [...into.assets.values()]
618
+ for (const [name, child] of into.namespaces) {
619
+ const text = symbol(name, true)
620
+ const asset = assets.find(
621
+ (each) =>
622
+ each.name === name ||
623
+ (each.included && text !== '' && symbol(each.name, false) === text),
624
+ )
625
+ if (asset)
626
+ refuse(asset.source, `the namespace ${child.source} has the same name or symbol`)
627
+ checkScope(child)
628
+ }
629
+ }
630
+
631
+ const indent = (depth: number) => ' '.repeat(depth * 4)
632
+
633
+ function block(attributes: string[], type: string, body: string[]) {
634
+ return `${attributes.join('\n')}\nextension ${type} {\n\n${body.map((each) => `${each}\n\n`).join('')}}`
635
+ }
636
+
637
+ function namespaceText(
638
+ member: { path: string; symbol: string },
639
+ depth: number,
640
+ body: string[],
641
+ ) {
642
+ const pad = indent(depth)
643
+ return `${pad}/// The "${escape(member.path)}" asset catalog resource namespace.\n${pad}enum ${member.symbol} {\n\n${body.map((each) => `${each}\n\n`).join('')}${pad}}`
644
+ }
645
+
646
+ function resourceText(list: Member[], kind: Kind, type: string, depth: number): string[] {
647
+ const pad = indent(depth)
648
+ return list.map((member) =>
649
+ member.type === 'warning'
650
+ ? `${pad}#warning("${member.text}")`
651
+ : member.type === 'namespace'
652
+ ? namespaceText(
653
+ member,
654
+ depth,
655
+ resourceText(member.members, kind, type, depth + 1),
656
+ )
657
+ : `${pad}/// The "${escape(member.path)}" asset catalog ${kind} resource.\n${member.thinnable ? `${pad}@available(watchOS, unavailable)\n` : ''}${pad}static let ${member.symbol} = ${type}(${member.thinnable ? 'thinnableName' : 'name'}: "${escape(member.path)}", bundle: resourceBundle)`,
658
+ )
659
+ }
660
+
661
+ type Extension = {
662
+ // the conflict warning's type name
663
+ label: string
664
+ type: string
665
+ conflicts: Set<string>
666
+ // the platform guard around the initializer, or null for a one-line member
667
+ guard: string | null
668
+ }
669
+
670
+ function extensionText(
671
+ list: Member[],
672
+ kind: Kind,
673
+ ext: Extension,
674
+ depth: number,
675
+ refs: string[],
676
+ ): string[] {
677
+ const pad = indent(depth)
678
+ return list.flatMap((member) => {
679
+ if (member.type === 'warning')
680
+ return member.namespace ? [`${pad}#warning("${member.text}")`] : []
681
+ if (member.type === 'namespace')
682
+ return [
683
+ namespaceText(
684
+ member,
685
+ depth,
686
+ extensionText(member.members, kind, ext, depth + 1, [...refs, member.symbol]),
687
+ ),
688
+ ]
689
+ if (depth === 1 && ext.conflicts.has(member.symbol))
690
+ return [
691
+ `${pad}#warning("The \\"${escape(member.path)}\\" ${kind} asset name resolves to a conflicting ${ext.label} symbol \\"${member.symbol}\\". Try renaming the asset.")`,
692
+ ]
693
+ const ref = [...refs, member.symbol].join('.')
694
+ const doc = `${pad}/// The "${escape(member.path)}" asset catalog ${kind}.\n`
695
+ const optional = member.thinnable ? '?' : ''
696
+ if (!ext.guard)
697
+ return [
698
+ `${doc}${member.thinnable ? `${pad}@available(watchOS, unavailable)\n` : ''}${pad}static var ${member.symbol}: ${ext.type}${optional} { .init(${member.thinnable ? 'thinnableResource: ' : ''}.${ref}) }`,
699
+ ]
700
+ return [
701
+ `${doc}${pad}static var ${member.symbol}: ${ext.type}${optional} {\n#if ${ext.guard}\n${pad} .init(${member.thinnable ? 'thinnableResource' : 'resource'}: .${ref})\n#else\n${pad} .init()\n#endif\n${pad}}`,
702
+ ]
703
+ })
704
+ }
705
+
706
+ const nsColorConflicts = new Set(
707
+ 'unemphasizedSelectedContentBackgroundColor unemphasizedSelectedTextBackgroundColor controlAlternatingRowBackgroundColors alternatingContentBackgroundColors systemColorsDidChangeNotification alternateSelectedControlTextColor selectedContentBackgroundColor alternateSelectedControlColor secondarySelectedControlColor unemphasizedSelectedTextColor selectedTextBackgroundColor keyboardFocusIndicatorColor scrubberTexturedBackground controlLightHighlightColor selectedMenuItemTextColor underPageBackgroundColor disabledControlTextColor selectedControlTextColor controlBackgroundColor controlDarkShadowColor windowBackgroundColor selectedMenuItemColor controlHighlightColor quaternaryLabelColor selectedControlColor windowFrameTextColor placeholderTextColor textBackgroundColor secondaryLabelColor tertiaryLabelColor findHighlightColor controlAccentColor controlShadowColor currentControlTint selectedKnobColor selectedTextColor windowFrameColor controlTextColor headerTextColor scrollBarColor separatorColor highlightColor ignoresAlpha systemOrange systemPurple systemIndigo controlColor systemYellow systemGreen systemBrown headerColor shadowColor systemBlue systemPink systemTeal systemCyan labelColor systemMint systemGray systemRed knobColor gridColor linkColor textColor lightGray darkGray magenta orange purple yellow white black green brown clear blue cyan gray red'.split(
708
+ ' ',
709
+ ),
710
+ )
711
+ const uiColorConflicts = new Set(
712
+ 'secondarySystemGroupedBackground tertiarySystemGroupedBackground secondarySystemBackground tertiarySystemBackground groupTableViewBackground systemGroupedBackground quaternarySystemFill smallSystemFontSize secondarySystemFill tertiarySystemFill systemBackground quaternaryLabel opaqueSeparator placeholderText systemFontSize buttonFontSize secondaryLabel labelFontSize tertiaryLabel systemOrange systemPurple systemIndigo systemYellow systemGray2 systemGray3 systemGray4 systemGray5 systemGray6 systemGreen systemBrown systemBlue systemPink systemTeal systemFill systemCyan systemMint systemGray systemRed tintColor separator lightText lightGray darkText darkGray magenta orange purple yellow white black label green brown clear blue link cyan gray red'.split(
713
+ ' ',
714
+ ),
715
+ )
716
+ const colorConflicts = new Set(
717
+ 'transferRepresentation accentColor secondary primary orange purple indigo yellow white black green brown clear blue pink teal cyan mint gray red'.split(
718
+ ' ',
719
+ ),
720
+ )
721
+ const nsImageConflicts = new Set(
722
+ 'touchBarAudioOutputVolumeMediumTemplateName touchBarAudioOutputVolumeHighTemplateName touchBarAudioOutputVolumeOffTemplateName touchBarAudioOutputVolumeLowTemplateName touchBarTextJustifiedAlignTemplateName touchBarCommunicationVideoTemplateName touchBarCommunicationAudioTemplateName touchBarSkipAhead30SecondsTemplateName touchBarSkipAhead15SecondsTemplateName touchBarTextStrikethroughTemplateName touchBarSkipBack30SecondsTemplateName touchBarSkipBack15SecondsTemplateName stopProgressFreestandingTemplateName touchBarAudioOutputMuteTemplateName invalidDataFreestandingTemplateName touchBarEnterFullScreenTemplateName touchBarTextCenterAlignTemplateName touchBarAudioInputMuteTemplateName followLinkFreestandingTemplateName touchBarExitFullScreenTemplateName touchBarTextRightAlignTemplateName touchBarTextUnderlineTemplateName touchBarTextLeftAlignTemplateName touchBarOpenInBrowserTemplateName touchBarFolderMoveToTemplateName touchBarFolderCopyToTemplateName touchBarFastForwardTemplateName rightFacingTriangleTemplateName refreshFreestandingTemplateName touchBarRotateRightTemplateName touchBarRecordStartTemplateName touchBarSkipToStartTemplateName touchBarTextItalicTemplateName touchBarNewMessageTemplateName leftFacingTriangleTemplateName revealFreestandingTemplateName touchBarVolumeDownTemplateName touchBarRecordStopTemplateName touchBarRotateLeftTemplateName touchBarAudioInputTemplateName touchBarColorPickerStrokeName touchBarSkipAheadTemplateName touchBarSkipToEndTemplateName touchBarGoForwardTemplateName touchBarPlayPauseTemplateName touchBarQuickLookTemplateName touchBarAddDetailTemplateName touchBarUserGroupTemplateName touchBarNewFolderTemplateName touchBarBookmarksTemplateName touchBarSlideshowTemplateName statusPartiallyAvailableName touchBarPlayheadTemplateName touchBarDownloadTemplateName touchBarTextBoldTemplateName touchBarSkipBackTemplateName touchBarVolumeUpTemplateName touchBarTextListTemplateName touchBarIconViewTemplateName touchBarListViewTemplateName touchBarUserAddTemplateName touchBarComposeTemplateName touchBarRefreshTemplateName enterFullScreenTemplateName touchBarTagIconTemplateName touchBarGetInfoTemplateName touchBarSidebarTemplateName touchBarTextBoxTemplateName touchBarHistoryTemplateName touchBarColorPickerFillName touchBarColorPickerFontName touchBarRewindTemplateName menuMixedStateTemplateName touchBarDeleteTemplateName touchBarRemoveTemplateName touchBarSearchTemplateName touchBarGoBackTemplateName exitFullScreenTemplateName touchBarGoDownTemplateName touchBarFolderTemplateName touchBarShareTemplateName touchBarPauseTemplateName touchBarAlarmTemplateName lockUnlockedTemplateName touchBarMailTemplateName touchBarGoUpTemplateName touchBarUserTemplateName iChatTheaterTemplateName stopProgressTemplateName touchBarPlayTemplateName touchBarAddTemplateName menuOnStateTemplateName lockLockedTemplateName smartBadgeTemplateName columnViewTemplateName preferencesGeneralName statusUnavailableName goForwardTemplateName bluetoothTemplateName quickLookTemplateName bookmarksTemplateName slideshowTemplateName multipleDocumentsName iconViewTemplateName listViewTemplateName flowViewTemplateName imageUnfilteredTypes statusAvailableName refreshTemplateName goRightTemplateName applicationIconName folderBurnableName removeTemplateName goBackTemplateName actionTemplateName goLeftTemplateName shareTemplateName homeTemplateName pathTemplateName userAccountsName addTemplateName folderSmartName statusNoneName colorPanelName trashEmptyName fontPanelName trashFullName userGroupName userGuestName advancedName mobileMeName everyoneName computerName networkName cautionName bonjourName folderName imageTypes infoName userName'.split(
723
+ ' ',
724
+ ),
725
+ )
726
+ const uiImageConflicts = new Set([
727
+ 'strokedCheckmark',
728
+ 'checkmark',
729
+ 'actions',
730
+ 'remove',
731
+ 'add',
732
+ ])
733
+
734
+ const imports = (all: boolean) =>
735
+ `import Foundation\n${all ? '#if canImport(AppKit)\nimport AppKit\n#endif\n#if canImport(UIKit)\nimport UIKit\n#endif\n#if canImport(SwiftUI)\nimport SwiftUI\n#endif\n' : ''}#if canImport(DeveloperToolsSupport)\nimport DeveloperToolsSupport\n#endif\n\n#if SWIFT_PACKAGE\nprivate let resourceBundle = Foundation.Bundle.module\n#else\nprivate class ResourceBundleClass {}\nprivate let resourceBundle = Foundation.Bundle(for: ResourceBundleClass.self)\n#endif\n\n`
736
+
737
+ const thinnableInit = (available: string, type: string, appKit: string, uiKit: string) =>
738
+ `@available(${available})\n@available(watchOS, unavailable)\nextension ${type} {\n\n private init?(thinnableName: Swift.String, bundle: Foundation.Bundle) {\n#if canImport(AppKit) && os(macOS)\n if ${appKit} != nil {\n self.init(name: thinnableName, bundle: bundle)\n } else {\n return nil\n }\n#elseif canImport(UIKit) && !os(watchOS)\n if ${uiKit}(named: thinnableName, in: bundle, compatibleWith: nil) != nil {\n self.init(name: thinnableName, bundle: bundle)\n } else {\n return nil\n }\n#else\n return nil\n#endif\n }\n\n}\n\n`
739
+
740
+ const thinnableConvenience = (
741
+ framework: string,
742
+ attributes: string,
743
+ type: string,
744
+ resource: string,
745
+ guard: string,
746
+ ) =>
747
+ `#if canImport(${framework})\n${attributes}\nextension ${type} {\n\n private convenience init?(thinnableResource: ${resource}?) {\n#if ${guard}\n if let resource = thinnableResource {\n self.init(resource: resource)\n } else {\n return nil\n }\n#else\n return nil\n#endif\n }\n\n}\n#endif\n\n`
748
+
749
+ const thinnableSwiftUI = (available: string, type: string, resource: string) =>
750
+ `@available(${available})\nextension ${type} {\n\n private init?(thinnableResource: ${resource}?) {\n if let resource = thinnableResource {\n self.init(resource)\n } else {\n return nil\n }\n }\n\n}`
751
+
752
+ const backwardsDeployment = (a: Availability) =>
753
+ `// MARK: - Backwards Deployment Support -\n\n/// A color resource.\nstruct ColorResource: Swift.Hashable, Swift.Sendable {\n\n /// An asset catalog color resource name.\n fileprivate let name: Swift.String\n\n /// An asset catalog color resource bundle.\n fileprivate let bundle: Foundation.Bundle\n\n /// Initialize a \`ColorResource\` with \`name\` and \`bundle\`.\n init(name: Swift.String, bundle: Foundation.Bundle) {\n self.name = name\n self.bundle = bundle\n }\n\n}\n\n/// An image resource.\nstruct ImageResource: Swift.Hashable, Swift.Sendable {\n\n /// An asset catalog image resource name.\n fileprivate let name: Swift.String\n\n /// An asset catalog image resource bundle.\n fileprivate let bundle: Foundation.Bundle\n\n /// Initialize an \`ImageResource\` with \`name\` and \`bundle\`.\n init(name: Swift.String, bundle: Foundation.Bundle) {\n self.name = name\n self.bundle = bundle\n }\n\n}\n\n#if canImport(AppKit)\n@available(${a.nsColor})\n@available(macCatalyst, unavailable)\nextension AppKit.NSColor {\n\n /// Initialize a \`NSColor\` with a color resource.\n convenience init(resource: ColorResource) {\n self.init(named: NSColor.Name(resource.name), bundle: resource.bundle)!\n }\n\n}\n\nprotocol _ACResourceInitProtocol {}\nextension AppKit.NSImage: _ACResourceInitProtocol {}\n\n@available(${a.nsImage})\n@available(macCatalyst, unavailable)\nextension _ACResourceInitProtocol {\n\n /// Initialize a \`NSImage\` with an image resource.\n init(resource: ImageResource) {\n self = resource.bundle.image(forResource: NSImage.Name(resource.name))! as! Self\n }\n\n}\n#endif\n\n#if canImport(UIKit)\n@available(${a.uiKit})\n@available(watchOS, unavailable)\nextension UIKit.UIColor {\n\n /// Initialize a \`UIColor\` with a color resource.\n convenience init(resource: ColorResource) {\n#if !os(watchOS)\n self.init(named: resource.name, in: resource.bundle, compatibleWith: nil)!\n#else\n self.init()\n#endif\n }\n\n}\n\n@available(${a.uiKit})\n@available(watchOS, unavailable)\nextension UIKit.UIImage {\n\n /// Initialize a \`UIImage\` with an image resource.\n convenience init(resource: ImageResource) {\n#if !os(watchOS)\n self.init(named: resource.name, in: resource.bundle, compatibleWith: nil)!\n#else\n self.init()\n#endif\n }\n\n}\n#endif\n\n#if canImport(SwiftUI)\n@available(${a.swiftUI})\nextension SwiftUI.Color {\n\n /// Initialize a \`Color\` with a color resource.\n init(_ resource: ColorResource) {\n self.init(resource.name, bundle: resource.bundle)\n }\n\n}\n\n@available(${a.swiftUI})\nextension SwiftUI.Image {\n\n /// Initialize an \`Image\` with an image resource.\n init(_ resource: ImageResource) {\n self.init(resource.name, bundle: resource.bundle)\n }\n\n}\n#endif`
754
+
755
+ type Availability = {
756
+ colorResource: string
757
+ imageResource: string
758
+ nsColor: string
759
+ nsImage: string
760
+ uiKit: string
761
+ swiftUI: string
762
+ }
763
+
764
+ const modern: Availability = {
765
+ colorResource: 'iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *',
766
+ imageResource: 'iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *',
767
+ nsColor: 'macOS 14.0, *',
768
+ nsImage: 'macOS 14.0, *',
769
+ uiKit: 'iOS 17.0, tvOS 17.0, *',
770
+ swiftUI: 'iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *',
771
+ }
772
+ const legacy: Availability = {
773
+ colorResource: 'iOS 11.0, macOS 10.13, tvOS 11.0, *',
774
+ imageResource: 'iOS 11.0, macOS 10.7, tvOS 11.0, *',
775
+ nsColor: 'macOS 10.13, *',
776
+ nsImage: 'macOS 10.7, *',
777
+ uiKit: 'iOS 11.0, tvOS 11.0, *',
778
+ swiftUI: 'iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *',
779
+ }
780
+
781
+ function render(catalogs: string[], settings: AssetSymbolSettings) {
782
+ const version = /^(\d+)(?:\.\d+){0,2}$/.exec(settings.deployment)
783
+ if (!version)
784
+ return refuse(
785
+ `IPHONEOS_DEPLOYMENT_TARGET ${settings.deployment}`,
786
+ 'it is not a version',
787
+ )
788
+ const current = Number(version[1]) >= 17
789
+ const a = current ? modern : legacy
790
+ const colorType = current ? 'DeveloperToolsSupport.ColorResource' : 'ColorResource'
791
+ const imageType = current ? 'DeveloperToolsSupport.ImageResource' : 'ImageResource'
792
+ const root = scope('the catalog root')
793
+ for (const catalog of catalogs) {
794
+ const file = join(catalog, 'Contents.json')
795
+ const json = readContents(file)
796
+ if (json) {
797
+ checkKeys(file, json, new Set(['info', 'properties']))
798
+ if (folderNamespace(file))
799
+ refuse(file, 'a namespace at the catalog root is unproven')
800
+ }
801
+ walk(catalog, root, settings.devices)
802
+ }
803
+ checkScope(root)
804
+ const colors = members(root, 'color', '', settings)
805
+ const images = members(root, 'image', '', settings)
806
+ let text = imports(settings.extensions || !current)
807
+ text += `// MARK: - Color Symbols -\n\n${block([`@available(${a.colorResource})`], colorType, resourceText(colors, 'color', colorType, 1))}\n\n`
808
+ text += `// MARK: - Image Symbols -\n\n${block([`@available(${a.imageResource})`], imageType, resourceText(images, 'image', imageType, 1))}\n\n`
809
+ if (settings.extensions) {
810
+ const appKit = (available: string) => [
811
+ `@available(${available})`,
812
+ '@available(macCatalyst, unavailable)',
813
+ ]
814
+ const uiKit = [`@available(${a.uiKit})`, '@available(watchOS, unavailable)']
815
+ const swiftUI = [`@available(${a.swiftUI})`]
816
+ const nsColor = {
817
+ label: 'NSColor',
818
+ type: 'AppKit.NSColor',
819
+ conflicts: nsColorConflicts,
820
+ guard: '!targetEnvironment(macCatalyst)',
821
+ }
822
+ const uiColor = {
823
+ label: 'UIColor',
824
+ type: 'UIKit.UIColor',
825
+ conflicts: uiColorConflicts,
826
+ guard: '!os(watchOS)',
827
+ }
828
+ const color = {
829
+ label: 'Color',
830
+ type: 'SwiftUI.Color',
831
+ conflicts: colorConflicts,
832
+ guard: null,
833
+ }
834
+ const nsImage = {
835
+ label: 'NSImage',
836
+ type: 'AppKit.NSImage',
837
+ conflicts: nsImageConflicts,
838
+ guard: '!targetEnvironment(macCatalyst)',
839
+ }
840
+ const uiImage = {
841
+ label: 'UIImage',
842
+ type: 'UIKit.UIImage',
843
+ conflicts: uiImageConflicts,
844
+ guard: '!os(watchOS)',
845
+ }
846
+ // the shape style extension holds top-level colors only, without warnings
847
+ const shapeStyle = extensionText(
848
+ colors.filter(
849
+ (member) => member.type === 'asset' && !colorConflicts.has(member.symbol),
850
+ ),
851
+ 'color',
852
+ color,
853
+ 1,
854
+ [],
855
+ )
856
+ text += `// MARK: - Color Symbol Extensions -\n\n`
857
+ text += `#if canImport(AppKit)\n${block(appKit(a.nsColor), 'AppKit.NSColor', extensionText(colors, 'color', nsColor, 1, []))}\n#endif\n\n`
858
+ text += `#if canImport(UIKit)\n${block(uiKit, 'UIKit.UIColor', extensionText(colors, 'color', uiColor, 1, []))}\n#endif\n\n`
859
+ text += `#if canImport(SwiftUI)\n${block(swiftUI, 'SwiftUI.Color', extensionText(colors, 'color', color, 1, []))}\n\n${block(swiftUI, 'SwiftUI.ShapeStyle where Self == SwiftUI.Color', shapeStyle)}\n#endif\n\n`
860
+ text += `// MARK: - Image Symbol Extensions -\n\n`
861
+ text += `#if canImport(AppKit)\n${block(appKit(a.nsImage), 'AppKit.NSImage', extensionText(images, 'image', nsImage, 1, []))}\n#endif\n\n`
862
+ text += `#if canImport(UIKit)\n${block(uiKit, 'UIKit.UIImage', extensionText(images, 'image', uiImage, 1, []))}\n#endif\n\n`
863
+ // the appkit initializers appear only when the catalogs hold that kind
864
+ text += `// MARK: - Thinnable Asset Support -\n\n`
865
+ text += thinnableInit(
866
+ a.colorResource,
867
+ colorType,
868
+ 'AppKit.NSColor(named: NSColor.Name(thinnableName), bundle: bundle)',
869
+ 'UIKit.UIColor',
870
+ )
871
+ if (hasKind(root, 'color'))
872
+ text += thinnableConvenience(
873
+ 'AppKit',
874
+ appKit(a.nsColor).join('\n'),
875
+ 'AppKit.NSColor',
876
+ colorType,
877
+ '!targetEnvironment(macCatalyst)',
878
+ )
879
+ text += thinnableConvenience(
880
+ 'UIKit',
881
+ uiKit.join('\n'),
882
+ 'UIKit.UIColor',
883
+ colorType,
884
+ '!os(watchOS)',
885
+ )
886
+ text += `#if canImport(SwiftUI)\n${thinnableSwiftUI(a.swiftUI, 'SwiftUI.Color', colorType)}\n\n${thinnableSwiftUI(a.swiftUI, 'SwiftUI.ShapeStyle where Self == SwiftUI.Color', colorType)}\n#endif\n\n`
887
+ text += thinnableInit(
888
+ a.imageResource,
889
+ imageType,
890
+ 'bundle.image(forResource: NSImage.Name(thinnableName))',
891
+ 'UIKit.UIImage',
892
+ )
893
+ if (hasKind(root, 'image'))
894
+ text += thinnableConvenience(
895
+ 'AppKit',
896
+ appKit(a.nsImage).join('\n'),
897
+ 'AppKit.NSImage',
898
+ imageType,
899
+ '!targetEnvironment(macCatalyst)',
900
+ )
901
+ text += thinnableConvenience(
902
+ 'UIKit',
903
+ uiKit.join('\n'),
904
+ 'UIKit.UIImage',
905
+ imageType,
906
+ '!os(watchOS)',
907
+ )
908
+ }
909
+ return current ? text : text + backwardsDeployment(a)
910
+ }
911
+
912
+ // the GeneratedAssetSymbols.swift actool writes for these catalogs (absolute
913
+ // paths, in xcode's order), or the first content it was never seen to handle
914
+ export function assetSymbolSource(catalogs: string[], settings: AssetSymbolSettings) {
915
+ try {
916
+ return { status: 'source' as const, text: render(catalogs, settings) }
917
+ } catch (error) {
918
+ if (error instanceof Refusal)
919
+ return { status: 'unknown' as const, reason: error.message }
920
+ throw error
921
+ }
922
+ }