@ng-native/desktop 0.26.0 → 0.27.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 (256) hide show
  1. package/README.md +6 -3
  2. package/bin/app-config.mjs +1 -0
  3. package/bin/archive.mjs +166 -0
  4. package/bin/autolink.mjs +61 -30
  5. package/bin/cli.mjs +127 -27
  6. package/bin/host.mjs +255 -58
  7. package/bin/package-linux.mjs +1394 -0
  8. package/bin/package.mjs +171 -35
  9. package/bin/plist.mjs +6 -2
  10. package/bin/png-icon.mjs +315 -0
  11. package/bin/prebuilt.mjs +147 -26
  12. package/bin/toolchain.mjs +258 -19
  13. package/native/CMakeLists.txt +64 -6
  14. package/native/appkit/CMakeLists.txt +2 -1
  15. package/native/appkit/appkit-backend.h +1 -0
  16. package/native/appkit/appkit-backend.mm +13 -0
  17. package/native/appkit/header-toolbar.mm +28 -25
  18. package/native/appkit/host-view.h +10 -0
  19. package/native/appkit/host-view.mm +146 -40
  20. package/native/appkit/input-replay.h +6 -0
  21. package/native/appkit/input-replay.mm +21 -12
  22. package/native/appkit/main.mm +11 -7
  23. package/native/appkit/native-controls.mm +13 -1
  24. package/native/appkit/split-view.mm +7 -13
  25. package/native/appkit/text-input-field.h +4 -0
  26. package/native/appkit/text-input-field.mm +20 -1
  27. package/native/cmake/curl.cmake +79 -0
  28. package/native/cmake/libraries/react-native-reanimated.cmake +5 -0
  29. package/native/cmake/libraries/react-native-worklets.cmake +5 -0
  30. package/native/cmake/linked-modules.cmake +20 -4
  31. package/native/cmake/react-native.cmake +18 -1
  32. package/native/core/include/ngn/accent-colors.h +38 -0
  33. package/native/core/include/ngn/accessibility-relations.h +65 -0
  34. package/native/core/include/ngn/accessibility.h +26 -0
  35. package/native/core/include/ngn/animated-frame-loop.h +56 -0
  36. package/native/core/include/ngn/app-info.h +24 -8
  37. package/native/core/include/ngn/app-menus.h +14 -1
  38. package/native/core/include/ngn/app-windows.h +15 -2
  39. package/native/core/include/ngn/aria-role.h +96 -0
  40. package/native/core/include/ngn/audio.h +2 -0
  41. package/native/core/include/ngn/camera.h +9 -0
  42. package/native/core/include/ngn/control-sizes.h +7 -2
  43. package/native/core/include/ngn/crash-report.h +31 -0
  44. package/native/core/include/ngn/curl-network.h +93 -0
  45. package/native/core/include/ngn/dbus-menu.h +39 -0
  46. package/native/core/include/ngn/default-menu.h +36 -0
  47. package/native/core/include/ngn/desktop-expo.h +7 -1
  48. package/native/core/include/ngn/desktop-modules.h +22 -0
  49. package/native/core/include/ngn/desktop-props.h +21 -1
  50. package/native/core/include/ngn/desktop-view-props.h +6 -0
  51. package/native/core/include/ngn/focus-order.h +10 -0
  52. package/native/core/include/ngn/header-bar.h +22 -0
  53. package/native/core/include/ngn/host-os.h +6 -0
  54. package/native/core/include/ngn/host-reload.h +21 -0
  55. package/native/core/include/ngn/host-state.h +23 -0
  56. package/native/core/include/ngn/image-source.h +26 -1
  57. package/native/core/include/ngn/input-script.h +3 -3
  58. package/native/core/include/ngn/input.h +4 -1
  59. package/native/core/include/ngn/launch-frame.h +21 -0
  60. package/native/core/include/ngn/launch-settings.h +23 -5
  61. package/native/core/include/ngn/mounting-backend.h +5 -0
  62. package/native/core/include/ngn/mounting-manager.h +1 -0
  63. package/native/core/include/ngn/native-controls.h +26 -5
  64. package/native/core/include/ngn/notification-schedule.h +74 -0
  65. package/native/core/include/ngn/notifications.h +2 -1
  66. package/native/core/include/ngn/openssl-update-crypto.h +15 -0
  67. package/native/core/include/ngn/photo-library.h +60 -20
  68. package/native/core/include/ngn/posix-locale.h +43 -0
  69. package/native/core/include/ngn/runtime.h +5 -0
  70. package/native/core/include/ngn/safe-areas.h +14 -2
  71. package/native/core/include/ngn/split-view.h +78 -0
  72. package/native/core/include/ngn/surface-metrics.h +7 -0
  73. package/native/core/include/ngn/system.h +14 -0
  74. package/native/core/include/ngn/text-input.h +13 -0
  75. package/native/core/include/ngn/text-units.h +38 -0
  76. package/native/core/include/ngn/updates.h +14 -2
  77. package/native/core/include/ngn/view-box.h +40 -0
  78. package/native/core/include/ngn/view-transform.h +15 -0
  79. package/native/core/include/ngn/web-browser.h +46 -0
  80. package/native/core/src/accent-colors.cpp +88 -0
  81. package/native/core/src/accessibility-relations.cpp +138 -0
  82. package/native/core/src/accessibility.cpp +50 -0
  83. package/native/core/src/animated-frame-loop.cpp +166 -0
  84. package/native/core/src/app-menus.cpp +26 -9
  85. package/native/core/src/app-windows.cpp +27 -6
  86. package/native/core/src/aria-role.cpp +127 -0
  87. package/native/core/src/control-sizes.cpp +9 -5
  88. package/native/core/src/crash-report.cpp +196 -0
  89. package/native/core/src/curl-network.cpp +1562 -0
  90. package/native/core/src/dbus-menu.cpp +71 -0
  91. package/native/core/src/default-menu.cpp +134 -0
  92. package/native/core/src/desktop-view-props.cpp +14 -0
  93. package/native/core/src/focus-order.cpp +19 -0
  94. package/native/core/src/header-bar.cpp +20 -0
  95. package/native/core/src/host-os.cpp +19 -0
  96. package/native/core/src/host-reload.cpp +45 -0
  97. package/native/core/src/host-state.cpp +8 -0
  98. package/native/core/src/image-source.cpp +90 -0
  99. package/native/core/src/input-dispatcher.cpp +27 -5
  100. package/native/core/src/input-script.cpp +3 -2
  101. package/native/core/src/launch-settings.cpp +76 -0
  102. package/native/core/src/libraries/react-native-reanimated.cpp +6 -1
  103. package/native/core/src/modules/app-info.cpp +55 -6
  104. package/native/core/src/modules/app-modules.cpp +1 -1
  105. package/native/core/src/modules/audio.cpp +4 -2
  106. package/native/core/src/modules/camera.cpp +8 -11
  107. package/native/core/src/modules/desktop-expo.cpp +10 -5
  108. package/native/core/src/modules/desktop-modules.cpp +106 -41
  109. package/native/core/src/modules/file-photo-picker.cpp +408 -0
  110. package/native/core/src/modules/notifications.cpp +13 -17
  111. package/native/core/src/modules/photo-library.cpp +42 -13
  112. package/native/core/src/modules/web-browser.cpp +89 -0
  113. package/native/core/src/mounting-manager.cpp +12 -0
  114. package/native/core/src/native-controls.cpp +42 -1
  115. package/native/core/src/notification-schedule.cpp +429 -0
  116. package/native/core/src/openssl-update-crypto.cpp +83 -0
  117. package/native/core/src/posix-locale.cpp +192 -0
  118. package/native/core/src/runtime.cpp +30 -1
  119. package/native/core/src/safe-areas.cpp +19 -4
  120. package/native/core/src/spawn-rules.cpp +4 -1
  121. package/native/core/src/split-view.cpp +93 -0
  122. package/native/core/src/system.cpp +19 -0
  123. package/native/core/src/text-input.cpp +18 -1
  124. package/native/core/src/text-units.cpp +99 -0
  125. package/native/core/src/updates.cpp +76 -17
  126. package/native/core/src/view-box.cpp +75 -40
  127. package/native/core/src/view-transform.cpp +28 -0
  128. package/native/docker/Dockerfile +38 -0
  129. package/native/docker/Dockerfile.fedora +36 -0
  130. package/native/docker/glibc-floor.sh +49 -0
  131. package/native/gtk/CMakeLists.txt +137 -0
  132. package/native/gtk/accent-colour.cpp +57 -0
  133. package/native/gtk/accent-colour.h +41 -0
  134. package/native/gtk/accessibility-settings.cpp +159 -0
  135. package/native/gtk/accessibility-settings.h +62 -0
  136. package/native/gtk/accessible-text.cpp +151 -0
  137. package/native/gtk/accessible-text.h +49 -0
  138. package/native/gtk/accessible.cpp +306 -0
  139. package/native/gtk/accessible.h +75 -0
  140. package/native/gtk/alerts.cpp +267 -0
  141. package/native/gtk/alerts.h +30 -0
  142. package/native/gtk/animation-frames.cpp +159 -0
  143. package/native/gtk/animation-frames.h +20 -0
  144. package/native/gtk/app-info.cpp +91 -0
  145. package/native/gtk/app-info.h +25 -0
  146. package/native/gtk/app-windows.cpp +439 -0
  147. package/native/gtk/app-windows.h +150 -0
  148. package/native/gtk/audio.cpp +370 -0
  149. package/native/gtk/audio.h +54 -0
  150. package/native/gtk/auth-session.cpp +73 -0
  151. package/native/gtk/auth-session.h +16 -0
  152. package/native/gtk/battery.cpp +110 -0
  153. package/native/gtk/battery.h +19 -0
  154. package/native/gtk/box-paint.cpp +262 -0
  155. package/native/gtk/box-paint.h +32 -0
  156. package/native/gtk/cairo-canvas.cpp +755 -0
  157. package/native/gtk/cairo-canvas.h +49 -0
  158. package/native/gtk/camera.cpp +909 -0
  159. package/native/gtk/camera.h +69 -0
  160. package/native/gtk/capture.cpp +46 -0
  161. package/native/gtk/capture.h +19 -0
  162. package/native/gtk/clock-format.cpp +151 -0
  163. package/native/gtk/clock-format.h +36 -0
  164. package/native/gtk/crypto.cpp +75 -0
  165. package/native/gtk/crypto.h +14 -0
  166. package/native/gtk/dbus-properties.cpp +131 -0
  167. package/native/gtk/dbus-properties.h +61 -0
  168. package/native/gtk/drag-and-drop.cpp +339 -0
  169. package/native/gtk/drag-and-drop.h +30 -0
  170. package/native/gtk/file-dialogs.cpp +239 -0
  171. package/native/gtk/file-dialogs.h +21 -0
  172. package/native/gtk/file-system.cpp +212 -0
  173. package/native/gtk/file-system.h +25 -0
  174. package/native/gtk/focus.cpp +282 -0
  175. package/native/gtk/focus.h +37 -0
  176. package/native/gtk/fonts.cpp +89 -0
  177. package/native/gtk/fonts.h +22 -0
  178. package/native/gtk/gst-frames.cpp +150 -0
  179. package/native/gtk/gst-frames.h +47 -0
  180. package/native/gtk/gst-playback.cpp +496 -0
  181. package/native/gtk/gst-playback.h +81 -0
  182. package/native/gtk/gtk-backend.cpp +690 -0
  183. package/native/gtk/gtk-backend.h +134 -0
  184. package/native/gtk/host-sources.cpp +354 -0
  185. package/native/gtk/host-sources.h +46 -0
  186. package/native/gtk/image-manipulator.cpp +254 -0
  187. package/native/gtk/image-manipulator.h +30 -0
  188. package/native/gtk/image-view.cpp +256 -0
  189. package/native/gtk/image-view.h +54 -0
  190. package/native/gtk/input-replay.cpp +299 -0
  191. package/native/gtk/input-replay.h +36 -0
  192. package/native/gtk/launcher-badge.cpp +29 -0
  193. package/native/gtk/launcher-badge.h +21 -0
  194. package/native/gtk/locales.cpp +131 -0
  195. package/native/gtk/locales.h +23 -0
  196. package/native/gtk/location.cpp +274 -0
  197. package/native/gtk/location.h +19 -0
  198. package/native/gtk/main.cpp +1092 -0
  199. package/native/gtk/menus.cpp +447 -0
  200. package/native/gtk/menus.h +100 -0
  201. package/native/gtk/native-controls.cpp +831 -0
  202. package/native/gtk/native-controls.h +58 -0
  203. package/native/gtk/network-state.cpp +72 -0
  204. package/native/gtk/network-state.h +24 -0
  205. package/native/gtk/notifications.cpp +235 -0
  206. package/native/gtk/notifications.h +30 -0
  207. package/native/gtk/pango-text.cpp +274 -0
  208. package/native/gtk/pango-text.h +73 -0
  209. package/native/gtk/portal.cpp +451 -0
  210. package/native/gtk/portal.h +71 -0
  211. package/native/gtk/printing.cpp +338 -0
  212. package/native/gtk/printing.h +34 -0
  213. package/native/gtk/proxy-resolver.cpp +74 -0
  214. package/native/gtk/proxy-resolver.h +20 -0
  215. package/native/gtk/screens.cpp +1461 -0
  216. package/native/gtk/screens.h +274 -0
  217. package/native/gtk/scroll-view.cpp +414 -0
  218. package/native/gtk/scroll-view.h +82 -0
  219. package/native/gtk/secret-store.cpp +120 -0
  220. package/native/gtk/secret-store.h +27 -0
  221. package/native/gtk/settings-portal.cpp +129 -0
  222. package/native/gtk/settings-portal.h +47 -0
  223. package/native/gtk/split-view.cpp +1105 -0
  224. package/native/gtk/split-view.h +195 -0
  225. package/native/gtk/status-notifier.cpp +487 -0
  226. package/native/gtk/status-notifier.h +43 -0
  227. package/native/gtk/surface-input.cpp +251 -0
  228. package/native/gtk/surface-input.h +57 -0
  229. package/native/gtk/system-access.cpp +295 -0
  230. package/native/gtk/system-access.h +37 -0
  231. package/native/gtk/text-field.cpp +827 -0
  232. package/native/gtk/text-field.h +78 -0
  233. package/native/gtk/video.cpp +527 -0
  234. package/native/gtk/video.h +47 -0
  235. package/native/gtk/view-widget.cpp +431 -0
  236. package/native/gtk/view-widget.h +105 -0
  237. package/native/gtk/window-scale.cpp +95 -0
  238. package/native/gtk/window-scale.h +35 -0
  239. package/native/scripts/atspi-check.py +310 -0
  240. package/native/scripts/atspi-check.test.py +48 -0
  241. package/native/scripts/build.sh +20 -3
  242. package/native/scripts/compilers.sh +17 -0
  243. package/native/scripts/deb-depends-check.sh +22 -0
  244. package/native/scripts/fetch.sh +23 -2
  245. package/native/scripts/launch-cell.sh +157 -0
  246. package/native/scripts/launch-probe.sh +14 -3
  247. package/native/scripts/make-prebuilt.mjs +133 -44
  248. package/native/scripts/prebuilt-host-cache.mjs +71 -40
  249. package/native/scripts/reset-for-compilers.sh +44 -0
  250. package/native/scripts/start-xvfb.sh +35 -0
  251. package/native/shim/paragraph-platform/react/renderer/components/text/HostPlatformParagraphProps.h +35 -0
  252. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +5 -2
  253. package/native/shim/worklets/linux-reanimated-props.h +14 -0
  254. package/native/shim/worklets/linux-worklets.h +23 -0
  255. package/package.json +6 -3
  256. package/prebuilt.json +70 -6
