@ng-native/desktop 0.0.0-stage → 0.23.0

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 (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/app.plugin.cjs +17 -0
  4. package/bin/app-config.mjs +168 -0
  5. package/bin/autolink.mjs +224 -0
  6. package/bin/cli.mjs +158 -0
  7. package/bin/host.mjs +427 -0
  8. package/bin/ng-native-desktop.mjs +4 -0
  9. package/bin/package.mjs +971 -0
  10. package/bin/plist.mjs +68 -0
  11. package/bin/prebuilt.mjs +328 -0
  12. package/bin/toolchain.mjs +192 -0
  13. package/native/CMakeLists.txt +276 -0
  14. package/native/appkit/CMakeLists.txt +109 -0
  15. package/native/appkit/address-search.h +26 -0
  16. package/native/appkit/address-search.mm +277 -0
  17. package/native/appkit/animation-frames.h +14 -0
  18. package/native/appkit/animation-frames.mm +106 -0
  19. package/native/appkit/app-info.h +12 -0
  20. package/native/appkit/app-info.mm +98 -0
  21. package/native/appkit/app-updater.mm +128 -0
  22. package/native/appkit/app-windows.h +81 -0
  23. package/native/appkit/app-windows.mm +318 -0
  24. package/native/appkit/appkit-backend.h +73 -0
  25. package/native/appkit/appkit-backend.mm +276 -0
  26. package/native/appkit/apple-authentication.h +19 -0
  27. package/native/appkit/apple-authentication.mm +248 -0
  28. package/native/appkit/apple-button-view.h +10 -0
  29. package/native/appkit/apple-button-view.mm +37 -0
  30. package/native/appkit/apple-id-button.h +16 -0
  31. package/native/appkit/apple-id-button.mm +50 -0
  32. package/native/appkit/audio.h +16 -0
  33. package/native/appkit/audio.mm +275 -0
  34. package/native/appkit/battery.h +13 -0
  35. package/native/appkit/battery.mm +92 -0
  36. package/native/appkit/bookmarks.h +17 -0
  37. package/native/appkit/bookmarks.mm +145 -0
  38. package/native/appkit/calendar.h +25 -0
  39. package/native/appkit/calendar.mm +660 -0
  40. package/native/appkit/camera-view.h +15 -0
  41. package/native/appkit/camera-view.mm +130 -0
  42. package/native/appkit/camera.h +39 -0
  43. package/native/appkit/camera.mm +362 -0
  44. package/native/appkit/cg-canvas.h +17 -0
  45. package/native/appkit/cg-canvas.mm +518 -0
  46. package/native/appkit/component-view.h +17 -0
  47. package/native/appkit/crypto.h +19 -0
  48. package/native/appkit/crypto.mm +78 -0
  49. package/native/appkit/desktop-expo.h +29 -0
  50. package/native/appkit/desktop-expo.mm +385 -0
  51. package/native/appkit/expo-image-drawing.h +46 -0
  52. package/native/appkit/expo-image-drawing.mm +131 -0
  53. package/native/appkit/expo-image-view.h +15 -0
  54. package/native/appkit/expo-image-view.mm +182 -0
  55. package/native/appkit/expo-ui-renderer.h +68 -0
  56. package/native/appkit/expo-ui-renderer.mm +101 -0
  57. package/native/appkit/expo-ui-view.h +26 -0
  58. package/native/appkit/expo-ui-view.mm +134 -0
  59. package/native/appkit/expo-ui.swift +1284 -0
  60. package/native/appkit/file-system.h +16 -0
  61. package/native/appkit/file-system.mm +140 -0
  62. package/native/appkit/fonts.h +12 -0
  63. package/native/appkit/fonts.mm +48 -0
  64. package/native/appkit/geocoder.h +19 -0
  65. package/native/appkit/geocoder.mm +101 -0
  66. package/native/appkit/glass-effect.h +22 -0
  67. package/native/appkit/glass-effect.mm +63 -0
  68. package/native/appkit/glass-view.h +8 -0
  69. package/native/appkit/glass-view.mm +65 -0
  70. package/native/appkit/header-toolbar.h +60 -0
  71. package/native/appkit/header-toolbar.mm +629 -0
  72. package/native/appkit/host-view.h +54 -0
  73. package/native/appkit/host-view.mm +1200 -0
  74. package/native/appkit/image-manipulator.h +14 -0
  75. package/native/appkit/image-manipulator.mm +191 -0
  76. package/native/appkit/image-request.h +22 -0
  77. package/native/appkit/image-request.mm +62 -0
  78. package/native/appkit/image-view.h +8 -0
  79. package/native/appkit/image-view.mm +142 -0
  80. package/native/appkit/input-replay.h +25 -0
  81. package/native/appkit/input-replay.mm +418 -0
  82. package/native/appkit/language-model.h +14 -0
  83. package/native/appkit/language-model.mm +99 -0
  84. package/native/appkit/language-model.swift +472 -0
  85. package/native/appkit/local-authentication.h +15 -0
  86. package/native/appkit/local-authentication.mm +133 -0
  87. package/native/appkit/location.h +16 -0
  88. package/native/appkit/location.mm +214 -0
  89. package/native/appkit/main.mm +1515 -0
  90. package/native/appkit/map-view.h +15 -0
  91. package/native/appkit/map-view.mm +109 -0
  92. package/native/appkit/maps.h +35 -0
  93. package/native/appkit/maps.mm +343 -0
  94. package/native/appkit/menu-bar.h +22 -0
  95. package/native/appkit/menu-bar.mm +208 -0
  96. package/native/appkit/modal-focus.h +16 -0
  97. package/native/appkit/modal-focus.mm +26 -0
  98. package/native/appkit/modal-host-view.h +79 -0
  99. package/native/appkit/modal-host-view.mm +442 -0
  100. package/native/appkit/native-controls.h +22 -0
  101. package/native/appkit/native-controls.mm +431 -0
  102. package/native/appkit/network-state.h +12 -0
  103. package/native/appkit/network-state.mm +64 -0
  104. package/native/appkit/network.h +14 -0
  105. package/native/appkit/network.mm +396 -0
  106. package/native/appkit/notifications.h +19 -0
  107. package/native/appkit/notifications.mm +309 -0
  108. package/native/appkit/photo-library.h +33 -0
  109. package/native/appkit/photo-library.mm +548 -0
  110. package/native/appkit/pointer-buttons.h +32 -0
  111. package/native/appkit/presentation-label.h +15 -0
  112. package/native/appkit/presentation-label.mm +12 -0
  113. package/native/appkit/presented-screen.h +19 -0
  114. package/native/appkit/presented-screen.mm +181 -0
  115. package/native/appkit/printing.h +42 -0
  116. package/native/appkit/printing.mm +393 -0
  117. package/native/appkit/push.h +19 -0
  118. package/native/appkit/push.mm +81 -0
  119. package/native/appkit/red-box.h +26 -0
  120. package/native/appkit/red-box.mm +387 -0
  121. package/native/appkit/screen-capture.h +21 -0
  122. package/native/appkit/screen-capture.mm +92 -0
  123. package/native/appkit/scroll-view.h +13 -0
  124. package/native/appkit/scroll-view.mm +251 -0
  125. package/native/appkit/scrollers.h +25 -0
  126. package/native/appkit/scrollers.mm +43 -0
  127. package/native/appkit/search-field.h +34 -0
  128. package/native/appkit/search-field.mm +291 -0
  129. package/native/appkit/search-toolbar-item.h +19 -0
  130. package/native/appkit/search-toolbar-item.mm +269 -0
  131. package/native/appkit/share-picker.h +34 -0
  132. package/native/appkit/share-picker.mm +121 -0
  133. package/native/appkit/split-view.h +77 -0
  134. package/native/appkit/split-view.mm +1206 -0
  135. package/native/appkit/store-review.h +13 -0
  136. package/native/appkit/store-review.mm +28 -0
  137. package/native/appkit/surface-view.h +45 -0
  138. package/native/appkit/surface-view.mm +558 -0
  139. package/native/appkit/svg-view.h +17 -0
  140. package/native/appkit/svg-view.mm +57 -0
  141. package/native/appkit/symbol-drawing.h +24 -0
  142. package/native/appkit/symbol-drawing.mm +117 -0
  143. package/native/appkit/symbol-view.h +8 -0
  144. package/native/appkit/symbol-view.mm +33 -0
  145. package/native/appkit/system-access.h +34 -0
  146. package/native/appkit/system-access.mm +210 -0
  147. package/native/appkit/system.h +24 -0
  148. package/native/appkit/system.mm +403 -0
  149. package/native/appkit/test-launch.h +36 -0
  150. package/native/appkit/test-launch.mm +115 -0
  151. package/native/appkit/text-input-field.h +76 -0
  152. package/native/appkit/text-input-field.mm +444 -0
  153. package/native/appkit/text-layout.h +58 -0
  154. package/native/appkit/text-layout.mm +477 -0
  155. package/native/appkit/text-recognition.h +13 -0
  156. package/native/appkit/text-recognition.mm +102 -0
  157. package/native/appkit/tracking.h +13 -0
  158. package/native/appkit/tracking.mm +51 -0
  159. package/native/appkit/tray-and-dock.h +45 -0
  160. package/native/appkit/tray-and-dock.mm +130 -0
  161. package/native/appkit/undo.h +23 -0
  162. package/native/appkit/undo.mm +125 -0
  163. package/native/appkit/updates.h +17 -0
  164. package/native/appkit/updates.mm +71 -0
  165. package/native/appkit/video-view.h +10 -0
  166. package/native/appkit/video-view.mm +42 -0
  167. package/native/appkit/video.h +38 -0
  168. package/native/appkit/video.mm +404 -0
  169. package/native/appkit/web-browser.h +12 -0
  170. package/native/appkit/web-browser.mm +97 -0
  171. package/native/appkit/web-view-component.h +9 -0
  172. package/native/appkit/web-view-component.mm +56 -0
  173. package/native/appkit/web-view.h +31 -0
  174. package/native/appkit/web-view.mm +394 -0
  175. package/native/cmake/libraries/react-native-reanimated.cmake +45 -0
  176. package/native/cmake/libraries/react-native-worklets.cmake +46 -0
  177. package/native/cmake/libraries.cmake +109 -0
  178. package/native/cmake/linked-modules.cmake +112 -0
  179. package/native/cmake/react-native.cmake +175 -0
  180. package/native/cmake/runtime-dependencies.cmake +34 -0
  181. package/native/cmake/swift.cmake +43 -0
  182. package/native/cmake/third-party.cmake +74 -0
  183. package/native/core/include/ngn/absent-views.h +27 -0
  184. package/native/core/include/ngn/accessibility.h +140 -0
  185. package/native/core/include/ngn/address-search.h +69 -0
  186. package/native/core/include/ngn/animation-frames.h +39 -0
  187. package/native/core/include/ngn/app-info.h +52 -0
  188. package/native/core/include/ngn/app-menus.h +146 -0
  189. package/native/core/include/ngn/app-windows.h +181 -0
  190. package/native/core/include/ngn/apple-authentication.h +116 -0
  191. package/native/core/include/ngn/asset.h +28 -0
  192. package/native/core/include/ngn/audio.h +125 -0
  193. package/native/core/include/ngn/back-swipe.h +112 -0
  194. package/native/core/include/ngn/battery.h +48 -0
  195. package/native/core/include/ngn/bytes.h +59 -0
  196. package/native/core/include/ngn/calendar.h +180 -0
  197. package/native/core/include/ngn/camera.h +128 -0
  198. package/native/core/include/ngn/control-sizes.h +111 -0
  199. package/native/core/include/ngn/core-modules.h +105 -0
  200. package/native/core/include/ngn/crypto.h +38 -0
  201. package/native/core/include/ngn/default-menu.h +91 -0
  202. package/native/core/include/ngn/desktop-expo.h +193 -0
  203. package/native/core/include/ngn/desktop-modal.h +109 -0
  204. package/native/core/include/ngn/desktop-props.h +75 -0
  205. package/native/core/include/ngn/desktop-view-props.h +110 -0
  206. package/native/core/include/ngn/dev-server.h +33 -0
  207. package/native/core/include/ngn/download.h +24 -0
  208. package/native/core/include/ngn/expo-image.h +192 -0
  209. package/native/core/include/ngn/expo-ui.h +133 -0
  210. package/native/core/include/ngn/file-system.h +274 -0
  211. package/native/core/include/ngn/focus-order.h +63 -0
  212. package/native/core/include/ngn/fonts.h +64 -0
  213. package/native/core/include/ngn/gestures.h +305 -0
  214. package/native/core/include/ngn/glass.h +67 -0
  215. package/native/core/include/ngn/header-bar.h +112 -0
  216. package/native/core/include/ngn/host-state.h +243 -0
  217. package/native/core/include/ngn/image-manipulator.h +70 -0
  218. package/native/core/include/ngn/input-dispatcher.h +211 -0
  219. package/native/core/include/ngn/input-script.h +56 -0
  220. package/native/core/include/ngn/input.h +112 -0
  221. package/native/core/include/ngn/key-value-store.h +41 -0
  222. package/native/core/include/ngn/language-model.h +69 -0
  223. package/native/core/include/ngn/launch-frame.h +47 -0
  224. package/native/core/include/ngn/launch-settings.h +98 -0
  225. package/native/core/include/ngn/layout-animations.h +24 -0
  226. package/native/core/include/ngn/library-components.h +13 -0
  227. package/native/core/include/ngn/library-glue.h +53 -0
  228. package/native/core/include/ngn/live-regions.h +54 -0
  229. package/native/core/include/ngn/local-authentication.h +74 -0
  230. package/native/core/include/ngn/location.h +89 -0
  231. package/native/core/include/ngn/maps.h +226 -0
  232. package/native/core/include/ngn/module-registry.h +51 -0
  233. package/native/core/include/ngn/mounting-backend.h +96 -0
  234. package/native/core/include/ngn/mounting-manager.h +155 -0
  235. package/native/core/include/ngn/native-controls.h +161 -0
  236. package/native/core/include/ngn/native-module.h +109 -0
  237. package/native/core/include/ngn/network-state.h +44 -0
  238. package/native/core/include/ngn/network.h +100 -0
  239. package/native/core/include/ngn/notifications.h +185 -0
  240. package/native/core/include/ngn/photo-library.h +130 -0
  241. package/native/core/include/ngn/printing.h +69 -0
  242. package/native/core/include/ngn/processes.h +114 -0
  243. package/native/core/include/ngn/red-box.h +119 -0
  244. package/native/core/include/ngn/reload-thread.h +258 -0
  245. package/native/core/include/ngn/runtime.h +161 -0
  246. package/native/core/include/ngn/safe-areas.h +77 -0
  247. package/native/core/include/ngn/screen-capture.h +35 -0
  248. package/native/core/include/ngn/screen-presentation.h +85 -0
  249. package/native/core/include/ngn/screen-stacks.h +80 -0
  250. package/native/core/include/ngn/scrollers.h +106 -0
  251. package/native/core/include/ngn/sharing.h +39 -0
  252. package/native/core/include/ngn/spawn-rules.h +78 -0
  253. package/native/core/include/ngn/splash-screen.h +41 -0
  254. package/native/core/include/ngn/split-view.h +270 -0
  255. package/native/core/include/ngn/sqlite.h +38 -0
  256. package/native/core/include/ngn/store-review.h +26 -0
  257. package/native/core/include/ngn/surface-book.h +101 -0
  258. package/native/core/include/ngn/svg.h +393 -0
  259. package/native/core/include/ngn/symbol.h +90 -0
  260. package/native/core/include/ngn/system.h +102 -0
  261. package/native/core/include/ngn/tabs-host.h +171 -0
  262. package/native/core/include/ngn/text-input.h +125 -0
  263. package/native/core/include/ngn/text-measurer.h +38 -0
  264. package/native/core/include/ngn/text-recognition.h +55 -0
  265. package/native/core/include/ngn/tracking.h +34 -0
  266. package/native/core/include/ngn/tray-and-dock.h +107 -0
  267. package/native/core/include/ngn/undo.h +37 -0
  268. package/native/core/include/ngn/updates.h +253 -0
  269. package/native/core/include/ngn/video.h +126 -0
  270. package/native/core/include/ngn/view-box.h +126 -0
  271. package/native/core/include/ngn/view-transform.h +26 -0
  272. package/native/core/include/ngn/view-tree.h +85 -0
  273. package/native/core/include/ngn/web-browser.h +45 -0
  274. package/native/core/include/ngn/web-view.h +133 -0
  275. package/native/core/include/ngn/worklet-host.h +98 -0
  276. package/native/core/src/absent-views.cpp +41 -0
  277. package/native/core/src/accessibility.cpp +374 -0
  278. package/native/core/src/animation-frames.cpp +49 -0
  279. package/native/core/src/app-menus.cpp +352 -0
  280. package/native/core/src/app-windows.cpp +444 -0
  281. package/native/core/src/back-swipe.cpp +91 -0
  282. package/native/core/src/bytes.cpp +158 -0
  283. package/native/core/src/control-sizes.cpp +232 -0
  284. package/native/core/src/default-menu.cpp +96 -0
  285. package/native/core/src/desktop-modal.cpp +162 -0
  286. package/native/core/src/desktop-view-props.cpp +80 -0
  287. package/native/core/src/dev-server-helper.cpp +152 -0
  288. package/native/core/src/dev-server.cpp +103 -0
  289. package/native/core/src/download.cpp +53 -0
  290. package/native/core/src/expo-image.cpp +548 -0
  291. package/native/core/src/expo-ui.cpp +203 -0
  292. package/native/core/src/focus-order.cpp +441 -0
  293. package/native/core/src/gestures.cpp +1806 -0
  294. package/native/core/src/glass.cpp +49 -0
  295. package/native/core/src/header-bar.cpp +104 -0
  296. package/native/core/src/host-services.cpp +50 -0
  297. package/native/core/src/host-state.cpp +61 -0
  298. package/native/core/src/input-dispatcher.cpp +727 -0
  299. package/native/core/src/input-script.cpp +123 -0
  300. package/native/core/src/key-value-store.cpp +169 -0
  301. package/native/core/src/launch-settings.cpp +148 -0
  302. package/native/core/src/layout-animations.cpp +62 -0
  303. package/native/core/src/libraries/RNCWebViewSpec.cpp +80 -0
  304. package/native/core/src/libraries/react-native-reanimated.cpp +216 -0
  305. package/native/core/src/libraries/react-native-worklets.cpp +192 -0
  306. package/native/core/src/libraries/rnscreens.cpp +125 -0
  307. package/native/core/src/libraries/rnsvg.cpp +345 -0
  308. package/native/core/src/libraries/safeareacontext.cpp +70 -0
  309. package/native/core/src/libraries/worklets-idle-frames.js +70 -0
  310. package/native/core/src/library-glue.cpp +35 -0
  311. package/native/core/src/live-regions.cpp +122 -0
  312. package/native/core/src/module-registry.cpp +50 -0
  313. package/native/core/src/modules/accessibility-manager.cpp +98 -0
  314. package/native/core/src/modules/address-search.cpp +219 -0
  315. package/native/core/src/modules/alert-manager.cpp +140 -0
  316. package/native/core/src/modules/app-info.cpp +74 -0
  317. package/native/core/src/modules/app-modules.cpp +405 -0
  318. package/native/core/src/modules/apple-authentication.cpp +188 -0
  319. package/native/core/src/modules/asset.cpp +111 -0
  320. package/native/core/src/modules/async-storage.cpp +192 -0
  321. package/native/core/src/modules/audio.cpp +541 -0
  322. package/native/core/src/modules/battery.cpp +88 -0
  323. package/native/core/src/modules/calendar.cpp +457 -0
  324. package/native/core/src/modules/camera.cpp +221 -0
  325. package/native/core/src/modules/core-modules.cpp +62 -0
  326. package/native/core/src/modules/crypto.cpp +117 -0
  327. package/native/core/src/modules/desktop-expo.cpp +527 -0
  328. package/native/core/src/modules/file-system.cpp +941 -0
  329. package/native/core/src/modules/fonts.cpp +163 -0
  330. package/native/core/src/modules/image-loader.cpp +105 -0
  331. package/native/core/src/modules/image-manipulator.cpp +305 -0
  332. package/native/core/src/modules/language-model.cpp +195 -0
  333. package/native/core/src/modules/local-authentication.cpp +140 -0
  334. package/native/core/src/modules/location.cpp +186 -0
  335. package/native/core/src/modules/maps.cpp +500 -0
  336. package/native/core/src/modules/network-state.cpp +72 -0
  337. package/native/core/src/modules/networking.cpp +387 -0
  338. package/native/core/src/modules/notifications.cpp +549 -0
  339. package/native/core/src/modules/photo-library.cpp +371 -0
  340. package/native/core/src/modules/printing.cpp +201 -0
  341. package/native/core/src/modules/screen-capture.cpp +71 -0
  342. package/native/core/src/modules/sharing.cpp +59 -0
  343. package/native/core/src/modules/splash-screen.cpp +70 -0
  344. package/native/core/src/modules/sqlite.cpp +421 -0
  345. package/native/core/src/modules/store-review.cpp +23 -0
  346. package/native/core/src/modules/text-recognition.cpp +107 -0
  347. package/native/core/src/modules/tracking.cpp +46 -0
  348. package/native/core/src/modules/undo.cpp +59 -0
  349. package/native/core/src/modules/video.cpp +366 -0
  350. package/native/core/src/modules/web-browser.cpp +100 -0
  351. package/native/core/src/modules/web-socket.cpp +266 -0
  352. package/native/core/src/mounting-manager.cpp +380 -0
  353. package/native/core/src/native-controls.cpp +129 -0
  354. package/native/core/src/native-module.cpp +250 -0
  355. package/native/core/src/network.cpp +219 -0
  356. package/native/core/src/posix-launcher.cpp +366 -0
  357. package/native/core/src/processes.cpp +324 -0
  358. package/native/core/src/red-box-errors.js +83 -0
  359. package/native/core/src/red-box.cpp +306 -0
  360. package/native/core/src/runtime.cpp +422 -0
  361. package/native/core/src/safe-areas.cpp +130 -0
  362. package/native/core/src/screen-presentation.cpp +61 -0
  363. package/native/core/src/screen-stacks.cpp +254 -0
  364. package/native/core/src/scrollers.cpp +181 -0
  365. package/native/core/src/spawn-rules.cpp +292 -0
  366. package/native/core/src/split-view.cpp +343 -0
  367. package/native/core/src/svg.cpp +1883 -0
  368. package/native/core/src/symbol.cpp +94 -0
  369. package/native/core/src/tabs-host.cpp +234 -0
  370. package/native/core/src/text-input.cpp +126 -0
  371. package/native/core/src/text-layout-manager.cpp +63 -0
  372. package/native/core/src/tray-and-dock.cpp +154 -0
  373. package/native/core/src/updates.cpp +965 -0
  374. package/native/core/src/view-box.cpp +788 -0
  375. package/native/core/src/view-transform.cpp +45 -0
  376. package/native/core/src/view-tree.cpp +234 -0
  377. package/native/core/src/web-view.cpp +143 -0
  378. package/native/core/src/worklet-host.cpp +10 -0
  379. package/native/scripts/build-hermes.sh +44 -0
  380. package/native/scripts/build.sh +171 -0
  381. package/native/scripts/cache-dir.sh +18 -0
  382. package/native/scripts/codegen-library.sh +193 -0
  383. package/native/scripts/compiler-launcher.sh +17 -0
  384. package/native/scripts/fetch.sh +174 -0
  385. package/native/scripts/hermes-built.sh +10 -0
  386. package/native/scripts/host-dir.sh +16 -0
  387. package/native/scripts/macos-target.sh +8 -0
  388. package/native/scripts/make-prebuilt.mjs +360 -0
  389. package/native/scripts/prebuilt-host-cache.mjs +158 -0
  390. package/native/shim/openssl/sha.h +22 -0
  391. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +37 -0
  392. package/package.json +70 -3
  393. package/prebuilt.json +33 -0
@@ -0,0 +1,965 @@
1
+ #include "ngn/updates.h"
2
+
3
+ #include "ngn/bytes.h"
4
+ #include "ngn/file-system.h"
5
+ #include "ngn/native-module.h"
6
+
7
+ #include <folly/json.h>
8
+
9
+ #include <algorithm>
10
+ #include <cctype>
11
+ #include <fstream>
12
+ #include <regex>
13
+ #include <set>
14
+ #include <sstream>
15
+ #include <stdexcept>
16
+
17
+ namespace ngn {
18
+
19
+ namespace fs = std::filesystem;
20
+
21
+ namespace {
22
+
23
+ std::string lower(std::string text) {
24
+ std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return std::tolower(c); });
25
+ return text;
26
+ }
27
+
28
+ std::string trim(const std::string &text) {
29
+ size_t start = text.find_first_not_of(" \t\r\n");
30
+ if (start == std::string::npos) {
31
+ return "";
32
+ }
33
+ return text.substr(start, text.find_last_not_of(" \t\r\n") - start + 1);
34
+ }
35
+
36
+ std::string headerOf(const Headers &headers, const std::string &name) {
37
+ for (const auto &[key, value] : headers) {
38
+ if (lower(key) == name) {
39
+ return value;
40
+ }
41
+ }
42
+ return "";
43
+ }
44
+
45
+ // A parameter of a header value: `boundary` of `multipart/mixed; boundary=abc`.
46
+ std::string parameterOf(const std::string &value, const std::string &name) {
47
+ std::stringstream in(value);
48
+ std::string piece;
49
+ std::getline(in, piece, ';');
50
+ while (std::getline(in, piece, ';')) {
51
+ auto eq = piece.find('=');
52
+ if (eq != std::string::npos && lower(trim(piece.substr(0, eq))) == name) {
53
+ auto found = trim(piece.substr(eq + 1));
54
+ if (found.size() >= 2 && found.front() == '"' && found.back() == '"') {
55
+ found = found.substr(1, found.size() - 2);
56
+ }
57
+ return found;
58
+ }
59
+ }
60
+ return "";
61
+ }
62
+
63
+ std::string mediaType(const std::string &contentType) {
64
+ return lower(trim(contentType.substr(0, contentType.find(';'))));
65
+ }
66
+
67
+ // 8-4-4-4-12 hex digits: what the protocol's ids are, and all a folder name may be.
68
+ // Letters, digits, `.`, `-` and `_`, at least one.
69
+ bool fileNamePart(const std::string &text) {
70
+ return !text.empty() && std::all_of(text.begin(), text.end(), [](unsigned char c) {
71
+ return std::isalnum(c) || c == '.' || c == '-' || c == '_';
72
+ });
73
+ }
74
+
75
+ bool isUuid(const std::string &id) {
76
+ if (id.size() != 36) {
77
+ return false;
78
+ }
79
+ for (size_t i = 0; i < id.size(); i++) {
80
+ bool dash = i == 8 || i == 13 || i == 18 || i == 23;
81
+ if (dash ? id[i] != '-' : !std::isxdigit(static_cast<unsigned char>(id[i]))) {
82
+ return false;
83
+ }
84
+ }
85
+ return true;
86
+ }
87
+
88
+ UpdateManifest readManifest(const std::string &body) {
89
+ folly::dynamic json;
90
+ try {
91
+ json = folly::parseJson(body);
92
+ } catch (const std::exception &) {
93
+ throw std::runtime_error("the manifest is not JSON");
94
+ }
95
+ auto text = [&](const folly::dynamic &object, const char *key) -> std::string {
96
+ const auto *value = object.isObject() ? object.get_ptr(key) : nullptr;
97
+ if (value == nullptr || !value->isString()) {
98
+ throw std::runtime_error(std::string("the manifest has no ") + key);
99
+ }
100
+ return value->asString();
101
+ };
102
+ const auto *launch = json.isObject() ? json.get_ptr("launchAsset") : nullptr;
103
+ if (launch == nullptr || !launch->isObject()) {
104
+ throw std::runtime_error("the manifest has no launchAsset");
105
+ }
106
+ if (!isUuid(text(json, "id"))) {
107
+ throw std::runtime_error("the manifest's id is not a UUID");
108
+ }
109
+ std::vector<UpdateAsset> assets;
110
+ if (const auto *list = json.get_ptr("assets"); list != nullptr && list->isArray()) {
111
+ for (const auto &entry : *list) {
112
+ const auto *extension = entry.isObject() ? entry.get_ptr("fileExtension") : nullptr;
113
+ UpdateAsset asset{
114
+ .key = text(entry, "key"),
115
+ .hash = text(entry, "hash"),
116
+ .url = text(entry, "url"),
117
+ .fileExtension = extension != nullptr && extension->isString() ? extension->asString() : "",
118
+ };
119
+ // Both name a file in the update's folder, so neither may lead out of it.
120
+ if (!fileNamePart(asset.key) || asset.key == "." || asset.key == ".." ||
121
+ !(asset.fileExtension.empty() || (asset.fileExtension[0] == '.' && fileNamePart(asset.fileExtension.substr(1))))) {
122
+ throw std::runtime_error("the manifest's asset key or fileExtension is not part of a file name: " + asset.key + asset.fileExtension);
123
+ }
124
+ assets.push_back(std::move(asset));
125
+ }
126
+ }
127
+ return UpdateManifest{
128
+ .id = text(json, "id"),
129
+ .createdAt = text(json, "createdAt"),
130
+ .runtimeVersion = text(json, "runtimeVersion"),
131
+ .launchUrl = text(*launch, "url"),
132
+ .launchHash = text(*launch, "hash"),
133
+ .assets = std::move(assets),
134
+ .raw = json,
135
+ };
136
+ }
137
+
138
+ std::string readDirective(const std::string &body) {
139
+ try {
140
+ auto json = folly::parseJson(body);
141
+ if (const auto *type = json.isObject() ? json.get_ptr("type") : nullptr; type != nullptr && type->isString()) {
142
+ return type->asString();
143
+ }
144
+ } catch (const std::exception &) {
145
+ }
146
+ throw std::runtime_error("the directive is not a JSON object with a type");
147
+ }
148
+
149
+ struct Part {
150
+ Headers headers;
151
+ std::string body;
152
+ };
153
+
154
+ std::vector<Part> multipartParts(const std::string &body, const std::string &boundary) {
155
+ std::vector<Part> parts;
156
+ const std::string delimiter = "--" + boundary;
157
+ size_t at = body.find(delimiter);
158
+ while (at != std::string::npos) {
159
+ at += delimiter.size();
160
+ if (body.compare(at, 2, "--") == 0) {
161
+ break;
162
+ }
163
+ at = body.find("\r\n", at);
164
+ if (at == std::string::npos) {
165
+ break;
166
+ }
167
+ at += 2;
168
+ size_t next = body.find("\r\n" + delimiter, at);
169
+ if (next == std::string::npos) {
170
+ throw std::runtime_error("a multipart part does not end");
171
+ }
172
+ std::string raw = body.substr(at, next - at);
173
+ size_t split = raw.find("\r\n\r\n");
174
+ Part part;
175
+ std::string head = split == std::string::npos ? raw : raw.substr(0, split);
176
+ part.body = split == std::string::npos ? "" : raw.substr(split + 4);
177
+ std::stringstream lines(head);
178
+ std::string line;
179
+ while (std::getline(lines, line)) {
180
+ if (!line.empty() && line.back() == '\r') {
181
+ line.pop_back();
182
+ }
183
+ if (auto colon = line.find(':'); colon != std::string::npos) {
184
+ part.headers.emplace_back(trim(line.substr(0, colon)), trim(line.substr(colon + 1)));
185
+ }
186
+ }
187
+ parts.push_back(std::move(part));
188
+ at = next + 2;
189
+ }
190
+ return parts;
191
+ }
192
+
193
+ std::string readFile(const fs::path &file) {
194
+ std::ifstream in(file, std::ios::binary);
195
+ std::stringstream text;
196
+ text << in.rdbuf();
197
+ return text.str();
198
+ }
199
+
200
+ void writeFile(const fs::path &file, const std::string &bytes) {
201
+ fs::create_directories(file.parent_path());
202
+ auto temporary = file;
203
+ temporary += ".partial";
204
+ {
205
+ std::ofstream out(temporary, std::ios::binary | std::ios::trunc);
206
+ out.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
207
+ if (!out) {
208
+ throw std::runtime_error("could not write " + file.string());
209
+ }
210
+ }
211
+ fs::rename(temporary, file);
212
+ }
213
+
214
+ folly::dynamic toJson(const std::optional<LaunchState::Update> &update) {
215
+ if (!update) {
216
+ return nullptr;
217
+ }
218
+ return folly::dynamic::object("id", update->id)("createdAt", update->createdAt)("runtimeVersion", update->runtimeVersion)(
219
+ "file", update->file);
220
+ }
221
+
222
+ std::optional<LaunchState::Update> updateFrom(const folly::dynamic &json) {
223
+ if (!json.isObject()) {
224
+ return std::nullopt;
225
+ }
226
+ auto text = [&](const char *key) {
227
+ const auto *value = json.get_ptr(key);
228
+ return value != nullptr && value->isString() ? value->asString() : std::string();
229
+ };
230
+ return LaunchState::Update{
231
+ .id = text("id"), .createdAt = text("createdAt"), .runtimeVersion = text("runtimeVersion"), .file = text("file")};
232
+ }
233
+
234
+ // The response body and status of one request, gathered from its callbacks.
235
+ struct Download {
236
+ uint16_t status{0};
237
+ Headers headers;
238
+ std::string body;
239
+ };
240
+
241
+ } // namespace
242
+
243
+ std::map<std::string, std::string> assetPathsInBundle(const std::string &bundle) {
244
+ // A field of the registration, its key quoted (as JSON) or not (minified).
245
+ static const std::regex text(R"re("?(httpServerLocation|name|type)"?\s*:\s*"([^"]*)")re");
246
+ static const std::regex list(R"re("?(scales|fileHashes)"?\s*:\s*\[([^\]]*)\])re");
247
+ static const std::set<std::string> kept{"launch-asset", "manifest.json", "signature", "assets.json"};
248
+ auto items = [](const std::string &inside) {
249
+ std::vector<std::string> out;
250
+ std::stringstream in(inside);
251
+ std::string item;
252
+ while (std::getline(in, item, ',')) {
253
+ std::erase_if(item, [](char c) { return c == '"' || std::isspace(static_cast<unsigned char>(c)); });
254
+ out.push_back(item);
255
+ }
256
+ return out;
257
+ };
258
+ std::map<std::string, std::string> out;
259
+ constexpr std::string_view call = "registerAsset(";
260
+ for (size_t at = bundle.find(call); at != std::string::npos; at = bundle.find(call, at)) {
261
+ at += call.size();
262
+ // The registration is one flat object: no braces inside it.
263
+ auto end = bundle.find('}', at);
264
+ if (end == std::string::npos) {
265
+ break;
266
+ }
267
+ auto object = bundle.substr(at, end - at);
268
+ std::map<std::string, std::string> fields;
269
+ std::map<std::string, std::vector<std::string>> lists;
270
+ for (std::sregex_iterator m(object.begin(), object.end(), text), none; m != none; ++m) {
271
+ fields[(*m)[1]] = (*m)[2];
272
+ }
273
+ for (std::sregex_iterator m(object.begin(), object.end(), list), none; m != none; ++m) {
274
+ lists[(*m)[1]] = items((*m)[2]);
275
+ }
276
+ if (!fields.contains("httpServerLocation") || !fields.contains("name") || !fields.contains("type")) {
277
+ continue;
278
+ }
279
+ auto folder = fields["httpServerLocation"];
280
+ while (folder.starts_with('/')) {
281
+ folder.erase(0, 1);
282
+ }
283
+ const auto &scales = lists["scales"];
284
+ const auto &hashes = lists["fileHashes"];
285
+ for (size_t i = 0; i < scales.size() && i < hashes.size(); i++) {
286
+ double scale = 1;
287
+ try {
288
+ scale = std::stod(scales[i]);
289
+ } catch (const std::exception &) {
290
+ continue;
291
+ }
292
+ auto path = folder + "/" + fields["name"] + (scale == 1 ? "" : "@" + scales[i] + "x") + "." + fields["type"];
293
+ // As the resolver writes it: `../` as `_`, and a leading slash dropped.
294
+ for (size_t dots = path.find("../"); dots != std::string::npos; dots = path.find("../", dots)) {
295
+ path.replace(dots, 3, "_");
296
+ }
297
+ while (path.starts_with('/')) {
298
+ path.erase(0, 1);
299
+ }
300
+ auto parts = fs::path(path);
301
+ bool safe = !path.empty() && !kept.contains(*parts.begin());
302
+ for (const auto &part : parts) {
303
+ safe = safe && part != "." && part != "..";
304
+ }
305
+ if (safe && !hashes[i].empty()) {
306
+ out[hashes[i]] = path;
307
+ }
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+
313
+ std::string base64Url(const std::string &bytes) {
314
+ auto text = base64Encode(bytes);
315
+ for (auto &c : text) {
316
+ c = c == '+' ? '-' : c == '/' ? '_' : c;
317
+ }
318
+ while (!text.empty() && text.back() == '=') {
319
+ text.pop_back();
320
+ }
321
+ return text;
322
+ }
323
+
324
+ std::optional<std::map<std::string, std::string>> parseSignatureHeader(const std::string &header) {
325
+ std::map<std::string, std::string> out;
326
+ size_t at = 0;
327
+ while (at < header.size()) {
328
+ while (at < header.size() && (header[at] == ' ' || header[at] == ',')) {
329
+ at++;
330
+ }
331
+ if (at >= header.size()) {
332
+ break;
333
+ }
334
+ auto eq = header.find('=', at);
335
+ if (eq == std::string::npos || eq + 1 >= header.size() || header[eq + 1] != '"') {
336
+ return std::nullopt;
337
+ }
338
+ auto key = trim(header.substr(at, eq - at));
339
+ auto close = header.find('"', eq + 2);
340
+ if (close == std::string::npos) {
341
+ return std::nullopt;
342
+ }
343
+ out[key] = header.substr(eq + 2, close - eq - 2);
344
+ at = close + 1;
345
+ }
346
+ return out;
347
+ }
348
+
349
+ UpdateResponse parseUpdateResponse(const Headers &headers, const std::string &body) {
350
+ auto contentType = headerOf(headers, "content-type");
351
+ UpdateResponse response;
352
+ if (mediaType(contentType) == "multipart/mixed") {
353
+ auto boundary = parameterOf(contentType, "boundary");
354
+ if (boundary.empty()) {
355
+ throw std::runtime_error("the multipart response has no boundary");
356
+ }
357
+ for (auto &part : multipartParts(body, boundary)) {
358
+ auto name = parameterOf(headerOf(part.headers, "content-disposition"), "name");
359
+ if (name == "manifest") {
360
+ response.manifest = readManifest(part.body);
361
+ response.manifestBody = std::move(part.body);
362
+ response.signature = headerOf(part.headers, "expo-signature");
363
+ } else if (name == "directive") {
364
+ response.directive = readDirective(part.body);
365
+ response.directiveBody = part.body;
366
+ response.directiveSignature = headerOf(part.headers, "expo-signature");
367
+ }
368
+ }
369
+ return response;
370
+ }
371
+ response.manifest = readManifest(body);
372
+ response.manifestBody = body;
373
+ response.signature = headerOf(headers, "expo-signature");
374
+ return response;
375
+ }
376
+
377
+ UpdatesClient::UpdatesClient(UpdatesConfig config, std::shared_ptr<Http> http, std::shared_ptr<UpdateCrypto> crypto)
378
+ : config_(std::move(config)), http_(std::move(http)), crypto_(std::move(crypto)) {}
379
+
380
+ LaunchState UpdatesClient::load() const {
381
+ LaunchState state;
382
+ auto file = config_.directory / "state.json";
383
+ if (!fs::exists(file)) {
384
+ return state;
385
+ }
386
+ try {
387
+ auto json = folly::parseJson(readFile(file));
388
+ state.current = updateFrom(json.getDefault("current"));
389
+ state.previous = updateFrom(json.getDefault("previous"));
390
+ for (const auto &id : json.getDefault("failed", folly::dynamic::array())) {
391
+ if (id.isString()) {
392
+ state.failed.push_back(id.asString());
393
+ }
394
+ }
395
+ if (const auto *launching = json.get_ptr("launching"); launching != nullptr && launching->isString()) {
396
+ state.launching = launching->asString();
397
+ }
398
+ } catch (const std::exception &) {
399
+ // A state file that does not read is no state: the embedded bundle runs.
400
+ return LaunchState{};
401
+ }
402
+ return state;
403
+ }
404
+
405
+ void UpdatesClient::save(const LaunchState &state) const {
406
+ folly::dynamic failed = folly::dynamic::array();
407
+ for (const auto &id : state.failed) {
408
+ failed.push_back(id);
409
+ }
410
+ folly::dynamic json = folly::dynamic::object("current", toJson(state.current))("previous", toJson(state.previous))(
411
+ "failed", failed)("launching", state.launching);
412
+ writeFile(config_.directory / "state.json", folly::toPrettyJson(json));
413
+ }
414
+
415
+ std::string UpdatesClient::pathOf(const LaunchState::Update &update) const {
416
+ return (config_.directory / update.file).string();
417
+ }
418
+
419
+ std::optional<std::string> UpdatesClient::signatureProblem(
420
+ const std::string &body, const std::string &header, const std::string &what) const {
421
+ if (config_.certificatePem.empty()) {
422
+ return std::nullopt;
423
+ }
424
+ auto signature = parseSignatureHeader(header);
425
+ if (header.empty() || !signature || !signature->contains("sig")) {
426
+ return "the " + what + " has no expo-signature, and the app requires one";
427
+ }
428
+ auto keyId = signature->contains("keyid") ? signature->at("keyid") : std::string("main");
429
+ auto alg = signature->contains("alg") ? signature->at("alg") : config_.algorithm;
430
+ auto bytes = base64Decode(signature->at("sig"));
431
+ if (keyId != config_.keyId || alg != config_.algorithm || !bytes ||
432
+ !crypto_->verifyRsaSha256(config_.certificatePem, body, *bytes)) {
433
+ return "the " + what + "'s signature does not verify against the app's certificate";
434
+ }
435
+ return std::nullopt;
436
+ }
437
+
438
+ bool UpdatesClient::usable(const LaunchState::Update &update, const LaunchState &state) const {
439
+ // Only `<uuid>/launch-asset`, whatever the state file says.
440
+ if (!isUuid(update.id) || update.file != update.id + "/launch-asset" || update.runtimeVersion != config_.runtimeVersion ||
441
+ std::find(state.failed.begin(), state.failed.end(), update.id) != state.failed.end() || !fs::exists(pathOf(update))) {
442
+ return false;
443
+ }
444
+ // The files may have changed since they were checked: the kept manifest must still be signed,
445
+ // name this update, and hash to the asset.
446
+ try {
447
+ auto folder = config_.directory / update.id;
448
+ auto body = readFile(folder / "manifest.json");
449
+ auto manifest = readManifest(body);
450
+ std::string signature = fs::exists(folder / "signature") ? readFile(folder / "signature") : "";
451
+ // The assets are only looked for: hashing each at every launch would hold up the start.
452
+ if (!manifest.assets.empty()) {
453
+ auto paths = folly::parseJson(readFile(folder / "assets.json"));
454
+ for (const auto &asset : manifest.assets) {
455
+ const auto *path = paths.get_ptr(asset.key);
456
+ if (path == nullptr || !path->isString() || !fs::exists(folder / path->asString())) {
457
+ return false;
458
+ }
459
+ }
460
+ }
461
+ return manifest.id == update.id && !signatureProblem(body, signature) &&
462
+ base64Url(crypto_->sha256(readFile(pathOf(update)))) == manifest.launchHash;
463
+ } catch (const std::exception &) {
464
+ return false;
465
+ }
466
+ }
467
+
468
+ std::string UpdatesClient::launch() {
469
+ std::lock_guard lock(mutex_);
470
+ generation_++;
471
+ running_.reset();
472
+ if (!enabled()) {
473
+ return config_.embeddedBundle;
474
+ }
475
+ auto state = load();
476
+ if (!state.launching.empty()) {
477
+ // The last launch never ran long enough: it crashed. Its update is never run again.
478
+ if (std::find(state.failed.begin(), state.failed.end(), state.launching) == state.failed.end()) {
479
+ state.failed.push_back(state.launching);
480
+ }
481
+ if (state.current && state.current->id == state.launching) {
482
+ state.current = state.previous;
483
+ state.previous.reset();
484
+ }
485
+ state.launching.clear();
486
+ }
487
+ if (state.current && !usable(*state.current, state)) {
488
+ state.current.reset();
489
+ }
490
+ if (state.current) {
491
+ running_ = state.current;
492
+ state.launching = state.current->id;
493
+ }
494
+ try {
495
+ save(state);
496
+ } catch (const std::exception &) {
497
+ // Without its launch mark a crash in the update would never roll it back: the embedded
498
+ // bundle runs instead.
499
+ running_.reset();
500
+ }
501
+ return running_ ? pathOf(*running_) : config_.embeddedBundle;
502
+ }
503
+
504
+ void UpdatesClient::markLaunchSucceeded() {
505
+ std::lock_guard lock(mutex_);
506
+ markLocked();
507
+ }
508
+
509
+ void UpdatesClient::markLocked() {
510
+ if (!enabled()) {
511
+ return;
512
+ }
513
+ auto state = load();
514
+ if (!state.launching.empty() && running_ && state.launching == running_->id) {
515
+ state.launching.clear();
516
+ save(state);
517
+ }
518
+ }
519
+
520
+ void UpdatesClient::markLaunchSucceeded(uint64_t generation) {
521
+ std::lock_guard lock(mutex_);
522
+ if (generation == generation_) {
523
+ markLocked();
524
+ }
525
+ }
526
+
527
+ uint64_t UpdatesClient::launchGeneration() const {
528
+ std::lock_guard lock(mutex_);
529
+ return generation_;
530
+ }
531
+
532
+ std::optional<LaunchState::Update> UpdatesClient::running() const {
533
+ std::lock_guard lock(mutex_);
534
+ return running_;
535
+ }
536
+
537
+ std::map<std::string, std::string> UpdatesClient::localAssets() const {
538
+ std::lock_guard lock(mutex_);
539
+ std::map<std::string, std::string> out;
540
+ if (!running_) {
541
+ return out;
542
+ }
543
+ auto folder = config_.directory / running_->id;
544
+ try {
545
+ auto paths = folly::parseJson(readFile(folder / "assets.json"));
546
+ for (const auto &[key, value] : paths.items()) {
547
+ if (!key.isString() || !value.isString()) {
548
+ continue;
549
+ }
550
+ fs::path relative(value.asString());
551
+ bool inside = !relative.empty() && relative.is_relative() &&
552
+ std::none_of(relative.begin(), relative.end(), [](const fs::path &part) { return part == ".."; });
553
+ if (inside && fs::is_regular_file(folder / relative)) {
554
+ out[key.asString()] = (folder / relative).string();
555
+ }
556
+ }
557
+ } catch (const std::exception &) {
558
+ // An update with no readable assets.json has none to give; launch() would not have run one.
559
+ }
560
+ return out;
561
+ }
562
+
563
+ LaunchState UpdatesClient::state() const {
564
+ std::lock_guard lock(mutex_);
565
+ return load();
566
+ }
567
+
568
+ std::string UpdatesClient::bundleToRun() const {
569
+ std::lock_guard lock(mutex_);
570
+ auto state = load();
571
+ return state.current && usable(*state.current, state) ? pathOf(*state.current) : config_.embeddedBundle;
572
+ }
573
+
574
+ std::string UpdatesClient::beginReload() {
575
+ std::lock_guard lock(mutex_);
576
+ generation_++;
577
+ auto state = load();
578
+ running_.reset();
579
+ state.launching.clear();
580
+ if (state.current && usable(*state.current, state)) {
581
+ running_ = state.current;
582
+ state.launching = state.current->id;
583
+ }
584
+ save(state);
585
+ return running_ ? pathOf(*running_) : config_.embeddedBundle;
586
+ }
587
+
588
+ void UpdatesClient::check(std::function<void(CheckResult)> done) {
589
+ if (!enabled()) {
590
+ done({.error = "updates are off: the app has no updates URL"});
591
+ return;
592
+ }
593
+ HttpRequest request{.url = config_.url, .withCredentials = false};
594
+ request.headers = {
595
+ {"expo-protocol-version", "1"},
596
+ {"expo-platform", config_.platform},
597
+ {"expo-runtime-version", config_.runtimeVersion},
598
+ {"accept", "multipart/mixed,application/expo+json,application/json"},
599
+ };
600
+ if (auto current = running()) {
601
+ request.headers.emplace_back("expo-current-update-id", current->id);
602
+ }
603
+ if (!config_.certificatePem.empty()) {
604
+ request.headers.emplace_back(
605
+ "expo-expect-signature", "sig, keyid=\"" + config_.keyId + "\", alg=\"" + config_.algorithm + "\"");
606
+ }
607
+ auto download = std::make_shared<Download>();
608
+ auto task = http_->send(
609
+ std::move(request),
610
+ {
611
+ .onResponse =
612
+ [download](const HttpResponse &response) {
613
+ download->status = response.status;
614
+ download->headers = response.headers;
615
+ },
616
+ .onData = [download](std::string chunk, int64_t) { download->body += chunk; },
617
+ .onComplete =
618
+ [this, download, done](const std::string &error, bool) {
619
+ CheckResult result;
620
+ if (!error.empty()) {
621
+ result.error = "the update server could not be reached: " + error;
622
+ done(std::move(result));
623
+ return;
624
+ }
625
+ if (download->status == 204) {
626
+ done(std::move(result));
627
+ return;
628
+ }
629
+ if (download->status != 200) {
630
+ result.error = "the update server answered " + std::to_string(download->status);
631
+ done(std::move(result));
632
+ return;
633
+ }
634
+ try {
635
+ auto response = parseUpdateResponse(download->headers, download->body);
636
+ auto state = this->state();
637
+ std::lock_guard lock(mutex_);
638
+ found_.reset();
639
+ foundRollBack_ = false;
640
+ if (response.directive == "rollBackToEmbedded") {
641
+ // A rollback replaces what runs as surely as an update does: signed the same.
642
+ if (auto problem = signatureProblem(response.directiveBody, response.directiveSignature, "rollback directive")) {
643
+ throw std::runtime_error(*problem);
644
+ }
645
+ foundRollBack_ = running_.has_value() || state.current.has_value();
646
+ result.isAvailable = foundRollBack_;
647
+ result.isRollBackToEmbedded = foundRollBack_;
648
+ } else if (response.manifest) {
649
+ const auto &manifest = *response.manifest;
650
+ if (auto problem = signatureProblem(response.manifestBody, response.signature)) {
651
+ throw std::runtime_error(*problem);
652
+ }
653
+ bool failed = std::find(state.failed.begin(), state.failed.end(), manifest.id) != state.failed.end();
654
+ bool known = (running_ && running_->id == manifest.id) || (state.current && state.current->id == manifest.id);
655
+ if (manifest.runtimeVersion == config_.runtimeVersion && !failed && !known) {
656
+ found_ = manifest;
657
+ foundBody_ = response.manifestBody;
658
+ foundSignature_ = response.signature;
659
+ result.isAvailable = true;
660
+ result.manifest = manifest.raw;
661
+ }
662
+ }
663
+ } catch (const std::exception &e) {
664
+ result = CheckResult{.error = e.what()};
665
+ }
666
+ done(std::move(result));
667
+ },
668
+ });
669
+ std::lock_guard lock(mutex_);
670
+ task_ = std::move(task);
671
+ }
672
+
673
+ void UpdatesClient::fetch(std::function<void(FetchResult)> done) {
674
+ std::optional<UpdateManifest> found;
675
+ std::string foundBody;
676
+ std::string foundSignature;
677
+ bool rollBack = false;
678
+ {
679
+ std::lock_guard lock(mutex_);
680
+ found = found_;
681
+ foundBody = foundBody_;
682
+ foundSignature = foundSignature_;
683
+ rollBack = foundRollBack_;
684
+ }
685
+ if (rollBack) {
686
+ {
687
+ std::lock_guard lock(mutex_);
688
+ auto state = load();
689
+ state.previous = state.current;
690
+ state.current.reset();
691
+ save(state);
692
+ foundRollBack_ = false;
693
+ }
694
+ done({.isRollBackToEmbedded = true});
695
+ return;
696
+ }
697
+ if (!found) {
698
+ done({});
699
+ return;
700
+ }
701
+ // What has been downloaded and checked so far, as files relative to the update's folder.
702
+ struct Fetching {
703
+ UpdateManifest manifest;
704
+ std::vector<std::pair<std::string, std::string>> files;
705
+ // Each asset's key to where it goes, relative to the update's folder.
706
+ std::map<std::string, std::string> paths;
707
+ size_t next{0};
708
+ std::function<void()> step;
709
+ };
710
+ auto fetching = std::make_shared<Fetching>();
711
+ fetching->manifest = *found;
712
+ // Folders of the updates kept now, where an asset with the same hash may already be.
713
+ std::vector<fs::path> kept;
714
+ {
715
+ std::lock_guard lock(mutex_);
716
+ auto state = load();
717
+ for (const auto &update : {state.current, state.previous, running_}) {
718
+ if (update && isUuid(update->id) && update->id != found->id) {
719
+ kept.push_back(config_.directory / update->id);
720
+ }
721
+ }
722
+ }
723
+
724
+ // Sends one request, and calls `got` with its body, or `done` with why it failed.
725
+ auto download = [this, done](const std::string &url, const std::string &what, std::function<void(std::string)> got) {
726
+ auto body = std::make_shared<Download>();
727
+ auto task = http_->send(
728
+ HttpRequest{.url = url, .withCredentials = false},
729
+ {
730
+ .onResponse = [body](const HttpResponse &response) { body->status = response.status; },
731
+ .onData = [body](std::string chunk, int64_t) { body->body += chunk; },
732
+ .onComplete =
733
+ [body, what, done, got = std::move(got)](const std::string &error, bool) {
734
+ if (!error.empty() || body->status != 200) {
735
+ done({.error = error.empty() ? what + "'s server answered " + std::to_string(body->status)
736
+ : what + " could not be downloaded: " + error});
737
+ return;
738
+ }
739
+ got(std::move(body->body));
740
+ },
741
+ });
742
+ std::lock_guard lock(mutex_);
743
+ task_ = std::move(task);
744
+ };
745
+
746
+ // Given `fetching` rather than holding it: `fetching->step` holds this.
747
+ auto finish = [this, foundBody, foundSignature, done](const Fetching &fetching) {
748
+ FetchResult result;
749
+ const auto &found = fetching.manifest;
750
+ try {
751
+ std::lock_guard lock(mutex_);
752
+ LaunchState::Update update{
753
+ .id = found.id,
754
+ .createdAt = found.createdAt,
755
+ .runtimeVersion = found.runtimeVersion,
756
+ .file = found.id + "/launch-asset",
757
+ };
758
+ for (const auto &[file, bytes] : fetching.files) {
759
+ writeFile(config_.directory / update.id / file, bytes);
760
+ }
761
+ folly::dynamic paths = folly::dynamic::object();
762
+ for (const auto &[key, path] : fetching.paths) {
763
+ paths[key] = path;
764
+ }
765
+ writeFile(config_.directory / update.id / "assets.json", folly::toJson(paths));
766
+ // What the next launch checks the asset against, signature and all.
767
+ writeFile(config_.directory / update.id / "manifest.json", foundBody);
768
+ writeFile(config_.directory / update.id / "signature", foundSignature);
769
+ auto state = load();
770
+ if (state.current && state.current->id != update.id) {
771
+ state.previous = state.current;
772
+ }
773
+ state.current = update;
774
+ save(state);
775
+ // Only the updates the state names, and the one running, are kept.
776
+ for (const auto &entry : fs::directory_iterator(config_.directory)) {
777
+ auto name = entry.path().filename().string();
778
+ bool keep = !entry.is_directory() || name == update.id || (state.previous && name == state.previous->id) ||
779
+ (running_ && name == running_->id);
780
+ if (!keep) {
781
+ fs::remove_all(entry.path());
782
+ }
783
+ }
784
+ found_.reset();
785
+ result.isNew = true;
786
+ result.manifest = found.raw;
787
+ } catch (const std::exception &e) {
788
+ result.error = e.what();
789
+ }
790
+ done(std::move(result));
791
+ };
792
+
793
+ // Each asset in turn, from a kept update when one has it with the same hash, else the server.
794
+ // Holds `fetching` weakly, as `fetching` holds it: the request in flight keeps both alive.
795
+ fetching->step = [this, weak = std::weak_ptr<Fetching>(fetching), kept, download, finish, done] {
796
+ auto fetching = weak.lock();
797
+ if (!fetching) {
798
+ return;
799
+ }
800
+ if (fetching->next == fetching->manifest.assets.size()) {
801
+ finish(*fetching);
802
+ return;
803
+ }
804
+ const auto asset = fetching->manifest.assets[fetching->next++];
805
+ const auto path = fetching->paths.at(asset.key);
806
+ for (const auto &folder : kept) {
807
+ try {
808
+ auto keptPaths = folly::parseJson(readFile(folder / "assets.json"));
809
+ const auto *keptPath = keptPaths.get_ptr(asset.key);
810
+ if (keptPath == nullptr || !keptPath->isString() || !fs::exists(folder / keptPath->asString())) {
811
+ continue;
812
+ }
813
+ auto bytes = readFile(folder / keptPath->asString());
814
+ if (base64Url(crypto_->sha256(bytes)) == asset.hash) {
815
+ fetching->files.emplace_back(path, std::move(bytes));
816
+ fetching->step();
817
+ return;
818
+ }
819
+ } catch (const std::exception &) {
820
+ // A kept update with no readable assets.json has nothing to give.
821
+ }
822
+ }
823
+ download(asset.url, "the asset " + asset.key, [this, fetching, asset, path, done](std::string bytes) {
824
+ if (base64Url(crypto_->sha256(bytes)) != asset.hash) {
825
+ done({.error = "the asset " + asset.key + "'s hash is not the manifest's: the update was not kept"});
826
+ return;
827
+ }
828
+ fetching->files.emplace_back(path, std::move(bytes));
829
+ fetching->step();
830
+ });
831
+ };
832
+
833
+ download(found->launchUrl, "the launch asset", [this, fetching, done](std::string bytes) {
834
+ if (base64Url(crypto_->sha256(bytes)) != fetching->manifest.launchHash) {
835
+ done({.error = "the launch asset's hash is not the manifest's: it was not kept"});
836
+ return;
837
+ }
838
+ // Where the bundle asks for each asset, or by its key where it does not register it.
839
+ auto registered = assetPathsInBundle(bytes);
840
+ for (const auto &asset : fetching->manifest.assets) {
841
+ auto at = registered.find(asset.key);
842
+ fetching->paths[asset.key] = at != registered.end() ? at->second : "assets/" + asset.key + asset.fileExtension;
843
+ }
844
+ fetching->files.emplace_back("launch-asset", std::move(bytes));
845
+ fetching->step();
846
+ });
847
+ }
848
+
849
+ std::shared_ptr<NativeModule> makeUpdatesModule(
850
+ std::shared_ptr<UpdatesClient> client,
851
+ bool development,
852
+ std::function<void(const std::string &bundle, std::function<void(bool)> done)> reload,
853
+ std::shared_ptr<AppUpdater> appUpdater) {
854
+ // Where the updater's news goes: this module while it lives, which a reload replaces.
855
+ struct Sink {
856
+ std::mutex mutex;
857
+ NativeModule *module{nullptr};
858
+ };
859
+ struct Updates : NativeModule {
860
+ std::shared_ptr<Sink> sink = std::make_shared<Sink>();
861
+ ~Updates() override {
862
+ std::lock_guard lock(sink->mutex);
863
+ sink->module = nullptr;
864
+ }
865
+ Updates(
866
+ std::shared_ptr<UpdatesClient> client,
867
+ bool development,
868
+ std::function<void(const std::string &, std::function<void(bool)>)> reload,
869
+ std::shared_ptr<AppUpdater> appUpdater)
870
+ : NativeModule("NgNativeUpdates") {
871
+ listeners();
872
+ property("isAppUpdaterAvailable", [appUpdater] { return folly::dynamic(appUpdater != nullptr); });
873
+ sync("isAppUpdateAvailable", [appUpdater](const folly::dynamic &) {
874
+ return folly::dynamic(appUpdater != nullptr && appUpdater->updateAvailable());
875
+ });
876
+ promise("checkForAppUpdateAsync", [appUpdater](const folly::dynamic &, JsPromise p) {
877
+ if (appUpdater) {
878
+ appUpdater->check();
879
+ }
880
+ p.resolve(appUpdater != nullptr);
881
+ });
882
+ if (appUpdater) {
883
+ sink->module = this;
884
+ appUpdater->onUpdateAvailable([sink = sink](bool available) {
885
+ std::lock_guard lock(sink->mutex);
886
+ if (sink->module != nullptr) {
887
+ static_cast<Updates *>(sink->module)->announce(available);
888
+ }
889
+ });
890
+ }
891
+ bool on = client->enabled() && !development;
892
+ property("isEnabled", [on] { return folly::dynamic(on); });
893
+ property("runtimeVersion", [client] { return folly::dynamic(client->config().runtimeVersion); });
894
+ property("updateId", [client] {
895
+ auto running = client->running();
896
+ return running ? folly::dynamic(running->id) : folly::dynamic(nullptr);
897
+ });
898
+ property("isEmbeddedLaunch", [client] { return folly::dynamic(!client->running()); });
899
+ // The running update's assets by file hash (the manifest's key), as `file:` URLs, which a
900
+ // macOS bundle's asset resolver looks in first: a Hermes bytecode bundle's own registrations
901
+ // cannot be read here, so its assets are kept by key rather than where it would look.
902
+ property("localAssets", [client] {
903
+ folly::dynamic assets = folly::dynamic::object();
904
+ for (const auto &[key, file] : client->localAssets()) {
905
+ assets[key] = fileUri(file);
906
+ }
907
+ return assets;
908
+ });
909
+ auto refuse = [on, development](JsPromise &p) {
910
+ if (on) {
911
+ return false;
912
+ }
913
+ p.reject(development ? "Updates are off in development, where the bundle comes from the dev server."
914
+ : "Updates are off: the app has no updates URL (updates.url in app.json).");
915
+ return true;
916
+ };
917
+ promise("checkForUpdateAsync", [client, refuse](const folly::dynamic &, JsPromise p) {
918
+ if (refuse(p)) {
919
+ return;
920
+ }
921
+ client->check([p](UpdatesClient::CheckResult r) {
922
+ if (!r.error.empty()) {
923
+ p.reject(r.error);
924
+ return;
925
+ }
926
+ p.resolve(folly::dynamic::object("isAvailable", r.isAvailable)("isRollBackToEmbedded", r.isRollBackToEmbedded)(
927
+ "manifest", r.manifest));
928
+ });
929
+ });
930
+ promise("fetchUpdateAsync", [client, refuse](const folly::dynamic &, JsPromise p) {
931
+ if (refuse(p)) {
932
+ return;
933
+ }
934
+ client->fetch([p](UpdatesClient::FetchResult r) {
935
+ if (!r.error.empty()) {
936
+ p.reject(r.error);
937
+ return;
938
+ }
939
+ p.resolve(folly::dynamic::object("isNew", r.isNew)("isRollBackToEmbedded", r.isRollBackToEmbedded)(
940
+ "manifest", r.manifest));
941
+ });
942
+ });
943
+ promise("reloadAsync", [client, refuse, reload](const folly::dynamic &, JsPromise p) {
944
+ if (refuse(p)) {
945
+ return;
946
+ }
947
+ if (!reload) {
948
+ p.reject("This host cannot reload.");
949
+ return;
950
+ }
951
+ // Resolved first: the reload tears down the runtime the promise belongs to. A bundle that
952
+ // does not load is the host's to report.
953
+ auto bundle = client->beginReload();
954
+ p.resolve(nullptr);
955
+ reload(bundle, [](bool) {});
956
+ });
957
+ }
958
+ void announce(bool available) {
959
+ emit("appUpdateAvailable", folly::dynamic::object("available", available));
960
+ }
961
+ };
962
+ return std::make_shared<Updates>(std::move(client), development, std::move(reload), std::move(appUpdater));
963
+ }
964
+
965
+ } // namespace ngn