@preeternal/react-native-godot 0.0.0-stage → 0.2.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 (109) hide show
  1. package/LICENSE +22 -0
  2. package/Package.swift +106 -0
  3. package/README.md +590 -2
  4. package/android/build.gradle +291 -0
  5. package/android/consumer-rules.pro +20 -0
  6. package/android/fix-prefab.gradle +54 -0
  7. package/android/src/main/AndroidManifest.xml +2 -0
  8. package/android/src/main/cpp/CMakeLists.txt +78 -0
  9. package/android/src/main/cpp/GodotModule.cpp +764 -0
  10. package/android/src/main/cpp/OnLoad.cpp +66 -0
  11. package/android/src/main/cpp/libgodot_android.h +73 -0
  12. package/android/src/main/cpp/libgodot_jni.cpp +658 -0
  13. package/android/src/main/cpp/libgodot_jni.h +116 -0
  14. package/android/src/main/cpp/native_godot_module_jni.cpp +86 -0
  15. package/android/src/main/cpp/native_godot_module_jni.h +58 -0
  16. package/android/src/main/java/com/preeternal/reactnativegodot/NativeGodotModuleModule.kt +83 -0
  17. package/android/src/main/java/com/preeternal/reactnativegodot/NativeGodotModulePackage.kt +41 -0
  18. package/android/src/main/java/com/preeternal/reactnativegodot/NativeLibraryLoader.kt +5 -0
  19. package/android/src/main/java/com/preeternal/reactnativegodot/RTNGodotIO.kt +123 -0
  20. package/android/src/main/java/com/preeternal/reactnativegodot/RTNGodotView.kt +92 -0
  21. package/android/src/main/java/com/preeternal/reactnativegodot/RTNGodotViewManager.kt +34 -0
  22. package/android/src/main/java/com/preeternal/reactnativegodot/RTNLibGodot.kt +215 -0
  23. package/android/src/main/res/layout/downloading_expansion.xml +165 -0
  24. package/android/src/main/res/layout/godot_app_layout.xml +5 -0
  25. package/android/src/main/res/layout/snackbar.xml +27 -0
  26. package/android/src/main/res/layout/status_bar_ongoing_event_progress_bar.xml +108 -0
  27. package/android/src/main/res/mipmap/icon.png +0 -0
  28. package/android/src/main/res/mipmap/icon_background.png +0 -0
  29. package/android/src/main/res/mipmap/icon_foreground.png +0 -0
  30. package/android/src/main/res/mipmap/icon_monochrome.png +0 -0
  31. package/android/src/main/res/mipmap-anydpi-v26/icon.xml +8 -0
  32. package/android/src/main/res/mipmap-anydpi-v26/themed_icon.xml +11 -0
  33. package/android/src/main/res/mipmap-hdpi/icon.png +0 -0
  34. package/android/src/main/res/mipmap-hdpi/icon_background.png +0 -0
  35. package/android/src/main/res/mipmap-hdpi/icon_foreground.png +0 -0
  36. package/android/src/main/res/mipmap-hdpi/icon_monochrome.png +0 -0
  37. package/android/src/main/res/mipmap-mdpi/icon.png +0 -0
  38. package/android/src/main/res/mipmap-mdpi/icon_background.png +0 -0
  39. package/android/src/main/res/mipmap-mdpi/icon_foreground.png +0 -0
  40. package/android/src/main/res/mipmap-mdpi/icon_monochrome.png +0 -0
  41. package/android/src/main/res/mipmap-xhdpi/icon.png +0 -0
  42. package/android/src/main/res/mipmap-xhdpi/icon_background.png +0 -0
  43. package/android/src/main/res/mipmap-xhdpi/icon_foreground.png +0 -0
  44. package/android/src/main/res/mipmap-xhdpi/icon_monochrome.png +0 -0
  45. package/android/src/main/res/mipmap-xxhdpi/icon.png +0 -0
  46. package/android/src/main/res/mipmap-xxhdpi/icon_background.png +0 -0
  47. package/android/src/main/res/mipmap-xxhdpi/icon_foreground.png +0 -0
  48. package/android/src/main/res/mipmap-xxhdpi/icon_monochrome.png +0 -0
  49. package/android/src/main/res/mipmap-xxxhdpi/icon.png +0 -0
  50. package/android/src/main/res/mipmap-xxxhdpi/icon_background.png +0 -0
  51. package/android/src/main/res/mipmap-xxxhdpi/icon_foreground.png +0 -0
  52. package/android/src/main/res/mipmap-xxxhdpi/icon_monochrome.png +0 -0
  53. package/android/src/main/res/values/dimens.xml +9 -0
  54. package/android/src/main/res/values/strings.xml +61 -0
  55. package/android/src/main/res/values/styles.xml +25 -0
  56. package/android/src/main/res/values-fa/strings.xml +14 -0
  57. package/android/src/main/res/values-ko/strings.xml +54 -0
  58. package/android/src/main/res/xml/godot_provider_paths.xml +15 -0
  59. package/android/src/test/java/com/preeternal/reactnativegodot/NativeGodotModulePackageTest.kt +26 -0
  60. package/app.plugin.js +169 -0
  61. package/cpp/AppleRendererPolicy.h +95 -0
  62. package/cpp/GodotModule.h +126 -0
  63. package/cpp/LibGodotABI.h +52 -0
  64. package/cpp/NativeGodotModule.cpp +825 -0
  65. package/cpp/NativeGodotModule.h +45 -0
  66. package/cpp/godot-log.h +64 -0
  67. package/ios/GodotModule.mm +695 -0
  68. package/ios/NativeGodotModuleProvider.h +35 -0
  69. package/ios/NativeGodotModuleProvider.mm +42 -0
  70. package/ios/RTNGodotView.h +42 -0
  71. package/ios/RTNGodotView.mm +671 -0
  72. package/ios/log.mm +38 -0
  73. package/lib/module/NativeNativeGodotModule.js +59 -0
  74. package/lib/module/NativeNativeGodotModule.js.map +1 -0
  75. package/lib/module/RTNGodotView.js +6 -0
  76. package/lib/module/RTNGodotView.js.map +1 -0
  77. package/lib/module/RTNGodotView.native.js +5 -0
  78. package/lib/module/RTNGodotView.native.js.map +1 -0
  79. package/lib/module/RTNGodotViewNativeComponent.ts +37 -0
  80. package/lib/module/index.js +30 -0
  81. package/lib/module/index.js.map +1 -0
  82. package/lib/module/package.json +1 -0
  83. package/lib/typescript/package.json +1 -0
  84. package/lib/typescript/src/NativeNativeGodotModule.d.ts +26 -0
  85. package/lib/typescript/src/NativeNativeGodotModule.d.ts.map +1 -0
  86. package/lib/typescript/src/RTNGodotView.d.ts +7 -0
  87. package/lib/typescript/src/RTNGodotView.d.ts.map +1 -0
  88. package/lib/typescript/src/RTNGodotView.native.d.ts +3 -0
  89. package/lib/typescript/src/RTNGodotView.native.d.ts.map +1 -0
  90. package/lib/typescript/src/RTNGodotViewNativeComponent.d.ts +11 -0
  91. package/lib/typescript/src/RTNGodotViewNativeComponent.d.ts.map +1 -0
  92. package/lib/typescript/src/index.d.ts +6 -0
  93. package/lib/typescript/src/index.d.ts.map +1 -0
  94. package/package.json +282 -4
  95. package/prebuilt-utils.rb +46 -0
  96. package/react-native-godot.podspec +41 -0
  97. package/react-native.config.js +16 -0
  98. package/scripts/check-16kb.sh +136 -0
  99. package/scripts/check-packaged-artifacts.sh +156 -0
  100. package/scripts/ci/verify-ios-simulator.py +48 -0
  101. package/scripts/ci/verify-prebuilt-install.cjs +41 -0
  102. package/scripts/download-prebuilt.js +283 -0
  103. package/scripts/prebuilt-config.js +80 -0
  104. package/scripts/spm-autolinking-plugin.js +87 -0
  105. package/src/NativeNativeGodotModule.ts +90 -0
  106. package/src/RTNGodotView.native.tsx +2 -0
  107. package/src/RTNGodotView.tsx +12 -0
  108. package/src/RTNGodotViewNativeComponent.ts +37 -0
  109. package/src/index.tsx +28 -0
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ elf_cmd=""
5
+ elf_cmd_kind=""
6
+
7
+ find_elf_tool() {
8
+ local candidates=(
9
+ "llvm-readelf:readelf"
10
+ "readelf:readelf"
11
+ "greadelf:readelf"
12
+ "/opt/homebrew/opt/llvm/bin/llvm-readelf:readelf"
13
+ "/usr/local/opt/llvm/bin/llvm-readelf:readelf"
14
+ "/opt/homebrew/bin/greadelf:readelf"
15
+ "/usr/local/bin/greadelf:readelf"
16
+ "llvm-objdump:objdump"
17
+ "/opt/homebrew/opt/llvm/bin/llvm-objdump:objdump"
18
+ "/usr/local/opt/llvm/bin/llvm-objdump:objdump"
19
+ )
20
+
21
+ for candidate in "${candidates[@]}"; do
22
+ local path="${candidate%%:*}"
23
+ local kind="${candidate##*:}"
24
+
25
+ if command -v "$path" >/dev/null 2>&1; then
26
+ elf_cmd="$(command -v "$path")"
27
+ elf_cmd_kind="$kind"
28
+ return 0
29
+ fi
30
+ if [ -x "$path" ]; then
31
+ elf_cmd="$path"
32
+ elf_cmd_kind="$kind"
33
+ return 0
34
+ fi
35
+ done
36
+
37
+ if command -v xcrun >/dev/null 2>&1; then
38
+ local xcrun_objdump
39
+ xcrun_objdump="$(xcrun --find llvm-objdump 2>/dev/null || true)"
40
+ if [ -x "$xcrun_objdump" ]; then
41
+ elf_cmd="$xcrun_objdump"
42
+ elf_cmd_kind="objdump"
43
+ return 0
44
+ fi
45
+ fi
46
+
47
+ return 1
48
+ }
49
+
50
+ if [ "${GITHUB_ACTIONS:-}" = "true" ]; then
51
+ if command -v llvm-readelf >/dev/null 2>&1; then
52
+ elf_cmd="llvm-readelf"
53
+ elf_cmd_kind="readelf"
54
+ elif command -v readelf >/dev/null 2>&1; then
55
+ elf_cmd="readelf"
56
+ elf_cmd_kind="readelf"
57
+ elif command -v greadelf >/dev/null 2>&1; then
58
+ elf_cmd="greadelf"
59
+ elf_cmd_kind="readelf"
60
+ elif command -v llvm-objdump >/dev/null 2>&1; then
61
+ elf_cmd="llvm-objdump"
62
+ elf_cmd_kind="objdump"
63
+ fi
64
+ else
65
+ find_elf_tool || true
66
+ fi
67
+
68
+ if [ -z "$elf_cmd" ]; then
69
+ echo "ERROR: no ELF inspection tool found (llvm-readelf, readelf, greadelf, or llvm-objdump)" >&2
70
+ if [ "${GITHUB_ACTIONS:-}" != "true" ]; then
71
+ echo "Tip: brew install llvm (llvm-readelf/llvm-objdump) or binutils (greadelf), or export PATH to include them." >&2
72
+ fi
73
+ exit 1
74
+ fi
75
+
76
+ print_load_alignments() {
77
+ if [ "$elf_cmd_kind" = "objdump" ]; then
78
+ "$elf_cmd" --private-headers "$1" | awk '$1 == "LOAD" { print $1, $NF }'
79
+ else
80
+ "$elf_cmd" -l -W "$1" | awk '$1 == "LOAD" { print $1, $NF }'
81
+ fi
82
+ }
83
+
84
+ # Check the final stripped native libraries used by the example APK. Android's
85
+ # current Play requirement applies to 64-bit device variants, so arm64-v8a is
86
+ # the ABI that must be 16KB-aligned here.
87
+ search_roots=(example/android/app/build/intermediates/stripped_native_libs)
88
+ files=()
89
+
90
+ while IFS= read -r file; do
91
+ [ -n "$file" ] && files+=("$file")
92
+ done < <(
93
+ if command -v rg >/dev/null 2>&1; then
94
+ rg --files "${search_roots[@]}" \
95
+ | rg '/arm64-v8a/[^/]+\.so$' \
96
+ || true
97
+ else
98
+ find "${search_roots[@]}" -type f \
99
+ -path '*/arm64-v8a/*.so' \
100
+ -print 2>/dev/null || true
101
+ fi
102
+ )
103
+
104
+ if [ "${#files[@]}" -eq 0 ]; then
105
+ echo "ERROR: no arm64-v8a native libraries found; build Android first" >&2
106
+ echo "Searched: ${search_roots[*]}" >&2
107
+ exit 1
108
+ fi
109
+
110
+ for so in "${files[@]}"; do
111
+ echo "Checking 16KB alignment: $so"
112
+
113
+ if print_load_alignments "$so" | awk '
114
+ $1 == "LOAD" {
115
+ load = 1
116
+ if ($NF != "0x4000" && $NF != "2**14") bad = 1
117
+ }
118
+ END {
119
+ if (!load) exit 2
120
+ exit bad
121
+ }
122
+ '; then
123
+ :
124
+ else
125
+ status=$?
126
+ if [ "$status" -eq 2 ]; then
127
+ echo "ERROR: no LOAD segments found for $so" >&2
128
+ else
129
+ echo "ERROR: expected 16KB alignment (0x4000 or 2**14) for $so" >&2
130
+ fi
131
+ print_load_alignments "$so" || true
132
+ exit 1
133
+ fi
134
+ done
135
+
136
+ echo "OK: 16KB alignment verified for ${#files[@]} native libraries"
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5
+ TMP_DIR="$(mktemp -d)"
6
+
7
+ cleanup() {
8
+ rm -rf "$TMP_DIR"
9
+ }
10
+ trap cleanup EXIT
11
+
12
+ if [[ $# -gt 1 ]]; then
13
+ echo "Usage: $0 [path-to-tarball]" >&2
14
+ exit 1
15
+ fi
16
+
17
+ if [[ $# -eq 1 ]]; then
18
+ TARBALL="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
19
+ else
20
+ cd "$ROOT_DIR"
21
+ NPM_CONFIG_CACHE="$TMP_DIR/npm-cache" \
22
+ npm pack --silent --ignore-scripts \
23
+ --pack-destination "$TMP_DIR" >/dev/null
24
+ TARBALL="$(find "$TMP_DIR" -maxdepth 1 -type f \
25
+ -name '*.tgz' -print -quit)"
26
+ fi
27
+
28
+ cd "$ROOT_DIR"
29
+
30
+ if [[ ! -f "$TARBALL" ]]; then
31
+ echo "Tarball not found: $TARBALL" >&2
32
+ exit 1
33
+ fi
34
+
35
+ CONTENTS_FILE="$TMP_DIR/tar-contents.txt"
36
+ tar -tzf "$TARBALL" > "$CONTENTS_FILE"
37
+
38
+ required_paths=(
39
+ package/package.json
40
+ package/app.plugin.js
41
+ package/Package.swift
42
+ package/react-native-godot.podspec
43
+ package/react-native.config.js
44
+ package/prebuilt-utils.rb
45
+ package/scripts/download-prebuilt.js
46
+ package/scripts/prebuilt-config.js
47
+ package/scripts/spm-autolinking-plugin.js
48
+ package/src/index.tsx
49
+ package/lib/module/index.js
50
+ package/lib/typescript/src/index.d.ts
51
+ package/android/build.gradle
52
+ package/android/src/main/AndroidManifest.xml
53
+ package/android/src/main/cpp/CMakeLists.txt
54
+ package/ios/GodotModule.mm
55
+ package/cpp/NativeGodotModule.cpp
56
+ )
57
+
58
+ missing=()
59
+ for path in "${required_paths[@]}"; do
60
+ if ! grep -Fxq "$path" "$CONTENTS_FILE"; then
61
+ missing+=("$path")
62
+ fi
63
+ done
64
+
65
+ if (( ${#missing[@]} > 0 )); then
66
+ echo "Packaged tarball is missing required artifacts:" >&2
67
+ printf ' - %s\n' "${missing[@]}" >&2
68
+ exit 1
69
+ fi
70
+
71
+ forbidden_patterns=(
72
+ '^package/(android|ios)/build/'
73
+ '^package/(android|ios)/libs/'
74
+ '^package/(android|ios)/local\.properties$'
75
+ '^package/(example|node_modules)/'
76
+ '^package/\.build/'
77
+ '(^|/)\.DS_Store$'
78
+ )
79
+
80
+ for pattern in "${forbidden_patterns[@]}"; do
81
+ if grep -Eq "$pattern" "$CONTENTS_FILE"; then
82
+ echo "Packaged tarball contains forbidden content matching: $pattern" >&2
83
+ grep -E "$pattern" "$CONTENTS_FILE" | sed 's/^/ - /' >&2
84
+ exit 1
85
+ fi
86
+ done
87
+
88
+ node <<'NODE'
89
+ const fs = require('node:fs');
90
+ const path = require('node:path');
91
+
92
+ const root = process.cwd();
93
+ const packageJson = JSON.parse(
94
+ fs.readFileSync(path.join(root, 'package.json'), 'utf8')
95
+ );
96
+ const entries = packageJson.prebuiltFiles ?? [];
97
+ const errors = [];
98
+ const names = new Set();
99
+
100
+ for (const entry of entries) {
101
+ for (const field of [
102
+ 'name',
103
+ 'filename',
104
+ 'version',
105
+ 'base_url',
106
+ 'shasum',
107
+ 'destination_base_dir',
108
+ 'env',
109
+ ]) {
110
+ if (typeof entry[field] !== 'string' || entry[field].length === 0) {
111
+ errors.push(`${field} is missing for prebuilt entry`);
112
+ }
113
+ }
114
+
115
+ if (names.has(entry.name)) {
116
+ errors.push(`duplicate prebuilt name: ${entry.name}`);
117
+ }
118
+ names.add(entry.name);
119
+
120
+ if (
121
+ entry.base_url !==
122
+ 'https://github.com/Preeternal/libgodot/releases/download/'
123
+ ) {
124
+ errors.push(`unexpected base_url for ${entry.name}: ${entry.base_url}`);
125
+ }
126
+ if (!/^[0-9a-f]{64}$/i.test(entry.shasum)) {
127
+ errors.push(`invalid SHA-256 for ${entry.name}`);
128
+ }
129
+ if (entry.no_unpack !== 'false') {
130
+ errors.push(`${entry.name} must be unpacked by the installer`);
131
+ }
132
+
133
+ const target = path.join(
134
+ root,
135
+ entry.destination_base_dir,
136
+ entry.name,
137
+ entry.version
138
+ );
139
+ if (!fs.existsSync(target) || fs.readdirSync(target).length === 0) {
140
+ errors.push(`prebuilt directory is missing or empty: ${target}`);
141
+ }
142
+ }
143
+
144
+ if (entries.length !== 4) {
145
+ errors.push(`expected 4 prebuilt entries, found ${entries.length}`);
146
+ }
147
+
148
+ if (errors.length > 0) {
149
+ console.error(errors.join('\n'));
150
+ process.exit(1);
151
+ }
152
+
153
+ console.log(`Verified ${entries.length} prebuilt metadata entries and directories`);
154
+ NODE
155
+
156
+ echo "Verified packaged artifacts in: $TARBALL"
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env python3
2
+ """Check that installed XCFrameworks contain the requested Simulator binaries."""
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+ import plistlib
8
+ import subprocess
9
+
10
+
11
+ def verify(root, architectures):
12
+ package = json.loads((root / "package.json").read_text())
13
+ entries = {entry["name"]: entry for entry in package["prebuiltFiles"]}
14
+ for name in ("libgodot", "libgodot-cpp"):
15
+ entry = entries[name]
16
+ framework = (root / entry["destination_base_dir"] / name /
17
+ entry["version"] / (name + ".xcframework"))
18
+ with (framework / "Info.plist").open("rb") as stream:
19
+ libraries = plistlib.load(stream)["AvailableLibraries"]
20
+ simulators = [item for item in libraries
21
+ if item.get("SupportedPlatform") == "ios" and
22
+ item.get("SupportedPlatformVariant") == "simulator"]
23
+ matching = [item for item in simulators
24
+ if set(architectures).issubset(item["SupportedArchitectures"])]
25
+ if len(matching) != 1:
26
+ available = [item["SupportedArchitectures"] for item in simulators]
27
+ raise ValueError(f"{name}: need Simulator {architectures}; available {available}")
28
+ selected = matching[0]
29
+ library = framework / selected["LibraryIdentifier"] / selected["LibraryPath"]
30
+ binary = library / library.stem if library.suffix == ".framework" else library
31
+ if not binary.is_file():
32
+ raise ValueError(f"{name}: missing Simulator binary {binary}")
33
+ actual = subprocess.check_output(
34
+ ["xcrun", "lipo", "-archs", str(binary)], text=True).split()
35
+ if not set(selected["SupportedArchitectures"]).issubset(actual):
36
+ raise ValueError(f"{name}: Info.plist architectures differ from binary {actual}")
37
+ print(f"{name}: {selected['LibraryIdentifier']} {architectures} PASS")
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser(description=__doc__)
42
+ parser.add_argument("--arch", action="append", dest="architectures")
43
+ parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2])
44
+ args = parser.parse_args()
45
+ try:
46
+ verify(args.root, args.architectures or ["arm64"])
47
+ except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
48
+ parser.exit(1, f"iOS Simulator prebuilt check failed: {error}\n")
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const packageRoot = path.resolve(process.argv[2] ?? process.cwd());
7
+ const packageJsonPath = path.join(packageRoot, 'package.json');
8
+
9
+ if (!fs.existsSync(packageJsonPath)) {
10
+ throw new Error(`Package manifest not found: ${packageJsonPath}`);
11
+ }
12
+
13
+ const { prebuiltFiles } = require(
14
+ path.join(packageRoot, 'scripts/prebuilt-config.js')
15
+ ).resolvePrebuiltConfig();
16
+ const missing = [];
17
+
18
+ for (const entry of prebuiltFiles) {
19
+ const target = path.join(
20
+ packageRoot,
21
+ entry.destination_base_dir,
22
+ entry.name,
23
+ entry.version
24
+ );
25
+
26
+ if (!fs.existsSync(target) || fs.readdirSync(target).length === 0) {
27
+ missing.push(target);
28
+ }
29
+ }
30
+
31
+ if (missing.length > 0) {
32
+ console.error('Missing or empty prebuilt directories:');
33
+ for (const target of missing) {
34
+ console.error(`- ${target}`);
35
+ }
36
+ process.exit(1);
37
+ }
38
+
39
+ console.log(
40
+ `Verified ${prebuiltFiles.length} prebuilt directories in ${packageRoot}`
41
+ );
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Script to download pre‑built Godot zip files defined in the library's package.json.
5
+ *
6
+ * Usage (from the example project):
7
+ * yarn download-prebuilt
8
+ *
9
+ * The script:
10
+ * 1. Reads the `prebuiltFiles` array from @preeternal/react-native-godot's package.json.
11
+ * 2. For each entry it builds a download URL: `${base_url}${version}/${filename}`.
12
+ * 3. If an environment variable named in the entry's `env` key is set and non‑empty,
13
+ * its value is treated as a path to a local archive file. The file is copied into
14
+ * the temporary folder and processed as if it had been downloaded.
15
+ * 4. Otherwise the file is downloaded from the network to a temporary location.
16
+ * **Redirects (301, 302, 303, 307, 308) are now followed automatically via `curl -L`.**
17
+ * 5. Verifies the SHA‑256 checksum against `shasum` unless the environment variable
18
+ * SHASUM_CHECK is set to "false".
19
+ * 6. If the checksum matches (or verification is skipped), extracts the zip into
20
+ * `${destination_base_dir}/${name}/${version}` (creating directories as needed).
21
+ *
22
+ * Additional behaviour:
23
+ * - If the target extraction folder (`destination_base_dir/name/version`) already
24
+ * exists and is not empty, the script skips processing that entry.
25
+ * - The app's reactNativeGodot.microphone selects one complete release set.
26
+ * - --with-recording / --without-recording save that choice in the app package.json.
27
+ * - Previously installed versions are preserved when switching variants.
28
+ *
29
+ * NOTE:
30
+ * The `destination_base_dir` values in package.json are now interpreted as
31
+ * relative to the **parent folder of this script** (i.e. the repository root),
32
+ * not relative to the current working directory from which the script is invoked.
33
+ */
34
+
35
+ const fs = require('fs');
36
+ const path = require('path');
37
+ const os = require('os');
38
+ const crypto = require('crypto');
39
+ const { execFileSync, execFile } = require('child_process');
40
+ const {
41
+ resolvePrebuiltConfig,
42
+ setMicrophone,
43
+ parseArguments,
44
+ } = require('./prebuilt-config');
45
+
46
+ // Resolve the library's package.json (the script lives in ./scripts/)
47
+ const libPackagePath = path.resolve(__dirname, '..', 'package.json');
48
+ if (!fs.existsSync(libPackagePath)) {
49
+ console.error('Unable to locate package.json of the library.');
50
+ process.exit(1);
51
+ }
52
+ const libPackage = JSON.parse(fs.readFileSync(libPackagePath, 'utf8'));
53
+
54
+ if (
55
+ !Array.isArray(libPackage.prebuiltFiles) ||
56
+ libPackage.prebuiltFiles.length === 0
57
+ ) {
58
+ console.log('No prebuilt files defined in package.json.');
59
+ process.exit(0);
60
+ }
61
+
62
+ /**
63
+ * Download a file from `url` and write it to `destPath`.
64
+ * Uses the external `curl` command with `-L` to follow redirects.
65
+ *
66
+ * @param {string} url - The URL to download.
67
+ * @param {string} destPath - Destination file path.
68
+ * @returns {Promise<void>}
69
+ */
70
+ function downloadFile(url, destPath) {
71
+ return new Promise((resolve, reject) => {
72
+ // Ensure any previous partial file is removed
73
+ if (fs.existsSync(destPath)) {
74
+ try {
75
+ fs.unlinkSync(destPath);
76
+ } catch {
77
+ // ignore
78
+ }
79
+ }
80
+
81
+ execFile('curl', ['-fL', '-o', destPath, url], (error) => {
82
+ if (error) {
83
+ // Clean up partial download
84
+ if (fs.existsSync(destPath)) {
85
+ try {
86
+ fs.unlinkSync(destPath);
87
+ } catch {
88
+ // ignore
89
+ }
90
+ }
91
+ reject(new Error(`curl failed for ${url}: ${error.message}`));
92
+ } else {
93
+ resolve();
94
+ }
95
+ });
96
+ });
97
+ }
98
+
99
+ /**
100
+ * Compute SHA‑256 hash of a file.
101
+ */
102
+ function computeSha256(filePath) {
103
+ return new Promise((resolve, reject) => {
104
+ const hash = crypto.createHash('sha256');
105
+ const stream = fs.createReadStream(filePath);
106
+ stream.on('error', reject);
107
+ stream.on('data', (chunk) => hash.update(chunk));
108
+ stream.on('end', () => resolve(hash.digest('hex')));
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Extract a zip file using the system `unzip` command.
114
+ */
115
+ function unzipFile(zipPath, targetDir) {
116
+ try {
117
+ execFileSync('unzip', ['-qo', zipPath, '-d', targetDir], {
118
+ stdio: 'inherit',
119
+ });
120
+ } catch (err) {
121
+ throw new Error(`Failed to unzip ${zipPath}: ${err.message}`);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Helper: check whether a directory exists and is non‑empty.
127
+ */
128
+ function isNonEmptyDirectory(dirPath) {
129
+ try {
130
+ const stats = fs.statSync(dirPath);
131
+ if (!stats.isDirectory()) return false;
132
+ const entries = fs.readdirSync(dirPath);
133
+ return entries.length > 0;
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Resolve a path that is relative to the repository root (the parent folder of this script).
141
+ */
142
+ function resolveRepoRelative(relativePath) {
143
+ const repoRoot = path.resolve(__dirname, '..'); // parent of ./scripts/
144
+ return path.join(repoRoot, relativePath);
145
+ }
146
+
147
+ /**
148
+ * Main processing loop.
149
+ */
150
+ (async () => {
151
+ const options = parseArguments(process.argv.slice(2));
152
+ if (options.microphone !== undefined) {
153
+ setMicrophone(options.appRoot, options.microphone);
154
+ }
155
+ const selection = resolvePrebuiltConfig(options.appRoot);
156
+ console.log(
157
+ `LibGodot microphone: ${selection.microphone ? 'enabled (.1)' : 'excluded (.2)'}`
158
+ );
159
+ // Determine whether checksum verification should be performed.
160
+ const skipChecksum =
161
+ process.env.SHASUM_CHECK &&
162
+ process.env.SHASUM_CHECK.toLowerCase() === 'false';
163
+
164
+ const replaceExisting =
165
+ process.env.REPLACE_EXISTING &&
166
+ process.env.REPLACE_EXISTING.toLowerCase() === 'true';
167
+
168
+ for (const entry of selection.prebuiltFiles) {
169
+ const {
170
+ name,
171
+ filename,
172
+ version,
173
+ base_url,
174
+ shasum,
175
+ destination_base_dir,
176
+ env,
177
+ no_unpack,
178
+ } = entry;
179
+
180
+ // Build URL – use the `filename` field for the actual archive name.
181
+ const url = `${base_url}${version}/${filename}`;
182
+ console.log(`\nProcessing ${name} (version ${version})`);
183
+ console.log(`Downloading from: ${url}`);
184
+ const need_unzip = no_unpack.toLowerCase() === 'false';
185
+
186
+ // Resolve destination directories relative to the repository root.
187
+ const destBaseFull = resolveRepoRelative(destination_base_dir);
188
+ const extractDir = path.join(destBaseFull, name, version);
189
+
190
+ // -----------------------------------------------------------------
191
+ // Skip logic: if target folder exists and is non‑empty, skip entry.
192
+ // -----------------------------------------------------------------
193
+ if (isNonEmptyDirectory(extractDir)) {
194
+ if (!replaceExisting) {
195
+ console.log(
196
+ `Target directory ${extractDir} already exists and is not empty. Skipping this entry.`
197
+ );
198
+ continue; // move to next prebuilt file
199
+ }
200
+ }
201
+
202
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'rtngodot-prebuilt-'));
203
+ const tmpPath = path.join(tmpDir, filename);
204
+
205
+ try {
206
+ // -------------------------------------------------------------
207
+ // 1️⃣ If an environment variable is provided, use the local file.
208
+ // -------------------------------------------------------------
209
+ if (env && process.env[env] && process.env[env].trim() !== '') {
210
+ const localFilePath = process.env[env];
211
+ console.log(
212
+ `Environment variable ${env} is set. Using local archive: ${localFilePath}`
213
+ );
214
+
215
+ if (!fs.existsSync(localFilePath)) {
216
+ throw new Error(
217
+ `Local file specified by ${env} does not exist: ${localFilePath}`
218
+ );
219
+ }
220
+
221
+ // Copy the local archive into the temporary location so that the rest
222
+ // of the workflow (checksum, unzip) works unchanged.
223
+ fs.copyFileSync(localFilePath, tmpPath);
224
+ console.log('Copied local archive to temporary location.');
225
+ } else {
226
+ // -------------------------------------------------------------
227
+ // 2️⃣ No env var – download from the network (using curl).
228
+ // -------------------------------------------------------------
229
+ await downloadFile(url, tmpPath);
230
+ console.log('Download completed.');
231
+ }
232
+
233
+ // -------------------------------------------------------------
234
+ // 3️⃣ Verify checksum (unless disabled)
235
+ // -------------------------------------------------------------
236
+ if (!skipChecksum) {
237
+ const actualHash = await computeSha256(tmpPath);
238
+ if (actualHash !== shasum.toLowerCase()) {
239
+ throw new Error(
240
+ `Checksum mismatch for ${name}. Expected ${shasum}, got ${actualHash}`
241
+ );
242
+ }
243
+ console.log('Checksum verified.');
244
+ } else {
245
+ console.log(
246
+ 'Skipping checksum verification because SHASUM_CHECK is set to false.'
247
+ );
248
+ }
249
+
250
+ // -------------------------------------------------------------
251
+ // 4️⃣ Extract
252
+ // -------------------------------------------------------------
253
+ const stagedDir = path.join(tmpDir, 'extracted');
254
+ fs.mkdirSync(stagedDir);
255
+ console.log(`Extracting to ${extractDir}`);
256
+ if (need_unzip) {
257
+ unzipFile(tmpPath, stagedDir);
258
+ } else {
259
+ const copyPath = path.join(stagedDir, filename);
260
+ fs.copyFileSync(tmpPath, copyPath);
261
+ }
262
+ if (fs.existsSync(extractDir)) fs.rmSync(extractDir, { recursive: true });
263
+ fs.mkdirSync(path.dirname(extractDir), { recursive: true });
264
+ fs.cpSync(stagedDir, extractDir, {
265
+ recursive: true,
266
+ verbatimSymlinks: true,
267
+ });
268
+ console.log('Extraction completed.');
269
+ } catch (err) {
270
+ console.error(`Error processing ${name}: ${err.message}`);
271
+ process.exitCode = 1;
272
+ return;
273
+ } finally {
274
+ // Clean up temporary file
275
+ fs.rmSync(tmpDir, { recursive: true, force: true });
276
+ }
277
+ }
278
+
279
+ console.log('\nAll prebuilt files have been processed successfully.');
280
+ })().catch((error) => {
281
+ console.error(error.message);
282
+ process.exitCode = 1;
283
+ });