@@ -0,0 +1,1394 @@
1
+ /**
2
+ * `ng-native-desktop package --os linux`: the app as something to hand to someone on Linux, one
3
+ * package per architecture.
4
+ *
5
+ * - `--format app` (the default): a runnable folder, `bin/`, `lib/` and `share/` as a prefix lays
6
+ * them out, and the same folder as a `.tar.gz`, with a detached GPG signature when `NGN_GPG_KEY`
7
+ * names a key.
8
+ * - `--format deb`: for Debian and Ubuntu, on the system's GTK, written in JavaScript.
9
+ * - `--format rpm`: for Fedora and the RHEL family, on the system's GTK, by `rpmbuild`, which writes
10
+ * the libraries the binary links as requirements; signed by `rpmsign` with `NGN_GPG_KEY`.
11
+ * - `--format flatpak`: sandboxed, on the GNOME runtime: a `.flatpak` bundle per architecture, an
12
+ * OSTree repository to serve as the app's own remote (signed with `NGN_GPG_KEY`), and the manifest
13
+ * it was built from. What the sandbox takes away is named before it is built.
14
+ *
15
+ * Each installs `<app id>.desktop`, the icon in the hicolor theme's sizes and
16
+ * `<app id>.metainfo.xml`, and the host reads its settings from `metadata.json` beside the bundle,
17
+ * as a macOS app reads its `Info.plist`. The JavaScript is compiled to Hermes bytecode once, for
18
+ * every architecture: the bytecode does not depend on one. The packages carry no updater of their
19
+ * own: the package manager or Flatpak updates the app, and Expo Updates its JavaScript.
20
+ *
21
+ * `app` and `deb` need no tools beyond Node. `rpm` and `flatpak` run `rpmbuild` and
22
+ * `flatpak-builder`, on Linux when they are installed and otherwise in a container through Docker or
23
+ * Podman (AlmaLinux 9 for rpm, Fedora 44 for flatpak), which is how a Mac makes them.
24
+ */
25
+ import { createHash } from 'node:crypto';
26
+ import { homedir } from 'node:os';
27
+ import path from 'node:path';
28
+
29
+ import { desktopAppConfig, hostCapabilities } from './app-config.mjs';
30
+ import { ar, tarGz, withFolders } from './archive.mjs';
31
+ import {
32
+ linuxHermesCompiler,
33
+ prepareHost,
34
+ readExpoConfig,
35
+ resolveReactNative,
36
+ UsageError,
37
+ } from './host.mjs';
38
+ import { escape } from './plist.mjs';
39
+ import { decodePng, encodePng, scaleImage } from './png-icon.mjs';
40
+
41
+ /**
42
+ * @typedef {import('./host.mjs').system} System
43
+ * @typedef {import('./app-config.mjs').DesktopAppConfig} DesktopAppConfig
44
+ * @typedef {import('./app-config.mjs').ExpoConfig} ExpoConfig
45
+ * @typedef {import('./archive.mjs').ArchiveEntry} ArchiveEntry
46
+ * @typedef {'x64' | 'arm64'} LinuxArch
47
+ * @typedef {'app' | 'deb' | 'rpm' | 'flatpak'} LinuxFormat
48
+ * @typedef {{ format: LinuxFormat, arch: LinuxArch | 'all', output: string, license?: string, homepage?: string, categories?: string, maintainer?: string }} LinuxPackageCommand
49
+ */
50
+
51
+ export const LINUX_FORMATS = /** @type {const} */ (['app', 'deb', 'rpm', 'flatpak']);
52
+
53
+ /** Each architecture by the name each format gives it. */
54
+ export const LINUX_ARCHES = {
55
+ x64: { deb: 'amd64', rpm: 'x86_64', flatpak: 'x86_64' },
56
+ arm64: { deb: 'arm64', rpm: 'aarch64', flatpak: 'aarch64' },
57
+ };
58
+
59
+ /**
60
+ * The oldest of each system library a `deb` or `rpm` runs on: Ubuntu 24.04, Debian 13 and Fedora 44
61
+ * have newer, and the host is built against AlmaLinux 9's glibc. A Flatpak brings its own.
62
+ */
63
+ export const LINUX_MINIMUMS = { glibc: '2.34', gtk: '4.10', libadwaita: '1.4', gstreamer: '1.22' };
64
+
65
+ /** The GNOME runtime a Flatpak runs on, a new one each year. */
66
+ export const FLATPAK_RUNTIME = {
67
+ runtime: 'org.gnome.Platform',
68
+ sdk: 'org.gnome.Sdk',
69
+ version: '50',
70
+ };
71
+
72
+ /** The hicolor sizes the icon is scaled to, up to the size it is. */
73
+ export const ICON_SIZES = [16, 24, 32, 48, 64, 128, 256, 512];
74
+
75
+ /** The freedesktop main categories, one of which a desktop entry needs. */
76
+ const MAIN_CATEGORIES = [
77
+ 'AudioVideo',
78
+ 'Audio',
79
+ 'Video',
80
+ 'Development',
81
+ 'Education',
82
+ 'Game',
83
+ 'Graphics',
84
+ 'Network',
85
+ 'Office',
86
+ 'Science',
87
+ 'Settings',
88
+ 'System',
89
+ 'Utility',
90
+ ];
91
+
92
+ /**
93
+ * The longest package name. `bin/<name>` links to `../lib/<name>/ngn-app`, which a tar header holds
94
+ * at 100 bytes or fewer, and this keeps it well within.
95
+ */
96
+ const MAX_SLUG = 64;
97
+
98
+ /** The host's file in `lib/<name>/`, named the same for every app so that no slug can name another file there. */
99
+ const HOST_FILE = 'ngn-app';
100
+
101
+ /** The file the bundle is in, beside the host, as on macOS. */
102
+ const BUNDLE_FILE = 'main.jsbundle';
103
+
104
+ /** The license of the generated metainfo itself, which AppStream asks for. */
105
+ const METADATA_LICENSE = 'CC0-1.0';
106
+
107
+ /**
108
+ * The flags `--os linux` takes, checked: `--categories` a list of freedesktop categories with a main
109
+ * one, `--homepage` an https URL, and `--license` an SPDX expression, which an rpm and a Flatpak
110
+ * need.
111
+ *
112
+ * @param {{ format: string, license?: string, homepage?: string, categories?: string, maintainer?: string }} values
113
+ */
114
+ export function checkLinuxFlags({ format, license, homepage, categories, maintainer }) {
115
+ if (license === undefined && (format === 'rpm' || format === 'flatpak')) {
116
+ throw new UsageError(
117
+ `--format ${format} needs --license, the app's SPDX license (MIT, GPL-3.0-or-later, ` +
118
+ 'LicenseRef-proprietary), which the package and its metainfo state.',
119
+ );
120
+ }
121
+ if (license !== undefined && !isSpdxExpression(license)) {
122
+ throw new UsageError(`--license takes an SPDX license expression, not "${license}".`);
123
+ }
124
+ if (homepage !== undefined && !isWebUrl(homepage)) {
125
+ throw new UsageError(`--homepage takes the URL of the app's page, not "${homepage}".`);
126
+ }
127
+ if (categories !== undefined) categoryList(categories);
128
+ checkMaintainer(format, maintainer);
129
+ }
130
+
131
+ /**
132
+ * Whether `value` is an SPDX license expression: ids (a `LicenseRef-` one too), `WITH` an
133
+ * exception, `AND`, `OR` and parentheses, complete, so `MIT AND` is not.
134
+ *
135
+ * @param {string} value
136
+ */
137
+ function isSpdxExpression(value) {
138
+ const tokens = value.match(/[()]|[^\s()]+/g) ?? [];
139
+ const id =
140
+ /^(?:(?:DocumentRef-[A-Za-z0-9.-]+:)?LicenseRef-[A-Za-z0-9.-]+|[A-Za-z0-9][A-Za-z0-9.-]*\+?)$/;
141
+ let at = 0;
142
+ const word = () => {
143
+ const token = tokens[at];
144
+ if (token === undefined || !id.test(token) || ['AND', 'OR', 'WITH'].includes(token)) {
145
+ return false;
146
+ }
147
+ at++;
148
+ return true;
149
+ };
150
+ const term = () => {
151
+ if (tokens[at] === '(') {
152
+ at++;
153
+ if (!compound() || tokens[at] !== ')') return false;
154
+ at++;
155
+ return true;
156
+ }
157
+ if (!word()) return false;
158
+ if (tokens[at] !== 'WITH') return true;
159
+ at++;
160
+ return word();
161
+ };
162
+ const compound = () => {
163
+ if (!term()) return false;
164
+ while (tokens[at] === 'AND' || tokens[at] === 'OR') {
165
+ at++;
166
+ if (!term()) return false;
167
+ }
168
+ return true;
169
+ };
170
+ return compound() && at === tokens.length;
171
+ }
172
+
173
+ /**
174
+ * Whether `value` is, all of it, an http or https URL with a host: no whitespace or control
175
+ * character, which would end the field it is written into and start another.
176
+ *
177
+ * @param {string} value
178
+ */
179
+ function isWebUrl(value) {
180
+ if (/[\u0000-\u0020\u007f-\u009f]/.test(value)) return false;
181
+ try {
182
+ const url = new URL(value);
183
+ return (url.protocol === 'https:' || url.protocol === 'http:') && url.hostname !== '';
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * `--maintainer`: a name and an email, which a deb needs.
191
+ *
192
+ * @param {string} format
193
+ * @param {string | undefined} maintainer
194
+ */
195
+ function checkMaintainer(format, maintainer) {
196
+ if (maintainer === undefined && format === 'deb') {
197
+ throw new UsageError(
198
+ '--format deb needs --maintainer, the name and email a Debian package names as its ' +
199
+ 'maintainer: --maintainer "Ada Lovelace <ada@example.com>".',
200
+ );
201
+ }
202
+ if (maintainer !== undefined && !/^[^<>\n]+ <[^<>\s@]+@[^<>\s]+>$/.test(maintainer)) {
203
+ throw new UsageError(
204
+ `--maintainer takes a name and an email, as "Ada Lovelace <ada@example.com>", not "${maintainer}".`,
205
+ );
206
+ }
207
+ }
208
+
209
+ /**
210
+ * `--categories` as a list, `Utility` when none are given. Throws unless one is a main category.
211
+ *
212
+ * @param {string | undefined} categories
213
+ */
214
+ export function categoryList(categories) {
215
+ if (categories === undefined) return ['Utility'];
216
+ const list = categories
217
+ .split(/[;,]/)
218
+ .map((each) => each.trim())
219
+ .filter(Boolean);
220
+ const bad = list.find((each) => !/^[A-Za-z0-9-]+$/.test(each));
221
+ if (bad !== undefined)
222
+ throw new UsageError(`--categories has "${bad}", which is not a category.`);
223
+ if (!list.some((each) => MAIN_CATEGORIES.includes(each))) {
224
+ throw new UsageError(
225
+ `--categories needs one of the main categories: ${MAIN_CATEGORIES.join(', ')}.`,
226
+ );
227
+ }
228
+ return [...new Set(list)];
229
+ }
230
+
231
+ /**
232
+ * The last part of the id made up for an `app` build: the slug's letters and digits, and `app` before
233
+ * a first digit, which a part of an id cannot start with (`2048` is `app2048`).
234
+ *
235
+ * @param {string} slug
236
+ */
237
+ function idPart(slug) {
238
+ const letters = slug.replace(/[^a-z0-9]/g, '') || 'app';
239
+ return /^\d/.test(letters) ? `app${letters}` : letters;
240
+ }
241
+
242
+ /**
243
+ * Throws a usage error for an id whose longest generated file name, `<id>.metainfo.xml`, is more
244
+ * than the 100 bytes a tar header holds. The id is the app's identity, so it is not shortened.
245
+ *
246
+ * @param {string} appId
247
+ */
248
+ function checkIdLength(appId) {
249
+ if (Buffer.byteLength(`${appId}.metainfo.xml`) > 100) {
250
+ throw new UsageError(
251
+ `The application id "${appId}" is too long: its metainfo file, ${appId}.metainfo.xml, takes ` +
252
+ 'more than the 100 bytes an archive holds. Shorten expo.ios.bundleIdentifier to 87 ' +
253
+ 'bytes or fewer.',
254
+ );
255
+ }
256
+ }
257
+
258
+ /**
259
+ * The application id `linuxNames` gives a package, checked for Linux and, for a Flatpak, Flathub.
260
+ *
261
+ * @param {string | null} bundleIdentifier
262
+ * @param {LinuxFormat} format
263
+ * @param {string} slug
264
+ */
265
+ function linuxAppId(bundleIdentifier, format, slug) {
266
+ if (bundleIdentifier === null && format !== 'app') {
267
+ throw new UsageError(
268
+ `--format ${format} names the app's files and its desktop entry by its id, and app.json ` +
269
+ 'sets none. Set expo.ios.bundleIdentifier, which the desktop OSes share with iOS.',
270
+ );
271
+ }
272
+ const appId = bundleIdentifier ?? `dev.ngnative.${idPart(slug)}`;
273
+ const part = /^[A-Za-z_][A-Za-z0-9_-]*$/;
274
+ const parts = appId.split('.');
275
+ if (parts.length < 2 || !parts.every((each) => part.test(each)) || appId.length > 255) {
276
+ throw new UsageError(
277
+ `The bundle identifier "${appId}" is not an application id Linux takes: two or more parts ` +
278
+ 'of letters, digits, _ and -, none starting with a digit.',
279
+ );
280
+ }
281
+ const flathub =
282
+ parts.length >= 3 &&
283
+ parts.length <= 5 &&
284
+ parts.slice(0, -1).every((each) => !each.includes('-'));
285
+ if (format === 'flatpak' && !flathub) {
286
+ throw new UsageError(
287
+ `A Flatpak's id has three to five parts with a dash only in the last, and "${appId}" does ` +
288
+ 'not. Change expo.ios.bundleIdentifier, or package another format.',
289
+ );
290
+ }
291
+ return appId;
292
+ }
293
+
294
+ /**
295
+ * The names a Linux package goes by: the application id, which names the desktop entry, the icon and
296
+ * the metainfo and is the host's GApplication id; the package and command name, from the slug; and
297
+ * the version. Throws a usage error for one the format cannot take.
298
+ *
299
+ * - The id is `ios.bundleIdentifier`, which the desktop OSes share with iOS. An `app` build makes one
300
+ * up from the slug when the app sets none, as a macOS `app` build does; the others need it. A
301
+ * Flatpak's id has three to five parts with a dash only in the last, as Flathub asks.
302
+ *
303
+ * @param {ExpoConfig} expo
304
+ * @param {DesktopAppConfig} config
305
+ * @param {LinuxFormat} format
306
+ */
307
+ export function linuxNames(expo, config, format) {
308
+ const slug = linuxSlug(expo, config);
309
+ if (slug.length < 2) {
310
+ throw new UsageError(
311
+ `The slug "${expo.slug ?? config.name}" makes no package name, which needs two letters or ` +
312
+ 'digits. Set expo.slug in app.json.',
313
+ );
314
+ }
315
+ if (slug.length > MAX_SLUG) {
316
+ throw new UsageError(
317
+ `The slug "${slug}" makes a package name of ${slug.length} characters, and a Linux package ` +
318
+ `takes ${MAX_SLUG} at most. Shorten expo.slug in app.json.`,
319
+ );
320
+ }
321
+ const appId = linuxAppId(config.bundleIdentifier, format, slug);
322
+ checkIdLength(appId);
323
+ const version = config.version;
324
+ if (!/^\d[A-Za-z0-9.+~]*$/.test(version)) {
325
+ throw new UsageError(
326
+ `The version "${version}" is not one a Linux package takes: a digit first, then letters, ` +
327
+ 'digits, ., + and ~. Change "version" in app.json.',
328
+ );
329
+ }
330
+ return { appId, packageName: slug, version };
331
+ }
332
+
333
+ /**
334
+ * The slug a Linux package and its command are named for, lowercased into the letters a package
335
+ * name takes.
336
+ *
337
+ * @param {ExpoConfig} expo
338
+ * @param {DesktopAppConfig} config
339
+ */
340
+ function linuxSlug(expo, config) {
341
+ return String(expo.slug ?? config.name)
342
+ .toLowerCase()
343
+ .replace(/[^a-z0-9+.-]+/g, '-')
344
+ .replace(/^[^a-z0-9]+|[-.]+$/g, '');
345
+ }
346
+
347
+ /**
348
+ * The GApplication id a dev run (`ng-native-desktop run --os linux`) gives the host: the one an
349
+ * `app` package of the same app has. Throws a usage error for a bundle identifier Linux cannot
350
+ * take.
351
+ *
352
+ * @param {ExpoConfig} expo
353
+ * @param {DesktopAppConfig} config
354
+ */
355
+ export function linuxRunAppId(expo, config) {
356
+ return linuxAppId(config.bundleIdentifier, 'app', linuxSlug(expo, config));
357
+ }
358
+
359
+ /**
360
+ * @typedef {{ appId: string, packageName: string, version: string }} LinuxNames
361
+ * @typedef {LinuxNames & { name: string, summary: string, description: string, categories: string[], schemes: string[], mimeTypes?: string[], icon: boolean, license?: string, homepage?: string, maintainer?: string, released: string }} LinuxApp
362
+ */
363
+
364
+ /**
365
+ * A desktop entry value: one line, with the spec's escapes.
366
+ *
367
+ * @param {string} value
368
+ */
369
+ function entryValue(value) {
370
+ return value.replace(/\\/g, '\\\\').replace(/\r?\n/g, ' ').replace(/\t/g, ' ');
371
+ }
372
+
373
+ /**
374
+ * Where each installed format puts the app's tree; the `app` folder runs from wherever it is
375
+ * unpacked, so it has none.
376
+ *
377
+ * @type {Partial<Record<LinuxFormat, string>>}
378
+ */
379
+ export const LINUX_PREFIX = { deb: '/usr', rpm: '/usr', flatpak: '/app' };
380
+
381
+ /**
382
+ * The app's desktop entry, `<app id>.desktop`, which launchers list it by. Its document types'
383
+ * MIME types and its URL schemes, as `x-scheme-handler` types, are what it opens: with the files
384
+ * or the link in `%U`, or, where it is installed with its D-Bus service (`dbusActivatable`), through
385
+ * the session bus, which starts it if it is not running and hands a running one the files or
386
+ * the link. Wayland matches the window to the entry by its name, the host's app id.
387
+ *
388
+ * @param {LinuxApp} app
389
+ * @param {{ dbusActivatable?: boolean }} [options]
390
+ */
391
+ export function desktopEntry(app, { dbusActivatable = false } = {}) {
392
+ const types = [
393
+ ...(app.mimeTypes ?? []),
394
+ ...app.schemes.map((scheme) => `x-scheme-handler/${scheme}`),
395
+ ];
396
+ const lines = [
397
+ '[Desktop Entry]',
398
+ 'Type=Application',
399
+ `Name=${entryValue(app.name)}`,
400
+ `Comment=${entryValue(app.summary)}`,
401
+ `Exec=${app.packageName} %U`,
402
+ ...(app.icon ? [`Icon=${app.appId}`] : []),
403
+ 'Terminal=false',
404
+ ...(dbusActivatable ? ['DBusActivatable=true'] : []),
405
+ `Categories=${app.categories.join(';')};`,
406
+ ...(types.length > 0 ? [`MimeType=${types.map((type) => `${type};`).join('')}`] : []),
407
+ `StartupWMClass=${app.appId}`,
408
+ ];
409
+ return `${lines.join('\n')}\n`;
410
+ }
411
+
412
+ /**
413
+ * The app's D-Bus service, `<app id>.service`, which lets the session bus start it by its id for
414
+ * a desktop entry with `DBusActivatable=true`. The host takes `--gapplication-service` to start as
415
+ * that service.
416
+ *
417
+ * @param {LinuxApp} app
418
+ * @param {string} prefix where the format installs the tree (LINUX_PREFIX)
419
+ */
420
+ export function dbusService(app, prefix) {
421
+ return [
422
+ '[D-BUS Service]',
423
+ `Name=${app.appId}`,
424
+ `Exec=${prefix}/bin/${app.packageName} --gapplication-service`,
425
+ '',
426
+ ].join('\n');
427
+ }
428
+
429
+ /**
430
+ * The app's AppStream metainfo, `<app id>.metainfo.xml`, which GNOME Software, Discover and a
431
+ * Flatpak remote list it by: the Expo `name`, `description` and `version`, and what `package` was
432
+ * told of the license, the homepage and the developer.
433
+ *
434
+ * @param {LinuxApp} app
435
+ */
436
+ export function metainfo(app) {
437
+ const developer = app.maintainer?.replace(/\s*<.*$/, '');
438
+ const lines = [
439
+ '<?xml version="1.0" encoding="UTF-8"?>',
440
+ '<component type="desktop-application">',
441
+ ` <id>${escape(app.appId)}</id>`,
442
+ ` <metadata_license>${METADATA_LICENSE}</metadata_license>`,
443
+ ...(app.license ? [` <project_license>${escape(app.license)}</project_license>`] : []),
444
+ ` <name>${escape(app.name)}</name>`,
445
+ ` <summary>${escape(app.summary)}</summary>`,
446
+ ...(developer
447
+ ? [
448
+ ` <developer id="${escape(app.appId.split('.').slice(0, -1).join('.'))}">`,
449
+ ` <name>${escape(developer)}</name>`,
450
+ ' </developer>',
451
+ ]
452
+ : []),
453
+ ' <description>',
454
+ ` <p>${escape(app.description)}</p>`,
455
+ ' </description>',
456
+ ` <launchable type="desktop-id">${escape(app.appId)}.desktop</launchable>`,
457
+ ...(app.homepage ? [` <url type="homepage">${escape(app.homepage)}</url>`] : []),
458
+ ' <provides>',
459
+ ` <binary>${escape(app.packageName)}</binary>`,
460
+ ' </provides>',
461
+ ' <content_rating type="oars-1.1" />',
462
+ ' <releases>',
463
+ ` <release version="${escape(app.version)}" date="${app.released}" />`,
464
+ ' </releases>',
465
+ '</component>',
466
+ ];
467
+ return `${lines.join('\n')}\n`;
468
+ }
469
+
470
+ /**
471
+ * What the host reads before JavaScript runs, beside the bundle: the keys a macOS app's
472
+ * `Info.plist` gives it, so one lookup in the core serves both. The format names the package, so
473
+ * `Updates` knows no whole-app updater is built in.
474
+ *
475
+ * @param {DesktopAppConfig} config
476
+ * @param {{ format: LinuxFormat, appId: string, updatesCertificate?: string }} options
477
+ */
478
+ export function linuxMetadata(config, { format, appId, updatesCertificate }) {
479
+ const signing = updatesCertificate
480
+ ? {
481
+ NGNUpdatesCodeSigningCertificate: updatesCertificate,
482
+ NGNUpdatesCodeSigningKeyId: config.updatesCodeSigning?.keyId ?? 'main',
483
+ NGNUpdatesCodeSigningAlg: config.updatesCodeSigning?.alg ?? 'rsa-v1_5-sha256',
484
+ }
485
+ : {};
486
+ const all = {
487
+ CFBundleName: config.name,
488
+ CFBundleIdentifier: appId,
489
+ CFBundleShortVersionString: config.version,
490
+ CFBundleVersion: config.buildNumber,
491
+ NGNBundleFile: BUNDLE_FILE,
492
+ NGNModuleName: 'main',
493
+ NGNDistribution: format,
494
+ NGNCapabilities: hostCapabilities(config.options),
495
+ NGNUpdatesURL: config.updatesUrl,
496
+ NGNRuntimeVersion: config.runtimeVersion,
497
+ ...signing,
498
+ };
499
+ const set = Object.entries(all).filter(([, value]) => value !== undefined && value !== null);
500
+ return `${JSON.stringify(Object.fromEntries(set), null, 2)}\n`;
501
+ }
502
+
503
+ /**
504
+ * What a `.deb` depends on: the floor the host is built for, every other library the host links
505
+ * (the static libcurl's OpenSSL 3, nghttp2 and zlib, SQLite, libatomic and the C++ runtime), and
506
+ * glib-networking, the GIO module GLib's proxy resolver reads the desktop's proxy settings through,
507
+ * under the package names Debian 13 and Ubuntu 24.04 share. dpkg does not read the binary, so a
508
+ * library left out here is missing on a system without it: CI installs only these into a clean
509
+ * Ubuntu 24.04 and checks that every library the built host needs is found
510
+ * (`native/scripts/deb-depends-check.sh`).
511
+ */
512
+ export const DEB_DEPENDS = [
513
+ `libc6 (>= ${LINUX_MINIMUMS.glibc})`,
514
+ `libgtk-4-1 (>= ${LINUX_MINIMUMS.gtk})`,
515
+ `libadwaita-1-0 (>= ${LINUX_MINIMUMS.libadwaita})`,
516
+ 'libsecret-1-0',
517
+ 'glib-networking',
518
+ `libgstreamer1.0-0 (>= ${LINUX_MINIMUMS.gstreamer})`,
519
+ `libgstreamer-plugins-base1.0-0 (>= ${LINUX_MINIMUMS.gstreamer})`,
520
+ // Loaded rather than linked: playbin3 and the converters (base), PulseAudio's sink and source,
521
+ // which PipeWire answers too (pulseaudio), and the WAV, Ogg, MP4 and VP9 elements (good).
522
+ 'gstreamer1.0-plugins-base',
523
+ 'gstreamer1.0-plugins-good',
524
+ 'gstreamer1.0-pulseaudio',
525
+ 'libssl3t64',
526
+ 'libnghttp2-14',
527
+ 'zlib1g',
528
+ 'libsqlite3-0',
529
+ 'libatomic1',
530
+ 'libstdc++6',
531
+ ];
532
+
533
+ /**
534
+ * Why a `.deb` around a host built on this machine may not run where it installs: its `Depends`
535
+ * floors are those of the prebuilt host, built on AlmaLinux 9, and a host built against a newer
536
+ * distribution's libraries can need newer ones than they say. An rpm's own scanner reads what the
537
+ * host links, and a Flatpak brings its runtime, so neither is warned.
538
+ *
539
+ * @param {LinuxArch} arch
540
+ */
541
+ export function selfBuiltDebWarning(arch) {
542
+ const m = LINUX_MINIMUMS;
543
+ return (
544
+ `No prebuilt Linux ${arch} host fits this app, so the .deb holds one built on this machine. Its ` +
545
+ `dependencies (glibc ${m.glibc}, GTK ${m.gtk}, libadwaita ${m.libadwaita} and GStreamer ` +
546
+ `${m.gstreamer} or later) hold for the prebuilt host, built on AlmaLinux 9, and the one built ` +
547
+ 'here may need newer libraries than they say. Package on AlmaLinux 9, or use the prebuilt host, ' +
548
+ 'for a .deb that installs only where it runs.'
549
+ );
550
+ }
551
+
552
+ /**
553
+ * A `.deb`'s `control` file, depending on `DEB_DEPENDS`.
554
+ *
555
+ * @param {LinuxApp} app
556
+ * @param {{ arch: LinuxArch, installedKiB: number }} build
557
+ */
558
+ export function debControl(app, { arch, installedKiB }) {
559
+ const lines = [
560
+ `Package: ${app.packageName}`,
561
+ `Version: ${app.version}`,
562
+ `Architecture: ${LINUX_ARCHES[arch].deb}`,
563
+ `Maintainer: ${app.maintainer}`,
564
+ `Installed-Size: ${installedKiB}`,
565
+ `Depends: ${DEB_DEPENDS.join(', ')}`,
566
+ // AAC and HLS, which most MP4 audio and streams need. Suggested, not recommended: Debian's and
567
+ // Ubuntu's bad plugins depend on openh264, and a default install pulls in no H.264 decoder.
568
+ 'Suggests: gstreamer1.0-plugins-bad',
569
+ // pipewiresrc, the camera's stream from the Camera portal.
570
+ 'Recommends: gstreamer1.0-pipewire',
571
+ 'Section: misc',
572
+ 'Priority: optional',
573
+ ...(app.homepage ? [`Homepage: ${app.homepage}`] : []),
574
+ `Description: ${app.summary}`,
575
+ ` ${app.description.replace(/\r?\n/g, ' ')}`,
576
+ ];
577
+ return `${lines.join('\n')}\n`;
578
+ }
579
+
580
+ /**
581
+ * An rpm spec that copies the prepared folder into `/usr`. rpm's own scanner adds a requirement
582
+ * for each library the binary links; the floor is named on top, under Fedora's and the RHEL
583
+ * family's package names. Nothing is stripped or compiled: the host comes stripped.
584
+ *
585
+ * @param {LinuxApp} app
586
+ * @param {{ tree: string }} build the prepared folder, by its absolute path where rpmbuild runs
587
+ */
588
+ export function rpmSpec(app, { tree }) {
589
+ const m = LINUX_MINIMUMS;
590
+ // rpm expands a macro anywhere in the spec, so a literal % is written twice.
591
+ const text = (/** @type {string} */ value) => value.replace(/%/g, '%%');
592
+ const lines = [
593
+ `Name: ${app.packageName}`,
594
+ `Version: ${app.version}`,
595
+ 'Release: 1',
596
+ `Summary: ${text(app.summary)}`,
597
+ `License: ${app.license}`,
598
+ ...(app.homepage ? [`URL: ${text(app.homepage)}`] : []),
599
+ ...(app.maintainer ? [`Packager: ${text(app.maintainer)}`] : []),
600
+ `Requires: gtk4 >= ${m.gtk}`,
601
+ `Requires: libadwaita >= ${m.libadwaita}`,
602
+ 'Requires: libsecret',
603
+ // A GIO module, loaded rather than linked, so rpm's scanner does not find it.
604
+ 'Requires: glib-networking',
605
+ `Requires: gstreamer1 >= ${m.gstreamer}`,
606
+ `Requires: gstreamer1-plugins-base >= ${m.gstreamer}`,
607
+ // Plugins, loaded rather than linked: PulseAudio's sink and source, WAV, Ogg, MP4 and VP9.
608
+ 'Requires: gstreamer1-plugins-good',
609
+ // AAC and HLS, which most MP4 audio and streams need; never a patented decoder such as H.264's.
610
+ // Fedora's and RHEL's bad-free plugins have no H.264 decoder.
611
+ 'Recommends: gstreamer1-plugins-bad-free',
612
+ // pipewiresrc, the camera's stream from the Camera portal.
613
+ 'Recommends: pipewire-gstreamer',
614
+ // The host is stripped when it is built; rpm's own steps would strip it or look for debug info.
615
+ '%global debug_package %{nil}',
616
+ '%global __os_install_post %{nil}',
617
+ '',
618
+ '%description',
619
+ text(app.description),
620
+ '',
621
+ '%install',
622
+ // The build root is under the project, so its path may have a space: quoted in each command.
623
+ 'mkdir -p "$RPM_BUILD_ROOT/usr"',
624
+ `cp -a ${text(shellQuote(`${tree}/.`))} "$RPM_BUILD_ROOT/usr/"`,
625
+ // Read by everyone and written by root, whatever the copy kept: a mount can lose the modes.
626
+ 'chmod -R u+rwX,go+rX,go-w "$RPM_BUILD_ROOT/usr"',
627
+ '',
628
+ '%files',
629
+ `/usr/bin/${app.packageName}`,
630
+ `/usr/lib/${app.packageName}`,
631
+ `/usr/share/applications/${app.appId}.desktop`,
632
+ `/usr/share/dbus-1/services/${app.appId}.service`,
633
+ `/usr/share/metainfo/${app.appId}.metainfo.xml`,
634
+ ...(app.icon ? [`/usr/share/icons/hicolor/*/apps/${app.appId}.png`] : []),
635
+ ];
636
+ return `${lines.join('\n')}\n`;
637
+ }
638
+
639
+ /** The packages whose playback reaches the sound server. */
640
+ const MEDIA_PACKAGES = ['expo-audio', 'expo-video'];
641
+
642
+ /** The top folders a Flatpak's sandbox takes from its runtime, which `--filesystem` cannot give the host's. */
643
+ const RESERVED_PATHS = /^\/(?:app|bin|etc|lib|lib32|lib64|sbin|usr)(?:\/|$)/;
644
+
645
+ /**
646
+ * The Flatpak permissions the app is built with, kept to what it uses: the display, GL and the
647
+ * network (the Expo Updates client and `fetch` need it), the sound server when the app plays media
648
+ * (it has expo-audio or expo-video) or declares a reason for the microphone, and each path its
649
+ * capabilities declare. Files, links, notifications and secrets go through portals, which need no
650
+ * permission.
651
+ *
652
+ * @param {DesktopAppConfig} config
653
+ * @param {{ media?: boolean }} [app] `media`: the app has expo-audio or expo-video
654
+ */
655
+ export function finishArgs(config, { media = false } = {}) {
656
+ const args = [
657
+ '--share=ipc',
658
+ '--socket=wayland',
659
+ '--socket=fallback-x11',
660
+ '--device=dri',
661
+ '--share=network',
662
+ ];
663
+ if (media || config.permissions.usageStrings['NSMicrophoneUsageDescription']) {
664
+ args.push('--socket=pulseaudio');
665
+ }
666
+ for (const entry of config.options.capabilities?.paths ?? []) {
667
+ const access = (entry.access ?? 'read') === 'read' ? ':ro' : '';
668
+ // A colon starts the mode, so one in the path is escaped, with the backslash that escapes it.
669
+ const declared = entry.path.replace(/\/$/, '').replace(/[\\:]/g, '\\$&');
670
+ args.push(`--filesystem=${declared}${access}`);
671
+ }
672
+ return args;
673
+ }
674
+
675
+ /**
676
+ * What a Flatpak cannot do in its sandbox, one line each, as `sandboxProblems` names for `mas`.
677
+ *
678
+ * @param {DesktopAppConfig} config
679
+ */
680
+ export function flatpakProblems(config) {
681
+ const capabilities = config.options.capabilities ?? {};
682
+ const problems = [];
683
+ if ((capabilities.spawn ?? []).length > 0) {
684
+ problems.push(
685
+ 'capabilities.spawn: a Flatpak runs programs inside its sandbox, so Processes.spawn reaches only programs in the GNOME runtime or the app, none of the system.',
686
+ );
687
+ }
688
+ if ((capabilities.paths ?? []).length > 0) {
689
+ problems.push(
690
+ 'capabilities.paths: each declared path becomes a --filesystem permission, which Flathub reviews; the sandbox reaches no other file but those the user picks.',
691
+ );
692
+ for (const { path: declared } of capabilities.paths ?? []) {
693
+ if (RESERVED_PATHS.test(declared)) {
694
+ problems.push(
695
+ `capabilities.paths: ${declared} is a path a Flatpak's sandbox keeps for its own runtime, so --filesystem does not expose the host's.`,
696
+ );
697
+ }
698
+ }
699
+ }
700
+ return problems;
701
+ }
702
+
703
+ /**
704
+ * The Flatpak manifest: the app's prepared folder for each architecture, as the `.tar.gz` beside
705
+ * it, copied into `/app` with no compile, on the GNOME runtime. `flatpak-builder` builds it, and it
706
+ * is what a Flathub submission starts from.
707
+ *
708
+ * @param {LinuxApp} app
709
+ * @param {{ finishArgs: string[], archives: { arch: LinuxArch, file: string, sha256: string }[] }} build
710
+ */
711
+ export function flatpakManifest(app, build) {
712
+ return `${JSON.stringify(
713
+ {
714
+ id: app.appId,
715
+ runtime: FLATPAK_RUNTIME.runtime,
716
+ 'runtime-version': FLATPAK_RUNTIME.version,
717
+ sdk: FLATPAK_RUNTIME.sdk,
718
+ command: app.packageName,
719
+ 'finish-args': build.finishArgs,
720
+ modules: [
721
+ {
722
+ name: app.packageName,
723
+ buildsystem: 'simple',
724
+ 'build-commands': ['cp -a bin lib share /app/'],
725
+ sources: build.archives.map(({ arch, file, sha256 }) => ({
726
+ type: 'archive',
727
+ path: file,
728
+ sha256,
729
+ 'only-arches': [LINUX_ARCHES[arch].flatpak],
730
+ })),
731
+ },
732
+ ],
733
+ },
734
+ null,
735
+ 2,
736
+ )}\n`;
737
+ }
738
+
739
+ /**
740
+ * The prepared folder's files as archive entries under `prefix`, folders first.
741
+ *
742
+ * @param {System} sys
743
+ * @param {string} tree
744
+ * @param {string} prefix
745
+ * @returns {ArchiveEntry[]}
746
+ */
747
+ function treeEntries(sys, tree, prefix) {
748
+ /** @type {ArchiveEntry[]} */
749
+ const entries = sys
750
+ .files(tree)
751
+ .map(
752
+ (/** @type {{ path: string, mode: number, link?: string }} */ { path: file, mode, link }) =>
753
+ link !== undefined
754
+ ? { path: `${prefix}${file}`, mode: 0o777, link }
755
+ : { path: `${prefix}${file}`, mode, data: sys.readBytes(path.join(tree, file)) },
756
+ );
757
+ return withFolders(entries);
758
+ }
759
+
760
+ /**
761
+ * @param {{ status: number }} result
762
+ * @param {string} message
763
+ */
764
+ function expectSuccess(result, message) {
765
+ if (result.status !== 0) throw new Error(message);
766
+ }
767
+
768
+ /** @param {string} text */
769
+ function shellQuote(text) {
770
+ return `'${text.replace(/'/g, "'\\''")}'`;
771
+ }
772
+
773
+ /**
774
+ * Where `rpmbuild` and `flatpak-builder` run: on this machine when it is Linux and has the tool,
775
+ * else in a container through Docker or Podman (`PACKAGING_IMAGES`). Throws, naming what is
776
+ * missing, before anything is built.
777
+ *
778
+ * @param {System} sys
779
+ * @param {'rpmbuild' | 'flatpak-builder'} tool
780
+ * @param {LinuxFormat} format
781
+ * @returns {{ native: true } | { native: false, engine: string }}
782
+ */
783
+ export function linuxToolRunner(sys, tool, format) {
784
+ /** @param {string} command @param {string[]} args */
785
+ const works = (command, args) => {
786
+ try {
787
+ return sys.run(command, args, { capture: true }).status === 0;
788
+ } catch {
789
+ return false;
790
+ }
791
+ };
792
+ if (sys.platform === 'linux' && works(tool, ['--version'])) return { native: true };
793
+ for (const engine of ['docker', 'podman']) {
794
+ if (works(engine, ['info'])) return { native: false, engine };
795
+ }
796
+ const where = sys.platform === 'linux' ? `${tool}, or Docker or Podman` : 'Docker or Podman';
797
+ throw new UsageError(
798
+ `--format ${format} runs ${tool}, and this machine has no ${where} running to run it in a ` +
799
+ 'container. Install one and start it, then package again.',
800
+ );
801
+ }
802
+
803
+ /**
804
+ * The images the tools run in where this machine lacks them. rpmbuild runs on AlmaLinux 9, whose
805
+ * rpm is the oldest the packages install with, so every newer one reads what it writes.
806
+ * flatpak-builder runs on Fedora 44: AlmaLinux 9's 1.2 composes the metainfo with
807
+ * `appstream-compose`, which the GNOME runtime's SDK no longer has.
808
+ */
809
+ export const PACKAGING_IMAGES = {
810
+ rpmbuild: {
811
+ name: 'ngn-package-rpm',
812
+ dockerfile: `FROM almalinux:9
813
+ RUN dnf -y install rpm-build rpm-sign gnupg2 tar gzip && dnf clean all
814
+ `,
815
+ },
816
+ 'flatpak-builder': {
817
+ name: 'ngn-package-flatpak',
818
+ dockerfile: `FROM fedora:44
819
+ RUN dnf -y install flatpak flatpak-builder gnupg2 && dnf clean all
820
+ `,
821
+ },
822
+ };
823
+
824
+ /**
825
+ * Runs `script` (a shell script on disk) in the tool's packaging image, built first when this
826
+ * machine does not have it. The folders it touches are mounted at their own paths, and the GPG
827
+ * home, when a key signs, read-only at `/gnupg`. flatpak-builder's sandbox needs the container
828
+ * privileged, and the GNOME runtime it installs is kept in a volume between packages.
829
+ *
830
+ * @param {System} sys
831
+ * @param {string} engine
832
+ * @param {{ tool: 'rpmbuild' | 'flatpak-builder', script: string, folders: string[], staging: string, gnupg?: string }} run
833
+ */
834
+ function inContainer(sys, engine, { tool, script, folders, staging, gnupg }) {
835
+ const image = PACKAGING_IMAGES[tool];
836
+ const tag = `${image.name}:${createHash('sha256').update(image.dockerfile).digest('hex').slice(0, 12)}`;
837
+ if (sys.run(engine, ['image', 'inspect', tag], { capture: true }).status !== 0) {
838
+ const context = path.join(staging, 'image');
839
+ sys.writeFile(path.join(context, 'Dockerfile'), image.dockerfile);
840
+ expectSuccess(
841
+ sys.run(engine, ['build', '-t', tag, context]),
842
+ `${engine} could not build the packaging image; the output above says why.`,
843
+ );
844
+ }
845
+ const flatpak = tool === 'flatpak-builder';
846
+ const mounts = [...new Set(folders)].flatMap((folder) => ['-v', `${folder}:${folder}`]);
847
+ return sys.run(engine, [
848
+ 'run',
849
+ '--rm',
850
+ ...(flatpak ? ['--privileged'] : []),
851
+ ...mounts,
852
+ ...(gnupg ? ['-v', `${gnupg}:/gnupg:ro`] : []),
853
+ ...(flatpak ? ['-v', 'ngn-package-flatpak:/root/.local/share/flatpak'] : []),
854
+ tag,
855
+ 'sh',
856
+ script,
857
+ ]);
858
+ }
859
+
860
+ /**
861
+ * The lines that set up GPG for a script: in a container, a copy of the mounted home (gpg writes
862
+ * to its home), so the key must need no passphrase there; on Linux, the user's own.
863
+ *
864
+ * @param {boolean} native
865
+ */
866
+ function gpgSetup(native) {
867
+ if (native) return [];
868
+ return [
869
+ 'rm -rf /tmp/gnupg && cp -r /gnupg /tmp/gnupg && chmod 700 /tmp/gnupg',
870
+ 'export GNUPGHOME=/tmp/gnupg',
871
+ ];
872
+ }
873
+
874
+ /**
875
+ * The shell function `ngn_restore`, which gives what a container wrote back to this user: Docker on
876
+ * Linux writes as root. Rootless Podman needs none, since container root is already this user, and
877
+ * a host UID given to `chown` there would be read as a container one. Scripts run it on exit, so a
878
+ * failed build leaves nothing this user cannot remove, and it never changes the exit status.
879
+ *
880
+ * @param {System} sys
881
+ * @param {ReturnType<typeof linuxToolRunner>} runner
882
+ * @param {string[]} paths
883
+ * @returns {string[]}
884
+ */
885
+ function restoreOwnerLines(sys, runner, paths) {
886
+ const rootless = !runner.native && runner.engine === 'podman';
887
+ if (
888
+ runner.native ||
889
+ rootless ||
890
+ sys.platform !== 'linux' ||
891
+ typeof process.getuid !== 'function'
892
+ ) {
893
+ return [];
894
+ }
895
+ const owner = `${process.getuid()}:${process.getgid?.() ?? process.getuid()}`;
896
+ return [
897
+ `ngn_restore() { chown -R ${owner} ${paths.map(shellQuote).join(' ')} 2>/dev/null || true; }`,
898
+ ];
899
+ }
900
+
901
+ /**
902
+ * The GPG key packages are signed with, from `NGN_GPG_KEY`, and the home it is in.
903
+ *
904
+ * @param {System} sys
905
+ */
906
+ function gpgKey(sys) {
907
+ const key = sys.env['NGN_GPG_KEY'];
908
+ if (!key) return null;
909
+ return { key, home: sys.env['GNUPGHOME'] || path.join(homedir(), '.gnupg') };
910
+ }
911
+
912
+ /**
913
+ * The architectures `--arch` asks for.
914
+ *
915
+ * @param {LinuxArch | 'all'} arch
916
+ * @returns {LinuxArch[]}
917
+ */
918
+ export function linuxArches(arch) {
919
+ return arch === 'all' ? ['x64', 'arm64'] : [arch];
920
+ }
921
+
922
+ /**
923
+ * Builds the app for Linux and makes the packages `options.format` asks for, one per architecture.
924
+ * Returns the exit status.
925
+ *
926
+ * @param {LinuxPackageCommand} options
927
+ * @param {System} sys
928
+ */
929
+ export async function packageLinux(options, sys) {
930
+ if (sys.platform !== 'linux' && sys.platform !== 'darwin') {
931
+ throw new UsageError('Packaging for Linux runs on Linux or macOS.');
932
+ }
933
+ const plan = planLinuxPackage(options, sys);
934
+ const built = buildLinuxBundle(sys, plan);
935
+ const { format } = options;
936
+ /** @type {string[]} */
937
+ const made = [];
938
+ /** @type {{ arch: LinuxArch, file: string, sha256: string }[]} */
939
+ const archives = [];
940
+ for (const { arch, buildDir } of plan.hosts) {
941
+ const tree = assembleTree(sys, plan, built, { arch, buildDir });
942
+ made.push(...packageTree(sys, plan, { arch, tree, archives }));
943
+ }
944
+ if (format === 'flatpak' && plan.runner) {
945
+ made.push(...buildFlatpak(sys, { ...plan, runner: plan.runner, archives }));
946
+ }
947
+ for (const file of made) console.log(path.relative(plan.cwd, file));
948
+ return 0;
949
+ }
950
+
951
+ /**
952
+ * The package of one architecture's tree in `plan.format`; for `app` and `flatpak` its `.tar.gz`
953
+ * too, which is added to `archives`. Returns the files made.
954
+ *
955
+ * @param {System} sys
956
+ * @param {LinuxPlan} plan
957
+ * @param {{ arch: LinuxArch, tree: string, archives: { arch: LinuxArch, file: string, sha256: string }[] }} built
958
+ * @returns {string[]}
959
+ */
960
+ function packageTree(sys, plan, { arch, tree, archives }) {
961
+ const { format, app } = plan;
962
+ if (format === 'deb') return [writeDeb(sys, plan, { arch, tree })];
963
+ if (format === 'rpm') {
964
+ return plan.runner ? [buildRpm(sys, { ...plan, runner: plan.runner, arch, tree })] : [];
965
+ }
966
+ const base = `${app.packageName}-${app.version}-${LINUX_ARCHES[arch].rpm}`;
967
+ // A Flatpak's source is not the `app` archive of the same name: its metadata differs, and the
968
+ // output folder may hold the `app` one and its signature.
969
+ const archive =
970
+ format === 'app'
971
+ ? path.join(plan.output, `${base}.tar.gz`)
972
+ : path.join(plan.staging, `${base}-flatpak-source.tar.gz`);
973
+ sys.writeFile(archive, tarGz(treeEntries(sys, tree, `${base}/`)));
974
+ archives.push({ arch, file: archive, sha256: sys.sha256(archive) });
975
+ return format === 'app' ? shipFolder(sys, plan, { tree, archive, base }) : [];
976
+ }
977
+
978
+ /**
979
+ * @typedef {{ cwd: string, expo: ExpoConfig, config: DesktopAppConfig, app: LinuxApp, format: LinuxFormat, media: boolean, hosts: { arch: LinuxArch, buildDir: string }[], hermesc: string, icons: { size: number, png: Buffer }[], runner: ReturnType<typeof linuxToolRunner> | null, signing: ReturnType<typeof gpgKey>, output: string, staging: string }} LinuxPlan
980
+ */
981
+
982
+ /**
983
+ * Everything checked before anything is built, then the host for each architecture and the
984
+ * `hermesc` that compiles the bundle.
985
+ *
986
+ * @param {LinuxPackageCommand} options
987
+ * @param {System} sys
988
+ * @returns {LinuxPlan}
989
+ */
990
+ function planLinuxPackage(options, sys) {
991
+ const { format } = options;
992
+ const cwd = sys.cwd();
993
+ const reactNative = resolveReactNative(sys, cwd);
994
+ const expo = readExpoConfig(sys, cwd, 'linux');
995
+ const config = desktopAppConfig(expo);
996
+ const names = linuxNames(expo, config, format);
997
+ const description = expo.description?.trim();
998
+ if (!description) {
999
+ throw new UsageError(
1000
+ 'A Linux package states what the app does, and app.json has no expo.description. Add one: ' +
1001
+ 'its first sentence is the summary software centres list.',
1002
+ );
1003
+ }
1004
+ const tool = format === 'rpm' ? 'rpmbuild' : format === 'flatpak' ? 'flatpak-builder' : null;
1005
+ const runner = tool ? linuxToolRunner(sys, tool, format) : null;
1006
+ const signing = gpgKey(sys);
1007
+ if (signing && format === 'app') checkGpg(sys);
1008
+ if (format === 'flatpak') for (const line of flatpakProblems(config)) sys.warn(line);
1009
+ const icons = expo.icon ? scaledIcons(sys, path.resolve(cwd, expo.icon)) : [];
1010
+
1011
+ const hosts = linuxArches(options.arch).map((arch) => {
1012
+ const host = prepareHost(sys, { os: 'linux', arch, release: true, universal: false, expo });
1013
+ if (format === 'deb' && !host.prebuilt) sys.warn(selfBuiltDebWarning(arch));
1014
+ return { arch, buildDir: host.buildDir };
1015
+ });
1016
+ const app = {
1017
+ ...names,
1018
+ name: config.name,
1019
+ summary: summaryOf(description),
1020
+ description,
1021
+ categories: categoryList(options.categories),
1022
+ schemes: config.schemes,
1023
+ mimeTypes: [
1024
+ ...new Set((config.options.documentTypes ?? []).flatMap((type) => type.mimeTypes ?? [])),
1025
+ ],
1026
+ icon: icons.length > 0,
1027
+ // The day it is packaged, which AppStream asks of a release.
1028
+ released: new Date().toISOString().slice(0, 10),
1029
+ license: options.license,
1030
+ homepage: options.homepage,
1031
+ maintainer: options.maintainer,
1032
+ };
1033
+ return {
1034
+ cwd,
1035
+ expo,
1036
+ config,
1037
+ app,
1038
+ format,
1039
+ hosts,
1040
+ // Resolved from the app, as @ng-native/expo's adapters import them.
1041
+ media: MEDIA_PACKAGES.some((name) => sys.resolvePackage(cwd, name) !== null),
1042
+ hermesc: linuxHermesCompiler(sys, { reactNative, hosts, expo }),
1043
+ icons,
1044
+ runner,
1045
+ signing,
1046
+ output: path.resolve(cwd, options.output),
1047
+ staging: path.join(cwd, '.expo', 'ng-native-desktop', 'package-linux'),
1048
+ };
1049
+ }
1050
+
1051
+ /**
1052
+ * What is the same for every architecture: the bundle compiled to Hermes bytecode once, its assets
1053
+ * and the updates certificate.
1054
+ *
1055
+ * @param {System} sys
1056
+ * @param {LinuxPlan} plan
1057
+ */
1058
+ function buildLinuxBundle(sys, { cwd, config, hermesc, staging }) {
1059
+ sys.remove(staging);
1060
+ const assets = path.join(staging, 'bundle');
1061
+ const javascript = path.join(staging, 'main.js');
1062
+ const bytecode = path.join(staging, BUNDLE_FILE);
1063
+ expectSuccess(
1064
+ sys.expo(cwd, [
1065
+ 'export:embed',
1066
+ '--platform',
1067
+ 'linux',
1068
+ '--dev',
1069
+ 'false',
1070
+ '--bundle-output',
1071
+ javascript,
1072
+ '--assets-dest',
1073
+ assets,
1074
+ ]),
1075
+ 'expo export:embed did not bundle the app for linux; the output above says why.',
1076
+ );
1077
+ expectSuccess(
1078
+ sys.run(hermesc, [
1079
+ '-emit-binary',
1080
+ '-O',
1081
+ '-w',
1082
+ '-max-diagnostic-width=80',
1083
+ '-out',
1084
+ bytecode,
1085
+ javascript,
1086
+ ]),
1087
+ 'hermesc could not compile the bundle to Hermes bytecode; the output above says why.',
1088
+ );
1089
+ const certificate = config.updatesCodeSigning
1090
+ ? sys.readFile(path.resolve(cwd, config.updatesCodeSigning.certificate))
1091
+ : undefined;
1092
+ return { assets, bytecode, certificate };
1093
+ }
1094
+
1095
+ /**
1096
+ * The installed tree for one architecture, as a prefix lays it out: `bin/<name>` linking to the
1097
+ * host in `lib/<name>/` beside the bundle, its assets and `metadata.json`, and in `share/` the
1098
+ * desktop entry, the metainfo and the icons. Returns its folder.
1099
+ *
1100
+ * @param {System} sys
1101
+ * @param {LinuxPlan} plan
1102
+ * @param {ReturnType<typeof buildLinuxBundle>} built
1103
+ * @param {{ arch: LinuxArch, buildDir: string }} host
1104
+ */
1105
+ function assembleTree(sys, { config, app, format, staging, icons }, built, { arch, buildDir }) {
1106
+ const tree = path.join(staging, arch, 'tree');
1107
+ const lib = path.join(tree, 'lib', app.packageName);
1108
+ // The assets, where React Native's resolver looks beside the bundle; an app may have none.
1109
+ if (sys.exists(built.assets)) sys.copy(built.assets, lib);
1110
+ sys.copy(built.bytecode, path.join(lib, BUNDLE_FILE));
1111
+ sys.copy(path.join(buildDir, 'gtk', 'ngn-linux'), path.join(lib, HOST_FILE));
1112
+ sys.symlink(
1113
+ path.join('..', 'lib', app.packageName, HOST_FILE),
1114
+ path.join(tree, 'bin', app.packageName),
1115
+ );
1116
+ sys.writeFile(
1117
+ path.join(lib, 'metadata.json'),
1118
+ linuxMetadata(config, { format, appId: app.appId, updatesCertificate: built.certificate }),
1119
+ );
1120
+ const share = path.join(tree, 'share');
1121
+ const prefix = LINUX_PREFIX[format];
1122
+ sys.writeFile(
1123
+ path.join(share, 'applications', `${app.appId}.desktop`),
1124
+ desktopEntry(app, { dbusActivatable: prefix !== undefined }),
1125
+ );
1126
+ if (prefix !== undefined) {
1127
+ sys.writeFile(
1128
+ path.join(share, 'dbus-1', 'services', `${app.appId}.service`),
1129
+ dbusService(app, prefix),
1130
+ );
1131
+ }
1132
+ sys.writeFile(path.join(share, 'metainfo', `${app.appId}.metainfo.xml`), metainfo(app));
1133
+ for (const { size, png } of icons) {
1134
+ sys.writeFile(
1135
+ path.join(share, 'icons', 'hicolor', `${size}x${size}`, 'apps', `${app.appId}.png`),
1136
+ png,
1137
+ );
1138
+ }
1139
+ return tree;
1140
+ }
1141
+
1142
+ /**
1143
+ * The `app` format: the tree as a runnable folder beside its `.tar.gz`, which is signed when a key
1144
+ * is set.
1145
+ *
1146
+ * @param {System} sys
1147
+ * @param {LinuxPlan} plan
1148
+ * @param {{ tree: string, archive: string, base: string }} built
1149
+ */
1150
+ function shipFolder(sys, { output, signing }, { tree, archive, base }) {
1151
+ const folder = path.join(output, base);
1152
+ sys.remove(folder);
1153
+ sys.copy(tree, folder);
1154
+ // An earlier signed build's signature does not belong to this archive.
1155
+ if (!signing) sys.remove(`${archive}.asc`);
1156
+ return signing ? [folder, archive, signDetached(sys, signing.key, archive)] : [folder, archive];
1157
+ }
1158
+
1159
+ /**
1160
+ * The `.deb` of one architecture's tree, installed into `/usr`.
1161
+ *
1162
+ * @param {System} sys
1163
+ * @param {LinuxPlan} plan
1164
+ * @param {{ arch: LinuxArch, tree: string }} built
1165
+ */
1166
+ function writeDeb(sys, { app, output }, { arch, tree }) {
1167
+ const deb = path.join(output, `${app.packageName}_${app.version}_${LINUX_ARCHES[arch].deb}.deb`);
1168
+ const data = treeEntries(sys, tree, './usr/');
1169
+ const bytes = data.reduce((sum, entry) => sum + (entry.data?.length ?? 0), 0);
1170
+ const control = debControl(app, { arch, installedKiB: Math.ceil(bytes / 1024) });
1171
+ sys.writeFile(
1172
+ deb,
1173
+ ar([
1174
+ { name: 'debian-binary', data: Buffer.from('2.0\n') },
1175
+ {
1176
+ name: 'control.tar.gz',
1177
+ data: tarGz([
1178
+ { path: './', mode: 0o755 },
1179
+ { path: './control', mode: 0o644, data: Buffer.from(control) },
1180
+ ]),
1181
+ },
1182
+ { name: 'data.tar.gz', data: tarGz(data) },
1183
+ ]),
1184
+ );
1185
+ return deb;
1186
+ }
1187
+
1188
+ /**
1189
+ * The first sentence of the description, without its full stop, as AppStream wants a summary.
1190
+ *
1191
+ * @param {string} description
1192
+ */
1193
+ export function summaryOf(description) {
1194
+ const first = description.split(/(?<=[.!?])\s/)[0] ?? description;
1195
+ return first.replace(/\s+/g, ' ').replace(/\.$/, '').trim();
1196
+ }
1197
+
1198
+ /**
1199
+ * The icon scaled to each hicolor size up to its own, as PNGs. Throws a usage error for an icon it
1200
+ * cannot read or that is not square.
1201
+ *
1202
+ * @param {System} sys
1203
+ * @param {string} icon
1204
+ */
1205
+ export function scaledIcons(sys, icon) {
1206
+ let image;
1207
+ try {
1208
+ image = decodePng(sys.readBytes(icon));
1209
+ } catch (error) {
1210
+ throw new UsageError(
1211
+ `The icon ${icon} cannot be scaled for Linux: ${error instanceof Error ? error.message : error}. ` +
1212
+ 'expo.icon should be a square PNG, 1024 pixels a side.',
1213
+ );
1214
+ }
1215
+ if (image.width !== image.height) {
1216
+ throw new UsageError(
1217
+ `The icon ${icon} is ${image.width} by ${image.height}; Linux icons are square. Make expo.icon square.`,
1218
+ );
1219
+ }
1220
+ return ICON_SIZES.filter((size) => size <= image.width).map((size) => ({
1221
+ size,
1222
+ png: encodePng(scaleImage(image, size)),
1223
+ }));
1224
+ }
1225
+
1226
+ /**
1227
+ * Stops before anything is built when `NGN_GPG_KEY` is set and there is no `gpg` to sign with.
1228
+ *
1229
+ * @param {System} sys
1230
+ */
1231
+ function checkGpg(sys) {
1232
+ let found = false;
1233
+ try {
1234
+ found = sys.run('gpg', ['--version'], { capture: true }).status === 0;
1235
+ } catch {
1236
+ found = false;
1237
+ }
1238
+ if (!found) {
1239
+ throw new UsageError('NGN_GPG_KEY asks for a signature, and gpg is not installed to make it.');
1240
+ }
1241
+ }
1242
+
1243
+ /**
1244
+ * A detached, armoured signature of `file` beside it, by `key`.
1245
+ *
1246
+ * @param {System} sys
1247
+ * @param {string} key
1248
+ * @param {string} file
1249
+ */
1250
+ function signDetached(sys, key, file) {
1251
+ const signature = `${file}.asc`;
1252
+ sys.remove(signature);
1253
+ expectSuccess(
1254
+ sys.run('gpg', [
1255
+ '--batch',
1256
+ '--yes',
1257
+ '--armor',
1258
+ '--local-user',
1259
+ key,
1260
+ '--detach-sign',
1261
+ '--output',
1262
+ signature,
1263
+ file,
1264
+ ]),
1265
+ `gpg could not sign ${path.basename(file)} with ${key}.`,
1266
+ );
1267
+ return signature;
1268
+ }
1269
+
1270
+ /**
1271
+ * Builds the rpm for one architecture with `rpmbuild --target`, which copies prebuilt files for any
1272
+ * architecture without emulation, and signs it with `rpmsign` when a key is set.
1273
+ *
1274
+ * @param {System} sys
1275
+ * @param {{ app: LinuxApp, arch: LinuxArch, tree: string, staging: string, output: string, runner: ReturnType<typeof linuxToolRunner>, signing: ReturnType<typeof gpgKey> }} build
1276
+ */
1277
+ function buildRpm(sys, { app, arch, tree, staging, output, runner, signing }) {
1278
+ const top = path.join(staging, arch, 'rpm');
1279
+ const spec = path.join(staging, arch, `${app.packageName}.spec`);
1280
+ sys.writeFile(spec, rpmSpec(app, { tree }));
1281
+ const target = LINUX_ARCHES[arch].rpm;
1282
+ const file = `${app.packageName}-${app.version}-1.${target}.rpm`;
1283
+ const built = path.join(top, 'RPMS', target, file);
1284
+ const rpm = path.join(output, file);
1285
+ const restore = restoreOwnerLines(sys, runner, [top, rpm]);
1286
+ const lines = [
1287
+ 'set -e',
1288
+ ...restore,
1289
+ ...(restore.length > 0 ? ['trap ngn_restore EXIT'] : []),
1290
+ `rpmbuild -bb --target ${target} --define ${shellQuote(`_topdir ${top}`)} ${shellQuote(spec)}`,
1291
+ ...(signing
1292
+ ? [
1293
+ ...gpgSetup(runner.native),
1294
+ `rpmsign --addsign --define ${shellQuote(`_gpg_name ${signing.key}`)} ${shellQuote(built)}`,
1295
+ ]
1296
+ : []),
1297
+ `mkdir -p ${shellQuote(output)}`,
1298
+ `cp ${shellQuote(built)} ${shellQuote(rpm)}`,
1299
+ ];
1300
+ runScript(sys, runner, {
1301
+ lines,
1302
+ staging,
1303
+ output,
1304
+ signing,
1305
+ tool: 'rpmbuild',
1306
+ name: `rpm-${arch}`,
1307
+ });
1308
+ return rpm;
1309
+ }
1310
+
1311
+ /**
1312
+ * Builds the Flatpak for each architecture with `flatpak-builder` into one OSTree repository, the
1313
+ * app's own remote, signed when a key is set, then a `.flatpak` bundle of each that installs the
1314
+ * GNOME runtime from Flathub. An architecture other than the machine's needs QEMU's binfmt handlers,
1315
+ * since the build runs in that architecture's SDK.
1316
+ *
1317
+ * @param {System} sys
1318
+ * @param {{ app: LinuxApp, config: DesktopAppConfig, media: boolean, archives: { arch: LinuxArch, file: string, sha256: string }[], staging: string, output: string, runner: ReturnType<typeof linuxToolRunner>, signing: ReturnType<typeof gpgKey> }} build
1319
+ */
1320
+ function buildFlatpak(sys, { app, config, media, archives, staging, output, runner, signing }) {
1321
+ // The manifest's archives sit beside it, so it builds again from the output folder.
1322
+ const placed = archives.map((archive) => {
1323
+ const file = path.join(output, path.basename(archive.file));
1324
+ sys.copy(archive.file, file);
1325
+ return { ...archive, file: path.basename(file) };
1326
+ });
1327
+ const manifest = path.join(output, `${app.appId}.json`);
1328
+ sys.writeFile(
1329
+ manifest,
1330
+ flatpakManifest(app, { finishArgs: finishArgs(config, { media }), archives: placed }),
1331
+ );
1332
+ const repo = path.join(output, 'flatpak-repo');
1333
+ const sign = signing ? ` --gpg-sign=${shellQuote(signing.key)}` : '';
1334
+ const flathub = 'https://dl.flathub.org/repo/flathub.flatpakrepo';
1335
+ const bundles = placed.map(({ arch }) =>
1336
+ path.join(output, `${app.packageName}-${app.version}-${LINUX_ARCHES[arch].flatpak}.flatpak`),
1337
+ );
1338
+ const restore = restoreOwnerLines(sys, runner, [repo, ...bundles]);
1339
+ const lines = [
1340
+ 'set -e',
1341
+ ...restore,
1342
+ ...(signing ? gpgSetup(runner.native) : []),
1343
+ `flatpak remote-add --user --if-not-exists flathub ${flathub}`,
1344
+ // flatpak-builder's own folders on the machine's disk, not a mount, which cannot always take
1345
+ // the links it makes.
1346
+ 'work="$(mktemp -d)"',
1347
+ `trap 'rm -rf "$work" 2>/dev/null || true${restore.length > 0 ? '; ngn_restore' : ''}' EXIT`,
1348
+ ...placed.flatMap(({ arch }, index) => {
1349
+ const target = LINUX_ARCHES[arch].flatpak;
1350
+ return [
1351
+ `flatpak-builder --user --arch=${target} --install-deps-from=flathub --force-clean --disable-rofiles-fuse ` +
1352
+ `--default-branch=stable --state-dir="$work/state" --repo=${shellQuote(repo)}${sign} ` +
1353
+ `"$work/${target}" ${shellQuote(manifest)}`,
1354
+ `flatpak build-bundle --arch=${target} --runtime-repo=${flathub} ${shellQuote(repo)} ` +
1355
+ `${shellQuote(bundles[index] ?? '')} ${shellQuote(app.appId)} stable`,
1356
+ ];
1357
+ }),
1358
+ `flatpak build-update-repo --generate-static-deltas${sign} ${shellQuote(repo)}`,
1359
+ ];
1360
+ runScript(sys, runner, {
1361
+ lines,
1362
+ staging,
1363
+ output,
1364
+ signing,
1365
+ tool: 'flatpak-builder',
1366
+ name: 'flatpak',
1367
+ });
1368
+ return [...placed.map(({ file }) => path.join(output, file)), manifest, repo, ...bundles];
1369
+ }
1370
+
1371
+ /**
1372
+ * Writes `lines` as a script in the staging folder and runs it here or in the container.
1373
+ *
1374
+ * @param {System} sys
1375
+ * @param {ReturnType<typeof linuxToolRunner>} runner
1376
+ * @param {{ lines: string[], staging: string, output: string, signing: ReturnType<typeof gpgKey>, tool: 'rpmbuild' | 'flatpak-builder', name: string }} run
1377
+ */
1378
+ function runScript(sys, runner, { lines, staging, output, signing, tool, name }) {
1379
+ const script = path.join(staging, `${name}.sh`);
1380
+ sys.writeFile(script, `${lines.join('\n')}\n`);
1381
+ // The container mounts the output folder, which an engine will not make (Podman) or will make as
1382
+ // root (a rootful Docker).
1383
+ sys.mkdir(output);
1384
+ const result = runner.native
1385
+ ? sys.run('sh', [script])
1386
+ : inContainer(sys, runner.engine, {
1387
+ tool,
1388
+ script,
1389
+ folders: [staging, output],
1390
+ staging,
1391
+ ...(signing && { gnupg: signing.home }),
1392
+ });
1393
+ expectSuccess(result, `${tool} did not make the package; the output above says why.`);
1394
+ }