@webority/mobile-tools 0.176.0 → 0.178.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.
package/README.md CHANGED
@@ -49,8 +49,7 @@ npx mobile-tools prebuild --same-env [--platform android|ios]
49
49
  - Writes `android/app/src/<flavor>/AndroidManifest.xml` for the environment's flavor, with the `expo.modules.updates.*` meta-data, and `ios/<name>/Supporting/Expo.plist` as a whole plist document. Both are git-ignored, so neither is tracked.
50
50
  - With OTA on, the manifest URL `<OTA_UPDATE_BASE_URL>/ota/manifest/<OTA_PROJECT_PUBLIC_ID>/<component public id>/<environment>`, the runtime version `VERSION_INTERNAL`, check on launch `ALWAYS`, launch wait 0, and the code-signing certificate with the key id read from it and `alg` `rsa-v1_5-sha256`.
51
51
  - With OTA off, the Android manifest holds only `expo.modules.updates.ENABLED` `false`, and Expo.plist holds only `EXUpdatesEnabled` `<false/>`.
52
- - `OTA_CODE_SIGNING_CERT` names the update server's PEM certificate, relative to the app folder. It is required, because the server signs every manifest and an app without the certificate cannot verify one. A missing or malformed `OTA_PROJECT_PUBLIC_ID` also fails; the public ids are GUIDs, written lowercase. A setting that still carries a removed key (`OTA_PROJECT_ID`, `OTA_ANDROID_COMPONENT_ID`, `OTA_IOS_COMPONENT_ID`) fails, naming its replacement.
53
- - An app without environment flavors is refused: the flavor manifest is the only place these settings go.
52
+ - `OTA_CODE_SIGNING_CERT` names the update server's PEM certificate, relative to the app folder. It is required, because the server signs every manifest and an app without the certificate cannot verify one. A missing or malformed `OTA_PROJECT_PUBLIC_ID` also fails; the public ids are GUIDs, written lowercase. - An app without environment flavors is refused: the flavor manifest is the only place these settings go.
54
53
  - Without `--platform`, it writes the files of every platform folder the app has.
55
54
  - `--same-env` recompiles the environment last compiled, which refreshes the build stamp.
56
55
  - Running it twice gives the same native files as running it once. A file whose content did not change is not rewritten.
@@ -61,6 +60,17 @@ npx mobile-tools prebuild --same-env [--platform android|ios]
61
60
  | Staging | `.staging` | `staging` |
62
61
  | Production | none | `production` |
63
62
 
63
+ ### `settings`
64
+
65
+ ```bash
66
+ npx mobile-tools settings --env <Development|Staging|Production>
67
+ npx mobile-tools settings --same-env
68
+ ```
69
+
70
+ - Writes `appsettings.Compiled.json` exactly as `prebuild` does, with the same checks and build stamp, and touches no native file. `prebuild` writes the file through the same code.
71
+ - Use it where only the app's JavaScript needs the compiled settings, such as a type check on a clean checkout.
72
+ - Fails when `appsettings.Compiled.json` is not git-ignored.
73
+
64
74
  ### `sync`
65
75
 
66
76
  ```bash
@@ -92,7 +102,7 @@ npx mobile-tools run --env <Environment> [--platform android|ios] [--device <ser
92
102
  **Android** (the default):
93
103
 
94
104
  1. Runs `sync --check` and stops on a stale tree.
95
- 2. First runs `adb connect` for any open MuMu port (16384 + 32 n, and 7555) that `adb` does not list yet. Then lists `adb` devices. A device that answers on several serials (MuMu shows one instance as `127.0.0.1:16416`, `127.0.0.1:7555` and `emulator-5556`) is shown once.
105
+ 2. First runs `adb connect` for any open MuMu port (16384 + 32 n) that `adb` does not list yet. Then lists `adb` devices. A device that answers on several serials (MuMu shows one instance as `127.0.0.1:16416`, `127.0.0.1:7555` and `emulator-5556`) is shown once.
96
106
  3. Picks the device:
97
107
  - the one named by `--device` (any of its serials, or its model name);
98
108
  - otherwise the only device;
@@ -171,7 +181,7 @@ Exit codes: `0` when the artifacts exist; `1` when the build or the artifact che
171
181
  npx mobile-tools devices [--platform android|ios] [--json]
172
182
  ```
173
183
 
174
- 1. Android: connects the local MuMu emulators. For each open port in 16384 + 32 n (n from 0 to 15) and 7555 that `adb` does not list as `127.0.0.1:<port>`, it runs `adb connect`. A failed connect is a warning, never an error.
184
+ 1. Android: connects the local MuMu emulators. For each open port in 16384 + 32 n (n from 0 to 15) that `adb` does not list as `127.0.0.1:<port>`, it runs `adb connect`. A failed connect is a warning, never an error.
175
185
  2. Android: lists every ready device once, however many serials reach it.
176
186
  3. iOS (macOS only): lists the booted simulators from `xcrun simctl`. Physical iPhones are not listed, because `run` installs only simulator apps.
177
187
 
package/lib/build.js CHANGED
@@ -1 +1 @@
1
- import{copyFileSync,existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{gradleOutputDir,gradleTask,loadToolsConfig,mappingFile,resolveIosProjectName}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{gradleInvocation,warnLongWindowsPath}from"./platform.js";import{prebuild}from"./prebuild.js";import{ensurePods,requireSynced}from"./sync.js";import{prependXosShims,xosPath,xosSimulatorBuild}from"./xos.js";const DEBUG_SIGNED_SUFFIX="-debugsigned.apk";export const debugSignedProblem=e=>e.debugSigned?"aab"===e.artifact?"--debug-signed builds an apk; an App Bundle is release only and would need the upload key":"ios-sim"===e.artifact?"--debug-signed signs an Android apk; ios-sim builds have no signing":e.debug?"--debug-signed signs the release build; --debug already builds the debug variant, so use one or the other":"Production"===e.env?"--debug-signed is for staging test builds; a Production build must be signed with the upload key":null:null;const debugSignedCopy=e=>{const o=`${e.slice(0,-4)}-debugsigned.apk`;return copyFileSync(e,o),o},buildAndroid=async(e,o,a)=>{const{appRoot:i,env:s}=e;requireSynced(i,{pods:!1});const t=loadToolsConfig(i),n=path.join(i,"android");existsSync(path.join(n,"app","build.gradle"))||fail("appConfigInvalid",`android/app/build.gradle not found in ${i}`),void 0!==e.abis&&e.gradleArgs.some(e=>e.startsWith("-PreactNativeArchitectures"))&&fail("badInput","--arch and a -PreactNativeArchitectures argument after -- both set the Android ABIs: pass only one"),prebuild({appRoot:i,env:s,platform:"android",otaTest:e.otaTest});const r=gradleTask(s,t.flavors,o,a),d=path.join(logDir(i),`gradle-${s}-${logStamp()}.log`),l=void 0===e.abis?[]:[`-PreactNativeArchitectures=${e.abis.join(",")}`],p=e.debugSigned?["-PweborityDebugSigned=true"]:[];warnLongWindowsPath(i),await buildOrFail(gradleInvocation(n,[`:app:${r}`,...l,...p,...e.gradleArgs],process.platform,process.env),n,d,`gradle ${r}`);const g=gradleOutputDir(i,s,t.flavors,o,a),u=existsSync(g)?readdirSync(g,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.${o}`)&&!e.name.endsWith("-debugsigned.apk")).map(e=>path.resolve(g,e.name)).sort():[];0===u.length&&fail("artifactMissing",`the build produced no ${o} in ${g}`);const c=mappingFile(i,s,t.flavors),b="release"===a&&existsSync(c)?c:null;return{artifacts:e.debugSigned?u.map(debugSignedCopy):u,mapping:b,log:d}},buildIos=async(e,o)=>{e.gradleArgs.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const{appRoot:a,env:i}=e,s=xosPath(process.env,process.platform);requireSynced(a,{pods:!1});const t=loadToolsConfig(a),n=resolveIosProjectName(a,t)??fail("appConfigInvalid",`no ios/ folder in ${a}`);prebuild({appRoot:a,env:i,platform:"ios",otaTest:e.otaTest}),prependXosShims(s,a),ensurePods(a,process.platform);const r="release"===o?"Release":"Debug",d=path.join(logDir(a),`xos-${i}-${logStamp()}.log`);return{artifacts:[await xosSimulatorBuild(s,{appRoot:a,projectName:n,configuration:r,arch:e.arch??"x86_64"},d)],mapping:null,log:d}};export const build=async e=>{const o=debugSignedProblem(e);null!==o&&fail("badInput",o);const a=e.debug?"debug":"release",i="ios-sim"===e.artifact?await buildIos(e,a):await buildAndroid(e,e.artifact,a);if(isJsonOutput())sayJson({artifacts:i.artifacts,mapping:i.mapping,log:i.log});else{for(const e of i.artifacts)say(`build: ${e}`);null!==i.mapping&&say(`build: mapping ${i.mapping}`)}};
1
+ import{copyFileSync,existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{gradleOutputDir,gradleTask,loadToolsConfig,mappingFile,resolveIosProjectName}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{gradleInvocation,warnLongWindowsPath}from"./platform.js";import{prebuild}from"./prebuild.js";import{ensurePods,requireSynced}from"./sync.js";import{prependXosToolPath,xosPath,xosSimulatorBuild}from"./xos.js";const DEBUG_SIGNED_SUFFIX="-debugsigned.apk";export const debugSignedProblem=e=>e.debugSigned?"aab"===e.artifact?"--debug-signed builds an apk; an App Bundle is release only and would need the upload key":"ios-sim"===e.artifact?"--debug-signed signs an Android apk; ios-sim builds have no signing":e.debug?"--debug-signed signs the release build; --debug already builds the debug variant, so use one or the other":"Production"===e.env?"--debug-signed is for staging test builds; a Production build must be signed with the upload key":null:null;const debugSignedCopy=e=>{const o=`${e.slice(0,-4)}-debugsigned.apk`;return copyFileSync(e,o),o},buildAndroid=async(e,o,a)=>{const{appRoot:i,env:s}=e;requireSynced(i,{pods:!1});const t=loadToolsConfig(i),n=path.join(i,"android");existsSync(path.join(n,"app","build.gradle"))||fail("appConfigInvalid",`android/app/build.gradle not found in ${i}`),void 0!==e.abis&&e.gradleArgs.some(e=>e.startsWith("-PreactNativeArchitectures"))&&fail("badInput","--arch and a -PreactNativeArchitectures argument after -- both set the Android ABIs: pass only one"),prebuild({appRoot:i,env:s,platform:"android",otaTest:e.otaTest});const r=gradleTask(s,t.flavors,o,a),d=path.join(logDir(i),`gradle-${s}-${logStamp()}.log`),l=void 0===e.abis?[]:[`-PreactNativeArchitectures=${e.abis.join(",")}`],p=e.debugSigned?["-PweborityDebugSigned=true"]:[];warnLongWindowsPath(i),await buildOrFail(gradleInvocation(n,[`:app:${r}`,...l,...p,...e.gradleArgs],process.platform,process.env),n,d,`gradle ${r}`);const g=gradleOutputDir(i,s,t.flavors,o,a),u=existsSync(g)?readdirSync(g,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.${o}`)&&!e.name.endsWith("-debugsigned.apk")).map(e=>path.resolve(g,e.name)).sort():[];0===u.length&&fail("artifactMissing",`the build produced no ${o} in ${g}`);const c=mappingFile(i,s,t.flavors),b="release"===a&&existsSync(c)?c:null;return{artifacts:e.debugSigned?u.map(debugSignedCopy):u,mapping:b,log:d}},buildIos=async(e,o)=>{e.gradleArgs.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const{appRoot:a,env:i}=e,s=xosPath(process.env,process.platform);requireSynced(a,{pods:!1});const t=loadToolsConfig(a),n=resolveIosProjectName(a,t)??fail("appConfigInvalid",`no ios/ folder in ${a}`);prebuild({appRoot:a,env:i,platform:"ios",otaTest:e.otaTest}),prependXosToolPath(s,a),ensurePods(a,process.platform);const r="release"===o?"Release":"Debug",d=path.join(logDir(a),`xos-${i}-${logStamp()}.log`);return{artifacts:[await xosSimulatorBuild(s,{appRoot:a,projectName:n,configuration:r,arch:e.arch??"x86_64"},d)],mapping:null,log:d}};export const build=async e=>{const o=debugSignedProblem(e);null!==o&&fail("badInput",o);const a=e.debug?"debug":"release",i="ios-sim"===e.artifact?await buildIos(e,a):await buildAndroid(e,e.artifact,a);if(isJsonOutput())sayJson({artifacts:i.artifacts,mapping:i.mapping,log:i.log});else{for(const e of i.artifacts)say(`build: ${e}`);null!==i.mapping&&say(`build: mapping ${i.mapping}`)}};
package/lib/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{parseArgs}from"node:util";import{build}from"./build.js";import{cache}from"./cache.js";import{parseEnvironment}from"./config.js";import{devices}from"./devices.js";import{doctor}from"./doctor.js";import{installHooks}from"./hooks.js";import{icons}from"./icons.js";import{initKeystore}from"./keystore.js";import{restartMetro}from"./metro.js";import{CliError,fail,reportFailure,say,setJsonOutput,warn}from"./output.js";import{parseAndroidAbis}from"./platform.js";import{prebuild}from"./prebuild.js";import{run}from"./run.js";import{uploadSymbols}from"./symbols.js";import{checkSync,sync,writeStamp}from"./sync.js";import{SIMULATOR_ARCHS}from"./xos.js";const COMMAND_USAGE={prebuild:" prebuild --env <Development|Staging|Production> [--platform android|ios]\n prebuild --same-env [--platform android|ios]\n Compile appsettings into appsettings.Compiled.json and stamp the native projects.",sync:" sync [--check | --stamp]\n --check: exit 1 with the fix command when node_modules (or ios/Pods) is stale.\n --stamp: record that node_modules matches the lockfile now (run it from postinstall).\n Without either: install from the lockfile, stamp, and reset native codegen when needed.",hooks:" hooks install\n Add git post-merge and post-checkout hooks that run sync --check.",run:" run --env <Environment> [--platform android|ios] [--device <serial|name>] [--rebuild] [--profiling] [--app <path.app>]\n Build for one device's ABI (or install the cached build with the same native fingerprint), install it there, reuse or start Metro, and launch. --rebuild skips the cache.\n iOS (macOS): installs the simulator app --app names on a booted simulator, starts Metro and launches it; it never builds.\n --profiling serves production JavaScript with React's profiling renderer; a Metro serving development JavaScript must be stopped first.",build:" build --env <Environment> --artifact apk|aab|ios-sim [--debug] [--debug-signed] [--ota-test] [--arch <value>] [--json] [-- <gradle args>]\n Prebuild, then build a release APK or App Bundle (Android, every ABI unless --arch) or an iOS simulator app through xOS Tools (xos on PATH).\n --arch for ios-sim: x86_64 (the default) or arm64. For apk and aab: arm64-v8a, armeabi-v7a, x86_64 or x86, as one value or a comma list; arm64 means arm64-v8a.\n --debug builds the debug variant (apk or ios-sim only).\n --debug-signed builds a staging test apk signed with the debug keystore, named *-debugsigned.apk (apk only; not with --debug or Production).\n --ota-test suffixes the OTA runtime version with -otatest, so only this build receives an update published for it.\n Arguments after -- go to Gradle unchanged (apk and aab only), for example -- --no-daemon --max-workers=3.",devices:" devices [--platform android|ios] [--json]\n Connect local MuMu emulators, then list every ready device once (simulators for iOS).",doctor:" doctor [--platform android|ios] [--fix] [--json]\n Check the toolchain and the app tree; exit 1 while a problem remains. --fix removes a stale autolinking cache.",cache:" cache list|clear [--json]\n List or remove this app's cached builds.",metro:" metro restart\n Stop the Metro mobile-tools started for this app and start it again on the same port.",icons:" icons [--source <png|svg>]\n Render per-environment launcher icons for Android flavors and iOS AppIcon-<Env> sets.",symbols:" symbols upload --env <Environment> --dsym <path>\n Upload an iOS build's dSYM folder or zip to Firebase Crashlytics, with the app id from that environment's GoogleService-Info plist; needs the Firebase CLI.",keystore:' keystore init --out <file.jks> [--alias upload] [--dname "CN=Android Upload Key"] [--validity-days 10000]\n Create the Android upload keystore with the password from MOBILE_TOOLS_KEYSTORE_PASSWORD and print its SHA-256 for store.json.'},USAGE=`mobile-tools <command> [options] (run from the app's root folder)\n\n${Object.values(COMMAND_USAGE).join("\n\n")}`,knownCommand=e=>Object.hasOwn(COMMAND_USAGE,e),commandUsage=e=>`usage:\n${COMMAND_USAGE[e]}`,parse=(e,o,t,a=!1)=>{try{const{values:e,positionals:n}=parseArgs({args:o,options:t,allowPositionals:a,strict:!0});return{values:e,positionals:n}}catch(o){return fail("badInput",`${o instanceof Error?o.message:String(o)}\n\n${commandUsage(e)}`)}},envOption=e=>"string"==typeof e?parseEnvironment(e):void 0,platformOption=e=>{if(void 0!==e)return"android"!==e&&"ios"!==e?fail("badInput",`--platform must be android or ios, not ${String(e)}`):e},JSON_COMMANDS=new Set(["build","cache","devices","doctor"]),artifactOption=e=>"apk"===e||"aab"===e||"ios-sim"===e?e:fail("badInput","build needs --artifact apk, aab or ios-sim"),main=async e=>{const[o,...t]=e,a=process.cwd(),n=t.indexOf("--"),s=n<0?t:t.slice(0,n);if(void 0!==o&&knownCommand(o)&&(s.includes("--help")||s.includes("-h")))say(commandUsage(o));else switch(setJsonOutput(JSON_COMMANDS.has(o??"")&&s.includes("--json")),o){case"prebuild":{const{values:e}=parse(o,t,{env:{type:"string"},"same-env":{type:"boolean"},platform:{type:"string"}});return void prebuild({appRoot:a,env:envOption(e.env),sameEnv:!0===e["same-env"],platform:platformOption(e.platform)})}case"sync":{const{values:e}=parse(o,t,{check:{type:"boolean"},stamp:{type:"boolean"}});if(e.check&&e.stamp&&fail("badInput","use --check or --stamp, not both"),e.stamp)return writeStamp(a),void say("sync --stamp: recorded node_modules as matching the lockfile");if(e.check){const e=checkSync(a,process.platform);return e.length>0&&fail("installStale",e.join("\n")),void say("sync --check: node_modules matches the lockfile")}return void sync(a,process.platform)}case"hooks":{const{positionals:e}=parse(o,t,{},!0);return"install"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools hooks install\n\n${USAGE}`),void installHooks(a)}case"run":{const{values:e}=parse(o,t,{env:{type:"string"},platform:{type:"string"},device:{type:"string"},rebuild:{type:"boolean"},profiling:{type:"boolean"},app:{type:"string"}}),n=envOption(e.env)??fail("badInput","run needs --env <Development|Staging|Production>");return void await run({appRoot:a,env:n,platform:platformOption(e.platform)??"android",device:"string"==typeof e.device?e.device:void 0,rebuild:!0===e.rebuild,profiling:!0===e.profiling,app:"string"==typeof e.app?e.app:void 0})}case"build":{const e=t.indexOf("--"),n=e<0?t:t.slice(0,e),s=e<0?[]:t.slice(e+1),{values:i}=parse(o,n,{env:{type:"string"},artifact:{type:"string"},debug:{type:"boolean"},"debug-signed":{type:"boolean"},"ota-test":{type:"boolean"},json:{type:"boolean"},arch:{type:"string"}}),r=envOption(i.env)??fail("badInput","build needs --env <Development|Staging|Production>"),p=artifactOption(i.artifact);!0===i.debug&&"aab"===p&&fail("badInput","--debug builds an apk or an ios-sim app; an App Bundle is release only"),"ios-sim"===p&&s.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const l="string"==typeof i.arch?i.arch:void 0,d="ios-sim"===p?SIMULATOR_ARCHS.find(e=>e===(l??"x86_64"))??fail("badInput","--arch must be x86_64 or arm64"):void 0,c="ios-sim"===p||void 0===l?void 0:parseAndroidAbis(l);return void await build({appRoot:a,env:r,artifact:p,debug:!0===i.debug,debugSigned:!0===i["debug-signed"],otaTest:!0===i["ota-test"],gradleArgs:s,arch:d,abis:c})}case"devices":{const{values:e}=parse(o,t,{platform:{type:"string"},json:{type:"boolean"}});return void await devices({appRoot:a,platform:platformOption(e.platform)??"android"})}case"doctor":{const{values:e}=parse(o,t,{platform:{type:"string"},fix:{type:"boolean"},json:{type:"boolean"}});return void await doctor({appRoot:a,platform:platformOption(e.platform),fix:!0===e.fix})}case"cache":{const{positionals:e}=parse(o,t,{json:{type:"boolean"}},!0),n=e[0];return 1!==e.length||"list"!==n&&"clear"!==n?fail("badInput",`usage: mobile-tools cache list|clear\n\n${USAGE}`):void await cache({appRoot:a,action:n})}case"metro":{const{positionals:e}=parse(o,t,{},!0);return"restart"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools metro restart\n\n${USAGE}`),void await restartMetro(a)}case"icons":{const{values:e}=parse(o,t,{source:{type:"string"}});return void await icons({appRoot:a,source:"string"==typeof e.source?e.source:void 0})}case"symbols":{const{values:e,positionals:n}=parse(o,t,{env:{type:"string"},dsym:{type:"string"}},!0);"upload"===n[0]&&1===n.length||fail("badInput",`usage: mobile-tools symbols upload --env <Environment> --dsym <path>\n\n${USAGE}`);const s=envOption(e.env)??fail("badInput","symbols upload needs --env <Development|Staging|Production>"),i="string"==typeof e.dsym?e.dsym:fail("badInput","symbols upload needs --dsym <path>");return void await uploadSymbols({appRoot:a,env:s,dsym:i})}case"keystore":{const{values:e,positionals:a}=parse(o,t,{out:{type:"string"},alias:{type:"string"},dname:{type:"string"},"validity-days":{type:"string"}},!0);"init"===a[0]&&1===a.length||fail("badInput",`usage: mobile-tools keystore init --out <file.jks>\n\n${USAGE}`);const n="string"==typeof e.out?e.out:fail("badInput","keystore init needs --out <file.jks>"),s="string"==typeof e["validity-days"]?e["validity-days"]:"10000";return/^[1-9][0-9]*$/.test(s)||fail("badInput",`--validity-days must be a positive whole number, not ${s}`),void await initKeystore({out:n,alias:"string"==typeof e.alias?e.alias:"upload",dname:"string"==typeof e.dname?e.dname:"CN=Android Upload Key",validityDays:Number(s)})}case"help":{const e=t[0];return void 0===e?void say(USAGE):(knownCommand(e)||fail("badInput",`unknown command "${e}"\n\n${USAGE}`),void say(commandUsage(e)))}case void 0:case"--help":case"-h":return void say(USAGE);default:fail("badInput",`unknown command "${o}"\n\n${USAGE}`)}};main(process.argv.slice(2)).catch(e=>{e instanceof CliError&&(reportFailure(e),process.exit(e.exitCode)),warn(e instanceof Error?e.stack??e.message:String(e)),process.exit(1)});
2
+ import{parseArgs}from"node:util";import{build}from"./build.js";import{cache}from"./cache.js";import{parseEnvironment}from"./config.js";import{devices}from"./devices.js";import{doctor}from"./doctor.js";import{installHooks}from"./hooks.js";import{icons}from"./icons.js";import{initKeystore}from"./keystore.js";import{restartMetro}from"./metro.js";import{CliError,fail,reportFailure,say,setJsonOutput,warn}from"./output.js";import{parseAndroidAbis}from"./platform.js";import{compileSettings,prebuild}from"./prebuild.js";import{run}from"./run.js";import{uploadSymbols}from"./symbols.js";import{checkSync,sync,writeStamp}from"./sync.js";import{SIMULATOR_ARCHS}from"./xos.js";const COMMAND_USAGE={prebuild:" prebuild --env <Development|Staging|Production> [--platform android|ios]\n prebuild --same-env [--platform android|ios]\n Compile appsettings into appsettings.Compiled.json and stamp the native projects.",settings:" settings --env <Development|Staging|Production>\n settings --same-env\n Compile appsettings into appsettings.Compiled.json only; no native file is touched.",sync:" sync [--check | --stamp]\n --check: exit 1 with the fix command when node_modules (or ios/Pods) is stale.\n --stamp: record that node_modules matches the lockfile now (run it from postinstall).\n Without either: install from the lockfile, stamp, and reset native codegen when needed.",hooks:" hooks install\n Add git post-merge and post-checkout hooks that run sync --check.",run:" run --env <Environment> [--platform android|ios] [--device <serial|name>] [--rebuild] [--profiling] [--app <path.app>]\n Build for one device's ABI (or install the cached build with the same native fingerprint), install it there, reuse or start Metro, and launch. --rebuild skips the cache.\n iOS (macOS): installs the simulator app --app names on a booted simulator, starts Metro and launches it; it never builds.\n --profiling serves production JavaScript with React's profiling renderer; a Metro serving development JavaScript must be stopped first.",build:" build --env <Environment> --artifact apk|aab|ios-sim [--debug] [--debug-signed] [--ota-test] [--arch <value>] [--json] [-- <gradle args>]\n Prebuild, then build a release APK or App Bundle (Android, every ABI unless --arch) or an iOS simulator app through xOS Tools (xos on PATH).\n --arch for ios-sim: x86_64 (the default) or arm64. For apk and aab: arm64-v8a, armeabi-v7a, x86_64 or x86, as one value or a comma list; arm64 means arm64-v8a.\n --debug builds the debug variant (apk or ios-sim only).\n --debug-signed builds a staging test apk signed with the debug keystore, named *-debugsigned.apk (apk only; not with --debug or Production).\n --ota-test suffixes the OTA runtime version with -otatest, so only this build receives an update published for it.\n Arguments after -- go to Gradle unchanged (apk and aab only), for example -- --no-daemon --max-workers=3.",devices:" devices [--platform android|ios] [--json]\n Connect local MuMu emulators, then list every ready device once (simulators for iOS).",doctor:" doctor [--platform android|ios] [--fix] [--json]\n Check the toolchain and the app tree; exit 1 while a problem remains. --fix removes a stale autolinking cache.",cache:" cache list|clear [--json]\n List or remove this app's cached builds.",metro:" metro restart\n Stop the Metro mobile-tools started for this app and start it again on the same port.",icons:" icons [--source <png|svg>]\n Render per-environment launcher icons for Android flavors and iOS AppIcon-<Env> sets.",symbols:" symbols upload --env <Environment> --dsym <path>\n Upload an iOS build's dSYM folder or zip to Firebase Crashlytics, with the app id from that environment's GoogleService-Info plist; needs the Firebase CLI.",keystore:' keystore init --out <file.jks> [--alias upload] [--dname "CN=Android Upload Key"] [--validity-days 10000]\n Create the Android upload keystore with the password from MOBILE_TOOLS_KEYSTORE_PASSWORD and print its SHA-256 for store.json.'},USAGE=`mobile-tools <command> [options] (run from the app's root folder)\n\n${Object.values(COMMAND_USAGE).join("\n\n")}`,knownCommand=e=>Object.hasOwn(COMMAND_USAGE,e),commandUsage=e=>`usage:\n${COMMAND_USAGE[e]}`,parse=(e,o,t,n=!1)=>{try{const{values:e,positionals:a}=parseArgs({args:o,options:t,allowPositionals:n,strict:!0});return{values:e,positionals:a}}catch(o){return fail("badInput",`${o instanceof Error?o.message:String(o)}\n\n${commandUsage(e)}`)}},envOption=e=>"string"==typeof e?parseEnvironment(e):void 0,platformOption=e=>{if(void 0!==e)return"android"!==e&&"ios"!==e?fail("badInput",`--platform must be android or ios, not ${String(e)}`):e},JSON_COMMANDS=new Set(["build","cache","devices","doctor"]),artifactOption=e=>"apk"===e||"aab"===e||"ios-sim"===e?e:fail("badInput","build needs --artifact apk, aab or ios-sim"),main=async e=>{const[o,...t]=e,n=process.cwd(),a=t.indexOf("--"),s=a<0?t:t.slice(0,a);if(void 0!==o&&knownCommand(o)&&(s.includes("--help")||s.includes("-h")))say(commandUsage(o));else switch(setJsonOutput(JSON_COMMANDS.has(o??"")&&s.includes("--json")),o){case"prebuild":{const{values:e}=parse(o,t,{env:{type:"string"},"same-env":{type:"boolean"},platform:{type:"string"}});return void prebuild({appRoot:n,env:envOption(e.env),sameEnv:!0===e["same-env"],platform:platformOption(e.platform)})}case"settings":{const{values:e}=parse(o,t,{env:{type:"string"},"same-env":{type:"boolean"}});return void compileSettings({appRoot:n,env:envOption(e.env),sameEnv:!0===e["same-env"]})}case"sync":{const{values:e}=parse(o,t,{check:{type:"boolean"},stamp:{type:"boolean"}});if(e.check&&e.stamp&&fail("badInput","use --check or --stamp, not both"),e.stamp)return writeStamp(n),void say("sync --stamp: recorded node_modules as matching the lockfile");if(e.check){const e=checkSync(n,process.platform);return e.length>0&&fail("installStale",e.join("\n")),void say("sync --check: node_modules matches the lockfile")}return void sync(n,process.platform)}case"hooks":{const{positionals:e}=parse(o,t,{},!0);return"install"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools hooks install\n\n${USAGE}`),void installHooks(n)}case"run":{const{values:e}=parse(o,t,{env:{type:"string"},platform:{type:"string"},device:{type:"string"},rebuild:{type:"boolean"},profiling:{type:"boolean"},app:{type:"string"}}),a=envOption(e.env)??fail("badInput","run needs --env <Development|Staging|Production>");return void await run({appRoot:n,env:a,platform:platformOption(e.platform)??"android",device:"string"==typeof e.device?e.device:void 0,rebuild:!0===e.rebuild,profiling:!0===e.profiling,app:"string"==typeof e.app?e.app:void 0})}case"build":{const e=t.indexOf("--"),a=e<0?t:t.slice(0,e),s=e<0?[]:t.slice(e+1),{values:i}=parse(o,a,{env:{type:"string"},artifact:{type:"string"},debug:{type:"boolean"},"debug-signed":{type:"boolean"},"ota-test":{type:"boolean"},json:{type:"boolean"},arch:{type:"string"}}),r=envOption(i.env)??fail("badInput","build needs --env <Development|Staging|Production>"),p=artifactOption(i.artifact);!0===i.debug&&"aab"===p&&fail("badInput","--debug builds an apk or an ios-sim app; an App Bundle is release only"),"ios-sim"===p&&s.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const l="string"==typeof i.arch?i.arch:void 0,d="ios-sim"===p?SIMULATOR_ARCHS.find(e=>e===(l??"x86_64"))??fail("badInput","--arch must be x86_64 or arm64"):void 0,c="ios-sim"===p||void 0===l?void 0:parseAndroidAbis(l);return void await build({appRoot:n,env:r,artifact:p,debug:!0===i.debug,debugSigned:!0===i["debug-signed"],otaTest:!0===i["ota-test"],gradleArgs:s,arch:d,abis:c})}case"devices":{const{values:e}=parse(o,t,{platform:{type:"string"},json:{type:"boolean"}});return void await devices({appRoot:n,platform:platformOption(e.platform)??"android"})}case"doctor":{const{values:e}=parse(o,t,{platform:{type:"string"},fix:{type:"boolean"},json:{type:"boolean"}});return void await doctor({appRoot:n,platform:platformOption(e.platform),fix:!0===e.fix})}case"cache":{const{positionals:e}=parse(o,t,{json:{type:"boolean"}},!0),a=e[0];return 1!==e.length||"list"!==a&&"clear"!==a?fail("badInput",`usage: mobile-tools cache list|clear\n\n${USAGE}`):void await cache({appRoot:n,action:a})}case"metro":{const{positionals:e}=parse(o,t,{},!0);return"restart"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools metro restart\n\n${USAGE}`),void await restartMetro(n)}case"icons":{const{values:e}=parse(o,t,{source:{type:"string"}});return void await icons({appRoot:n,source:"string"==typeof e.source?e.source:void 0})}case"symbols":{const{values:e,positionals:a}=parse(o,t,{env:{type:"string"},dsym:{type:"string"}},!0);"upload"===a[0]&&1===a.length||fail("badInput",`usage: mobile-tools symbols upload --env <Environment> --dsym <path>\n\n${USAGE}`);const s=envOption(e.env)??fail("badInput","symbols upload needs --env <Development|Staging|Production>"),i="string"==typeof e.dsym?e.dsym:fail("badInput","symbols upload needs --dsym <path>");return void await uploadSymbols({appRoot:n,env:s,dsym:i})}case"keystore":{const{values:e,positionals:n}=parse(o,t,{out:{type:"string"},alias:{type:"string"},dname:{type:"string"},"validity-days":{type:"string"}},!0);"init"===n[0]&&1===n.length||fail("badInput",`usage: mobile-tools keystore init --out <file.jks>\n\n${USAGE}`);const a="string"==typeof e.out?e.out:fail("badInput","keystore init needs --out <file.jks>"),s="string"==typeof e["validity-days"]?e["validity-days"]:"10000";return/^[1-9][0-9]*$/.test(s)||fail("badInput",`--validity-days must be a positive whole number, not ${s}`),void await initKeystore({out:a,alias:"string"==typeof e.alias?e.alias:"upload",dname:"string"==typeof e.dname?e.dname:"CN=Android Upload Key",validityDays:Number(s)})}case"help":{const e=t[0];return void 0===e?void say(USAGE):(knownCommand(e)||fail("badInput",`unknown command "${e}"\n\n${USAGE}`),void say(commandUsage(e)))}case void 0:case"--help":case"-h":return void say(USAGE);default:fail("badInput",`unknown command "${o}"\n\n${USAGE}`)}};main(process.argv.slice(2)).catch(e=>{e instanceof CliError&&(reportFailure(e),process.exit(e.exitCode)),warn(e instanceof Error?e.stack??e.message:String(e)),process.exit(1)});
package/lib/devices.d.ts CHANGED
@@ -38,7 +38,7 @@ export declare const pickDevice: <T extends {
38
38
  serials: string[];
39
39
  model: string;
40
40
  }>(devices: T[], requested: string | undefined, describe: (device: T) => string, interactive: boolean) => Promise<T>;
41
- /** adb ports of local emulators adb cannot find alone: MuMu Player 12 instances (16384 + 32 n) and the legacy MuMu port. */
41
+ /** adb ports of local emulators adb cannot find alone: MuMu Player 12 instances (16384 + 32 n). */
42
42
  export declare const LOCAL_EMULATOR_PORTS: readonly number[];
43
43
  /** One listed device, as the devices command prints it in JSON. */
44
44
  export type ListedDevice = ({
package/lib/devices.js CHANGED
@@ -1 +1 @@
1
- import{Socket}from"node:net";import{createInterface}from"node:readline/promises";import{capture}from"./exec.js";import{listAppleDevices}from"./ios.js";import{fail,isJsonOutput,say,sayJson,warn}from"./output.js";import{adbPath,requireDarwin}from"./platform.js";export const parseAdbDevices=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>""!==e&&!e.startsWith("List of devices")&&!e.startsWith("*")).map(e=>{const[t,o=""]=e.split(/\s+/);if(void 0===t)throw new Error("a non-empty adb line starts with its serial");return{serial:t,state:o}});const serialRank=e=>e.startsWith("emulator-")?1:e.includes(":")?2:0,deviceKey=e=>""!==e.serialNo?`${e.serialNo}|${e.androidId}`:/^[0-9a-f]{16}$/i.test(e.androidId)?`android:${e.androidId}`:`serial:${e.serial}`;export const dedupeDevices=e=>{const t=new Map;for(const o of e){const e=deviceKey(o);t.set(e,[...t.get(e)??[],o])}return[...t.values()].map(e=>{const t=[...e].sort((e,t)=>serialRank(e.serial)-serialRank(t.serial)||e.serial.localeCompare(t.serial)),[o]=t;if(void 0===o)throw new Error("a device group holds at least one probe");return{serial:o.serial,serials:t.map(e=>e.serial),model:o.model,abi:o.abi}}).sort((e,t)=>e.serial.localeCompare(t.serial))};const PROBE_SCRIPT="getprop ro.serialno; getprop ro.product.model; getprop ro.product.cpu.abi; settings get secure android_id";export const probeDevice=(e,t,o)=>{const s=capture({file:e,args:["-s",t,"shell",PROBE_SCRIPT]},o);if(0!==s.status)return fail("toolFailed",`adb could not read ${t}: ${s.stderr.trim()||s.stdout.trim()}`);const[r="",i="",a="",n=""]=s.stdout.split(/\r?\n/).map(e=>e.trim());return{serial:t,serialNo:r,model:i,abi:a,androidId:n}};export const listAndroidDevices=(e,t)=>{const o=capture({file:e,args:["devices"]},t);if(0!==o.status)return fail("toolFailed",`adb devices failed: ${o.stderr.trim()}`);const s=parseAdbDevices(o.stdout),r=s.filter(e=>"device"!==e.state),i=s.filter(e=>"device"===e.state);if(0===i.length){const e=r.map(e=>`${e.serial} is ${e.state}`).join("; ");return fail("deviceNotFound",`no Android device ready${e?` (${e})`:""}. Connect a phone with USB debugging, start an emulator, or adb connect host:port.`)}return dedupeDevices(i.map(o=>probeDevice(e,o.serial,t)))};export const describeDevice=e=>`${e.model||"unknown model"} (${e.serial}, ${e.abi})`;export const findDevice=(e,t)=>e.find(e=>e.serials.includes(t))??e.find(e=>e.model.toLowerCase()===t.toLowerCase());export const pickDevice=async(e,t,o,s)=>{const r=e.map((e,t)=>` ${t+1}. ${o(e)}`).join("\n");if(t)return findDevice(e,t)??fail("deviceNotFound",`no device matches --device ${t}. Connected:\n${r}`);const[i]=e;if(1===e.length&&void 0!==i)return i;if(!s)return fail("deviceAmbiguous",`several devices are connected; pass --device <serial|name>:\n${r}`);const a=createInterface({input:process.stdin,output:process.stdout});try{const t=await a.question(`Several devices are connected:\n${r}\nRun on which? [1-${e.length}] `);return e[Number(t.trim())-1]??fail("badInput",`no device numbered ${t.trim()}`)}finally{a.close()}};export const LOCAL_EMULATOR_PORTS=[...Array.from({length:16},(e,t)=>16384+32*t),7555];const isPortOpen=e=>new Promise(t=>{const o=new Socket;o.setTimeout(300),o.once("connect",()=>{o.destroy(),t(!0)}),o.once("timeout",()=>{o.destroy(),t(!1)}),o.once("error",()=>{o.destroy(),t(!1)}),o.connect(e,"127.0.0.1")});export const connectLocalEmulators=async(e,t)=>{const o=(await Promise.all(LOCAL_EMULATOR_PORTS.map(async e=>({port:e,open:await isPortOpen(e)})))).filter(e=>e.open).map(e=>e.port),s=capture({file:e,args:["devices"]},t),r=0===s.status?parseAdbDevices(s.stdout).map(e=>e.serial):[],i=[];for(const s of o){const o=`127.0.0.1:${s}`;if(r.includes(o))continue;const a=capture({file:e,args:["connect",o]},t),n=`${a.stdout}${a.stderr}`.trim();n.includes("connected to")?(say(`devices: connected ${o}`),i.push(o)):warn(`devices: ${o} is open but adb connect said: ${n}`)}return i};export const devices=async e=>{const{appRoot:t,platform:o}=e;let s;if("android"===o){const e=adbPath(process.env,process.platform);await connectLocalEmulators(e,t),s=listAndroidDevices(e,t).map(e=>({platform:"android",...e}))}else requireDarwin(process.platform,"devices --platform ios"),s=listAppleDevices(t).map(e=>({platform:"ios",...e}));if(isJsonOutput())sayJson({devices:s});else for(const e of s)if("android"===e.platform){const t=e.serials.length>1?` (also ${e.serials.slice(1).join(", ")})`:"";say(`${e.serial} ${e.model} ${e.abi}${t}`)}else say(`${e.udid} ${e.name} ${e.kind}`)};
1
+ import{Socket}from"node:net";import{createInterface}from"node:readline/promises";import{capture}from"./exec.js";import{listAppleDevices}from"./ios.js";import{fail,isJsonOutput,say,sayJson,warn}from"./output.js";import{adbPath,requireDarwin}from"./platform.js";export const parseAdbDevices=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>""!==e&&!e.startsWith("List of devices")&&!e.startsWith("*")).map(e=>{const[t,o=""]=e.split(/\s+/);if(void 0===t)throw new Error("a non-empty adb line starts with its serial");return{serial:t,state:o}});const serialRank=e=>e.startsWith("emulator-")?1:e.includes(":")?2:0,deviceKey=e=>""!==e.serialNo?`${e.serialNo}|${e.androidId}`:/^[0-9a-f]{16}$/i.test(e.androidId)?`android:${e.androidId}`:`serial:${e.serial}`;export const dedupeDevices=e=>{const t=new Map;for(const o of e){const e=deviceKey(o);t.set(e,[...t.get(e)??[],o])}return[...t.values()].map(e=>{const t=[...e].sort((e,t)=>serialRank(e.serial)-serialRank(t.serial)||e.serial.localeCompare(t.serial)),[o]=t;if(void 0===o)throw new Error("a device group holds at least one probe");return{serial:o.serial,serials:t.map(e=>e.serial),model:o.model,abi:o.abi}}).sort((e,t)=>e.serial.localeCompare(t.serial))};const PROBE_SCRIPT="getprop ro.serialno; getprop ro.product.model; getprop ro.product.cpu.abi; settings get secure android_id";export const probeDevice=(e,t,o)=>{const s=capture({file:e,args:["-s",t,"shell",PROBE_SCRIPT]},o);if(0!==s.status)return fail("toolFailed",`adb could not read ${t}: ${s.stderr.trim()||s.stdout.trim()}`);const[r="",i="",a="",n=""]=s.stdout.split(/\r?\n/).map(e=>e.trim());return{serial:t,serialNo:r,model:i,abi:a,androidId:n}};export const listAndroidDevices=(e,t)=>{const o=capture({file:e,args:["devices"]},t);if(0!==o.status)return fail("toolFailed",`adb devices failed: ${o.stderr.trim()}`);const s=parseAdbDevices(o.stdout),r=s.filter(e=>"device"!==e.state),i=s.filter(e=>"device"===e.state);if(0===i.length){const e=r.map(e=>`${e.serial} is ${e.state}`).join("; ");return fail("deviceNotFound",`no Android device ready${e?` (${e})`:""}. Connect a phone with USB debugging, start an emulator, or adb connect host:port.`)}return dedupeDevices(i.map(o=>probeDevice(e,o.serial,t)))};export const describeDevice=e=>`${e.model||"unknown model"} (${e.serial}, ${e.abi})`;export const findDevice=(e,t)=>e.find(e=>e.serials.includes(t))??e.find(e=>e.model.toLowerCase()===t.toLowerCase());export const pickDevice=async(e,t,o,s)=>{const r=e.map((e,t)=>` ${t+1}. ${o(e)}`).join("\n");if(t)return findDevice(e,t)??fail("deviceNotFound",`no device matches --device ${t}. Connected:\n${r}`);const[i]=e;if(1===e.length&&void 0!==i)return i;if(!s)return fail("deviceAmbiguous",`several devices are connected; pass --device <serial|name>:\n${r}`);const a=createInterface({input:process.stdin,output:process.stdout});try{const t=await a.question(`Several devices are connected:\n${r}\nRun on which? [1-${e.length}] `);return e[Number(t.trim())-1]??fail("badInput",`no device numbered ${t.trim()}`)}finally{a.close()}};export const LOCAL_EMULATOR_PORTS=Array.from({length:16},(e,t)=>16384+32*t);const isPortOpen=e=>new Promise(t=>{const o=new Socket;o.setTimeout(300),o.once("connect",()=>{o.destroy(),t(!0)}),o.once("timeout",()=>{o.destroy(),t(!1)}),o.once("error",()=>{o.destroy(),t(!1)}),o.connect(e,"127.0.0.1")});export const connectLocalEmulators=async(e,t)=>{const o=(await Promise.all(LOCAL_EMULATOR_PORTS.map(async e=>({port:e,open:await isPortOpen(e)})))).filter(e=>e.open).map(e=>e.port),s=capture({file:e,args:["devices"]},t),r=0===s.status?parseAdbDevices(s.stdout).map(e=>e.serial):[],i=[];for(const s of o){const o=`127.0.0.1:${s}`;if(r.includes(o))continue;const a=capture({file:e,args:["connect",o]},t),n=`${a.stdout}${a.stderr}`.trim();n.includes("connected to")?(say(`devices: connected ${o}`),i.push(o)):warn(`devices: ${o} is open but adb connect said: ${n}`)}return i};export const devices=async e=>{const{appRoot:t,platform:o}=e;let s;if("android"===o){const e=adbPath(process.env,process.platform);await connectLocalEmulators(e,t),s=listAndroidDevices(e,t).map(e=>({platform:"android",...e}))}else requireDarwin(process.platform,"devices --platform ios"),s=listAppleDevices(t).map(e=>({platform:"ios",...e}));if(isJsonOutput())sayJson({devices:s});else for(const e of s)if("android"===e.platform){const t=e.serials.length>1?` (also ${e.serials.slice(1).join(", ")})`:"";say(`${e.serial} ${e.model} ${e.abi}${t}`)}else say(`${e.udid} ${e.name} ${e.kind}`)};
package/lib/prebuild.d.ts CHANGED
@@ -69,5 +69,12 @@ export interface PrebuildOptions {
69
69
  /** Only `build --ota-test` sets it: the OTA runtime version gets the `-otatest` suffix. */
70
70
  otaTest?: boolean;
71
71
  }
72
+ export interface CompileSettingsOptions {
73
+ appRoot: string;
74
+ env?: Environment | undefined;
75
+ sameEnv?: boolean;
76
+ }
77
+ /** Compiles appsettings into appsettings.Compiled.json and writes no other file. Returns the settings it compiled. */
78
+ export declare const compileSettings: (options: CompileSettingsOptions) => AppSettings;
72
79
  /** Compiles appsettings and stamps the native layers. Returns the settings it compiled. */
73
80
  export declare const prebuild: (options: PrebuildOptions) => AppSettings;
package/lib/prebuild.js CHANGED
@@ -1 +1 @@
1
- import{copyFileSync,existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{checkAppSettings}from"./appSettingsRules.js";import{applicationId,COMPILED_FILE,ENVIRONMENTS,flavorOf,lastCompiledEnvironment,loadAppSettings,loadToolsConfig,resolveIosProjectName}from"./config.js";import{capture}from"./exec.js";import{androidOtaManifest,expoPlist,otaNativeSettings}from"./otaNative.js";import{fail,say}from"./output.js";import{findOnPath}from"./platform.js";export const IOS_COMPILED_XCCONFIG="ios/appsettings.Compiled.xcconfig";export const androidFlavorManifest=e=>`android/app/src/${flavorOf(e)}/AndroidManifest.xml`;export const expoPlistPath=e=>`ios/${e}/Supporting/Expo.plist`;export const usesExpoUpdates=e=>dependsOn(e,"expo-updates");export const generatedNativeFiles=(e,t,i,o)=>{if("android"===o)return usesExpoUpdates(e)?[androidFlavorManifest(i)]:[];const n=[IOS_COMPILED_XCCONFIG];if(void 0!==t){const o=path.join(e,loadToolsConfig(e).firebasePlistDir,`GoogleService-Info.${i}.plist`);existsSync(o)&&n.push(`ios/${t}/GoogleService-Info.plist`),usesExpoUpdates(e)&&n.push(expoPlistPath(t))}return n};export const nativeBuildInputs=(e,t)=>{const i=path.join(e,COMPILED_FILE);if(!existsSync(i))return fail("appConfigInvalid",`${COMPILED_FILE} is missing: run npx mobile-tools prebuild --env <Development|Staging|Production> first`);const o=JSON.parse(readFileSync(i,"utf8")),n=resolveIosProjectName(e,loadToolsConfig(e)),s=generatedNativeFiles(e,n,o.ENVIRONMENT,t).filter(t=>existsSync(path.join(e,t)));return[...["APP_ID","APP_NAME","VERSION_DISPLAY","VERSION_INTERNAL"].map(e=>`${e}=${JSON.stringify(o[e])}`),...s.map(t=>`${t}=${JSON.stringify(readFileSync(path.join(e,t),"utf8"))}`)].join("\n")};const requiredGroup=(e,t)=>{const i=e[t];if(void 0===i)throw new Error(`the pattern did not capture group ${t}`);return i},objectsOf=(e,t)=>[...e.matchAll(new RegExp(`\\n\\s*(\\w+)(?: /\\*([^\\n]*?)\\*/)? = \\{\\s*isa = ${t};`,"g"))].map(e=>({id:requiredGroup(e,1),name:(e[2]??"").trim()})),pbxObject=(e,t)=>{const i=new RegExp(`\\n\\s*${t}(?: /\\*[^\\n]*?\\*/)? = \\{`).exec(e);if(!i)return;let o=0;for(let t=i.index+i[0].length-1;t<e.length;t++)if(e.startsWith("/*",t)){if(t=e.indexOf("*/",t+2)+1,0===t)return}else if('"'===e[t])for(t++;t<e.length&&'"'!==e[t];t++)"\\"===e[t]&&t++;else if("{"===e[t])o++;else if("}"===e[t]&&0===--o)return e.slice(i.index,t+1)},configurationsOf=(e,t)=>[...(/buildConfigurations = \(([^)]*)\)/.exec(pbxObject(e,t)??"")?.[1]??"").matchAll(/(\w+)(?: \/\* ([^*]*?) \*\/)?,/g)].map(e=>({id:requiredGroup(e,1),name:e[2]??""})),unquote=e=>e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e,shipsInfoPlist=e=>/^com\.apple\.product-type\.(application|.*extension)/.test(e);export const shippedInfoPlists=e=>{const t=new Map,i=/\n\s*(\w+)(?: \/\*[^\n]*?\*\/)? = \{\s*isa = PBXNativeTarget;/g;for(const o of e.matchAll(i)){const i=requiredGroup(o,1),n=pbxObject(e,i)??"",s=unquote(/\sproductType = ([^;\n]*);/.exec(n)?.[1]??"");if(!shipsInfoPlist(s))continue;const r=unquote(/\sname = ([^;\n]*);/.exec(n)?.[1]??i),a=/\sbuildConfigurationList = (\w+)/.exec(n)?.[1],p=a&&pbxObject(e,a)||"",c=/buildConfigurations = \(([^)]*)\)/.exec(p)?.[1]??"";for(const i of c.matchAll(/\w+(?= \/\*|,)/g)){const o=requiredGroup(i,0),n=/\sINFOPLIST_FILE = ([^;\n]*);/.exec(pbxObject(e,o)??"")?.[1];n&&!t.has(unquote(n))&&t.set(unquote(n),r)}}return[...t].map(([e,t])=>({target:t,file:e}))};const BUILD_SETTING_KEYS=[["CFBundleIdentifier","PRODUCT_BUNDLE_IDENTIFIER"],["CFBundleShortVersionString","MARKETING_VERSION"],["CFBundleVersion","CURRENT_PROJECT_VERSION"]];export const fixedInfoPlistValues=e=>BUILD_SETTING_KEYS.flatMap(([t,i])=>{const o=new RegExp(`<key>${t}</key>\\s*(<[^>]*>)?([^<]*)`).exec(e);if(!o)return[];const n=requiredGroup(o,2),s=o[1],r="<string>"===s?n.trim():s??n.trim();return r===`$(${i})`||r===`\${${i}}`?[]:[{key:t,value:r,setting:i}]});export const checkInfoPlistReferences=(e,t)=>{const i=path.join(e,"ios"),o=readFileSync(path.join(i,`${t}.xcodeproj`,"project.pbxproj"),"utf8"),n=[{target:t,file:`${t}/Info.plist`},...shippedInfoPlists(o)],s=path.resolve(i,`${t}/Info.plist`),r=[],a=new Set;for(const{target:t,file:o}of n){const n=o.replace(/^(\$\(SRCROOT\)|\$\{SRCROOT\}|\$\(PROJECT_DIR\))\//,"");if(/\$[({]/.test(n)){r.push(`target ${t}: INFOPLIST_FILE ${o} uses a build setting prebuild cannot resolve`);continue}const p=path.resolve(i,n);if(a.has(p))continue;a.add(p);const c=path.relative(e,p).replace(/\\/g,"/");if(!existsSync(p)){r.push(`${c} not found (INFOPLIST_FILE of target ${t})`);continue}const d=readFileSync(p,"utf8");for(const{key:e,value:t,setting:i}of fixedInfoPlistValues(d))r.push(`${c}: ${e} is "${t}", must be $(${i})`);p!==s||/<key>CFBundleDisplayName<\/key>\s*<string>\$\(APP_NAME\)<\/string>/.test(d)||r.push(`${c}: CFBundleDisplayName must be $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}r.length>0&&fail("appConfigInvalid",`Info.plist values that ignore what prebuild writes into appsettings.Compiled.xcconfig:\n ${r.join("\n ")}`)};const XCCONFIG_BASE=/baseConfigurationReference = \w+ \/\* appsettings\.Compiled\.xcconfig \*\//,MANAGED_BUILD_SETTINGS=["PRODUCT_BUNDLE_IDENTIFIER","MARKETING_VERSION","CURRENT_PROJECT_VERSION"];export const checkPbxprojSettings=(e,t)=>{const i=[],o=objectsOf(e,"PBXProject")[0];void 0===o&&i.push("project.pbxproj has no PBXProject object to carry the base configuration");const n=o?/\sbuildConfigurationList = (\w+)/.exec(pbxObject(e,o.id)??"")?.[1]:void 0;for(const{id:t,name:o}of n?configurationsOf(e,n):[])XCCONFIG_BASE.test(pbxObject(e,t)??"")||i.push(`project configuration ${t} /* ${o} */ does not use appsettings.Compiled.xcconfig as its base configuration: set the project-level configurations' base configuration to appsettings.Compiled.xcconfig`);const s=t?[...MANAGED_BUILD_SETTINGS,"ASSETCATALOG_COMPILER_APPICON_NAME"]:MANAGED_BUILD_SETTINGS;for(const{id:t,name:o}of objectsOf(e,"XCBuildConfiguration")){const n=pbxObject(e,t)??"";for(const e of s)new RegExp(`\\s${e} = `).test(n)&&i.push(`configuration ${t} /* ${o} */ sets ${e}: remove it; ios/appsettings.Compiled.xcconfig sets it`);/\sINFOPLIST_KEY_CFBundleDisplayName = /.test(n)&&i.push(`configuration ${t} /* ${o} */ sets INFOPLIST_KEY_CFBundleDisplayName: remove it; Info.plist reads $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}i.length>0&&fail("appConfigInvalid",`project.pbxproj sets values that ios/appsettings.Compiled.xcconfig owns:\n ${i.join("\n ")}`)};const XCCONFIG_UNSAFE=/\/\/|[$";]/,xcconfigText=(e,t,i)=>{const o=[["APP_NAME",String(e.APP_NAME)],["PRODUCT_BUNDLE_IDENTIFIER",applicationId(String(e.APP_ID),t)],["MARKETING_VERSION",String(e.VERSION_DISPLAY)],["CURRENT_PROJECT_VERSION",String(e.VERSION_INTERNAL)],...i?[["ASSETCATALOG_COMPILER_APPICON_NAME",`AppIcon-${t}`]]:[]];for(const[e,t]of o)XCCONFIG_UNSAFE.test(t)&&fail("appConfigInvalid",`${e} must not contain // $ " or ;: it is written unquoted into ios/appsettings.Compiled.xcconfig`);return["// Written by mobile-tools prebuild from appsettings.Compiled.json for one environment. Not tracked: run prebuild to change it.",...o.map(([e,t])=>`${e} = ${t}`)].map(e=>`${e}\n`).join("")};export const buildCommit=e=>{const t=findOnPath("git",process.env,process.platform);if(!t)return"nogit";const i=capture({file:t,args:["rev-parse","--short","HEAD"]},e);if(0!==i.status)return"nogit";const o=capture({file:t,args:["status","--porcelain","--","."]},e);return 0!==o.status?fail("toolFailed",`git status failed in ${e}: ${o.stderr.trim()}`):""===o.stdout.trim()?i.stdout.trim():`${i.stdout.trim()}-dirty`};export const requireIgnored=(e,t)=>{const i=findOnPath("git",process.env,process.platform);if(!i||0!==capture({file:i,args:["rev-parse","--is-inside-work-tree"]},e).status)return;const o=t.filter(t=>{const o=capture({file:i,args:["check-ignore","-q","--",t]},e);return 0!==o.status&&1!==o.status&&fail("toolFailed",`git check-ignore failed for ${t}: ${o.stderr.trim()}`),1===o.status});o.length>0&&fail("appConfigInvalid",`add these lines to ${path.basename(e)}/.gitignore; prebuild writes them per environment:\n${o.join("\n")}`)};const writeIfChanged=(e,t)=>(!existsSync(e)||readFileSync(e,"utf8")!==t)&&(writeFileSync(e,t,"utf8"),!0),report=(e,t,i)=>{say(`prebuild: ${i?"wrote":"unchanged"} ${path.relative(e,t)}`)},dependsOn=(e,t)=>{const i=path.join(e,"package.json");if(!existsSync(i))return!1;const o=JSON.parse(readFileSync(i,"utf8"));return Boolean(o.dependencies?.[t])};export const usesFirebase=e=>dependsOn(e,"@react-native-firebase/app");export const checkNdkHook=e=>{const t=path.join(e,"android","build.gradle");if(!existsSync(t))return;const i=readFileSync(t,"utf8");/withId\(\s*["']com\.android\.library["']\s*\)/.test(i)&&/\.ndkVersion\s*=\s*rootProject\.ext\.ndkVersion/.test(i)||fail("appConfigInvalid",'android/build.gradle does not hand the app NDK to library modules; add after apply plugin "com.facebook.react.rootproject": subprojects { project -> project.plugins.withId("com.android.library") { project.android.ndkVersion = rootProject.ext.ndkVersion } }')};const MANAGED_GRADLE_KEYS=/^\s*(APP_NAME|APP_ID|VERSION_DISPLAY|VERSION_INTERNAL)\s*[=:]/gm;export const stampAndroid=(e,t,i,o,n)=>{const s=path.join(e,"android","gradle.properties");existsSync(s)||fail("appConfigInvalid",`android/gradle.properties not found in ${e}`),usesFirebase(e)&&!existsSync(path.join(e,"android","app","google-services.json"))&&fail("appConfigInvalid","android/app/google-services.json is missing; the app uses @react-native-firebase, whose Gradle plugin needs it"),checkNdkHook(e);const r=[...new Set([...readFileSync(s,"utf8").matchAll(MANAGED_GRADLE_KEYS)].map(([,e])=>e))];r.length>0&&fail("appConfigInvalid",`android/gradle.properties sets ${r.join(", ")}: remove them; android/app/build.gradle reads them from appsettings.Compiled.json`);const a=path.join(e,"android","app","build.gradle");if(existsSync(a)&&readFileSync(a,"utf8").includes("appsettings.Compiled.json")||fail("appConfigInvalid","android/app/build.gradle does not read appsettings.Compiled.json; add the compiledSettings loader (mobile-tools README, prebuild)"),usesExpoUpdates(e)){o.flavors||fail("appConfigInvalid",'expo-updates settings go into the flavor\'s manifest; set "flavors": true');const s=path.join(e,"android","app","src","main","AndroidManifest.xml");existsSync(s)||fail("appConfigInvalid","android/app/src/main/AndroidManifest.xml not found");const r=[...readFileSync(s,"utf8").matchAll(/android:name="(expo\.modules\.updates\.[^"]*)"/g)].map(([,e])=>e);r.length>0&&fail("appConfigInvalid",`android/app/src/main/AndroidManifest.xml sets ${r.join(", ")}: remove them from android/app/src/main/AndroidManifest.xml; prebuild writes them into ${androidFlavorManifest(i)}`);const a=otaNativeSettings(e,t,i,"android",n),p=path.join(e,androidFlavorManifest(i));mkdirSync(path.dirname(p),{recursive:!0}),report(e,p,writeIfChanged(p,androidOtaManifest(a)))}};export const stampIos=(e,t,i,o,n,s)=>{const r=path.join(e,"ios",n),a=path.join(r,"Info.plist"),p=path.join(e,"ios",`${n}.xcodeproj`,"project.pbxproj");for(const t of[a,p])existsSync(t)||fail("appConfigInvalid",`${path.relative(e,t)} not found: check "iosProjectName"`);checkInfoPlistReferences(e,n);const c=`AppIcon-${i}`,d=path.join(r,"Images.xcassets"),l=existsSync(path.join(d,`${c}.appiconset`)),f=ENVIRONMENTS.filter(e=>e!==i&&existsSync(path.join(d,`AppIcon-${e}.appiconset`)));!l&&f.length>0&&fail("appConfigInvalid",`ios/${n}/Images.xcassets has AppIcon-${f[0]} but no ${c}: run mobile-tools icons`),checkPbxprojSettings(readFileSync(p,"utf8"),l);const u=path.join(e,IOS_COMPILED_XCCONFIG);report(e,u,writeIfChanged(u,xcconfigText(t,i,l))),l||say(`prebuild: no AppIcon-${i} set, so ios/appsettings.Compiled.xcconfig sets no app icon name`);const g=path.join(r,"GoogleService-Info.plist"),I=path.join(e,o.firebasePlistDir,`GoogleService-Info.${i}.plist`);if(!existsSync(I)&&usesFirebase(e)&&fail("appConfigInvalid",`${path.relative(e,I)} is missing; the app uses @react-native-firebase, and an iOS build without it reports no crashes`),existsSync(I)){const t=!existsSync(g)||!readFileSync(I).equals(readFileSync(g));t&&copyFileSync(I,g),report(e,g,t)}else existsSync(g)&&(rmSync(g),say(`prebuild: removed ${path.relative(e,g)}, no ${path.relative(e,I)}`));if(usesExpoUpdates(e)){readFileSync(p,"utf8").includes("Expo.plist in Resources")||fail("appConfigInvalid","add Supporting/Expo.plist to the Xcode project's Copy Bundle Resources; prebuild writes its contents");const o=otaNativeSettings(e,t,i,"ios",s),r=path.join(e,expoPlistPath(n));mkdirSync(path.dirname(r),{recursive:!0}),report(e,r,writeIfChanged(r,expoPlist(o)))}};export const prebuild=e=>{const{appRoot:t,sameEnv:i,platform:o}=e,n=!0===e.otaTest;i&&e.env&&fail("badInput","pass --env or --same-env, not both");const s=i?lastCompiledEnvironment(t):e.env;if(!s)return fail("badInput","prebuild needs --env <Development|Staging|Production> or --same-env");const r=loadToolsConfig(t),a=resolveIosProjectName(t,r),p=loadAppSettings(t,s,r.requiredSettings);checkAppSettings(t,p,s);const c="android"===o||!o&&existsSync(path.join(t,"android")),d="android"===o?void 0:a;if("ios"===o&&void 0===d)return fail("appConfigInvalid",`no ios/ folder in ${t}`);const l=[...c?generatedNativeFiles(t,d,s,"android"):[],...void 0!==d?generatedNativeFiles(t,d,s,"ios"):[]];requireIgnored(t,[COMPILED_FILE,...l]);const f={...p,COMMIT:buildCommit(t),BUILD_TIME:(new Date).toISOString()};return writeFileSync(path.join(t,COMPILED_FILE),`${JSON.stringify(f,null,2)}\n`,"utf8"),say(`prebuild: wrote ${COMPILED_FILE} (${s}, ${f.COMMIT})`),c&&stampAndroid(t,f,s,r,n),void 0!==d&&stampIos(t,f,s,r,d,n),f};
1
+ import{copyFileSync,existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{checkAppSettings}from"./appSettingsRules.js";import{applicationId,COMPILED_FILE,ENVIRONMENTS,flavorOf,lastCompiledEnvironment,loadAppSettings,loadToolsConfig,resolveIosProjectName}from"./config.js";import{capture}from"./exec.js";import{androidOtaManifest,expoPlist,otaNativeSettings}from"./otaNative.js";import{fail,say}from"./output.js";import{findOnPath}from"./platform.js";export const IOS_COMPILED_XCCONFIG="ios/appsettings.Compiled.xcconfig";export const androidFlavorManifest=e=>`android/app/src/${flavorOf(e)}/AndroidManifest.xml`;export const expoPlistPath=e=>`ios/${e}/Supporting/Expo.plist`;export const usesExpoUpdates=e=>dependsOn(e,"expo-updates");export const generatedNativeFiles=(e,t,i,o)=>{if("android"===o)return usesExpoUpdates(e)?[androidFlavorManifest(i)]:[];const n=[IOS_COMPILED_XCCONFIG];if(void 0!==t){const o=path.join(e,loadToolsConfig(e).firebasePlistDir,`GoogleService-Info.${i}.plist`);existsSync(o)&&n.push(`ios/${t}/GoogleService-Info.plist`),usesExpoUpdates(e)&&n.push(expoPlistPath(t))}return n};export const nativeBuildInputs=(e,t)=>{const i=path.join(e,COMPILED_FILE);if(!existsSync(i))return fail("appConfigInvalid",`${COMPILED_FILE} is missing: run npx mobile-tools prebuild --env <Development|Staging|Production> first`);const o=JSON.parse(readFileSync(i,"utf8")),n=resolveIosProjectName(e,loadToolsConfig(e)),s=generatedNativeFiles(e,n,o.ENVIRONMENT,t).filter(t=>existsSync(path.join(e,t)));return[...["APP_ID","APP_NAME","VERSION_DISPLAY","VERSION_INTERNAL"].map(e=>`${e}=${JSON.stringify(o[e])}`),...s.map(t=>`${t}=${JSON.stringify(readFileSync(path.join(e,t),"utf8"))}`)].join("\n")};const requiredGroup=(e,t)=>{const i=e[t];if(void 0===i)throw new Error(`the pattern did not capture group ${t}`);return i},objectsOf=(e,t)=>[...e.matchAll(new RegExp(`\\n\\s*(\\w+)(?: /\\*([^\\n]*?)\\*/)? = \\{\\s*isa = ${t};`,"g"))].map(e=>({id:requiredGroup(e,1),name:(e[2]??"").trim()})),pbxObject=(e,t)=>{const i=new RegExp(`\\n\\s*${t}(?: /\\*[^\\n]*?\\*/)? = \\{`).exec(e);if(!i)return;let o=0;for(let t=i.index+i[0].length-1;t<e.length;t++)if(e.startsWith("/*",t)){if(t=e.indexOf("*/",t+2)+1,0===t)return}else if('"'===e[t])for(t++;t<e.length&&'"'!==e[t];t++)"\\"===e[t]&&t++;else if("{"===e[t])o++;else if("}"===e[t]&&0===--o)return e.slice(i.index,t+1)},configurationsOf=(e,t)=>[...(/buildConfigurations = \(([^)]*)\)/.exec(pbxObject(e,t)??"")?.[1]??"").matchAll(/(\w+)(?: \/\* ([^*]*?) \*\/)?,/g)].map(e=>({id:requiredGroup(e,1),name:e[2]??""})),unquote=e=>e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e,shipsInfoPlist=e=>/^com\.apple\.product-type\.(application|.*extension)/.test(e);export const shippedInfoPlists=e=>{const t=new Map,i=/\n\s*(\w+)(?: \/\*[^\n]*?\*\/)? = \{\s*isa = PBXNativeTarget;/g;for(const o of e.matchAll(i)){const i=requiredGroup(o,1),n=pbxObject(e,i)??"",s=unquote(/\sproductType = ([^;\n]*);/.exec(n)?.[1]??"");if(!shipsInfoPlist(s))continue;const r=unquote(/\sname = ([^;\n]*);/.exec(n)?.[1]??i),a=/\sbuildConfigurationList = (\w+)/.exec(n)?.[1],p=a&&pbxObject(e,a)||"",c=/buildConfigurations = \(([^)]*)\)/.exec(p)?.[1]??"";for(const i of c.matchAll(/\w+(?= \/\*|,)/g)){const o=requiredGroup(i,0),n=/\sINFOPLIST_FILE = ([^;\n]*);/.exec(pbxObject(e,o)??"")?.[1];n&&!t.has(unquote(n))&&t.set(unquote(n),r)}}return[...t].map(([e,t])=>({target:t,file:e}))};const BUILD_SETTING_KEYS=[["CFBundleIdentifier","PRODUCT_BUNDLE_IDENTIFIER"],["CFBundleShortVersionString","MARKETING_VERSION"],["CFBundleVersion","CURRENT_PROJECT_VERSION"]];export const fixedInfoPlistValues=e=>BUILD_SETTING_KEYS.flatMap(([t,i])=>{const o=new RegExp(`<key>${t}</key>\\s*(<[^>]*>)?([^<]*)`).exec(e);if(!o)return[];const n=requiredGroup(o,2),s=o[1],r="<string>"===s?n.trim():s??n.trim();return r===`$(${i})`||r===`\${${i}}`?[]:[{key:t,value:r,setting:i}]});export const checkInfoPlistReferences=(e,t)=>{const i=path.join(e,"ios"),o=readFileSync(path.join(i,`${t}.xcodeproj`,"project.pbxproj"),"utf8"),n=[{target:t,file:`${t}/Info.plist`},...shippedInfoPlists(o)],s=path.resolve(i,`${t}/Info.plist`),r=[],a=new Set;for(const{target:t,file:o}of n){const n=o.replace(/^(\$\(SRCROOT\)|\$\{SRCROOT\}|\$\(PROJECT_DIR\))\//,"");if(/\$[({]/.test(n)){r.push(`target ${t}: INFOPLIST_FILE ${o} uses a build setting prebuild cannot resolve`);continue}const p=path.resolve(i,n);if(a.has(p))continue;a.add(p);const c=path.relative(e,p).replace(/\\/g,"/");if(!existsSync(p)){r.push(`${c} not found (INFOPLIST_FILE of target ${t})`);continue}const d=readFileSync(p,"utf8");for(const{key:e,value:t,setting:i}of fixedInfoPlistValues(d))r.push(`${c}: ${e} is "${t}", must be $(${i})`);p!==s||/<key>CFBundleDisplayName<\/key>\s*<string>\$\(APP_NAME\)<\/string>/.test(d)||r.push(`${c}: CFBundleDisplayName must be $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}r.length>0&&fail("appConfigInvalid",`Info.plist values that ignore what prebuild writes into appsettings.Compiled.xcconfig:\n ${r.join("\n ")}`)};const XCCONFIG_BASE=/baseConfigurationReference = \w+ \/\* appsettings\.Compiled\.xcconfig \*\//,MANAGED_BUILD_SETTINGS=["PRODUCT_BUNDLE_IDENTIFIER","MARKETING_VERSION","CURRENT_PROJECT_VERSION"];export const checkPbxprojSettings=(e,t)=>{const i=[],o=objectsOf(e,"PBXProject")[0];void 0===o&&i.push("project.pbxproj has no PBXProject object to carry the base configuration");const n=o?/\sbuildConfigurationList = (\w+)/.exec(pbxObject(e,o.id)??"")?.[1]:void 0;for(const{id:t,name:o}of n?configurationsOf(e,n):[])XCCONFIG_BASE.test(pbxObject(e,t)??"")||i.push(`project configuration ${t} /* ${o} */ does not use appsettings.Compiled.xcconfig as its base configuration: set the project-level configurations' base configuration to appsettings.Compiled.xcconfig`);const s=t?[...MANAGED_BUILD_SETTINGS,"ASSETCATALOG_COMPILER_APPICON_NAME"]:MANAGED_BUILD_SETTINGS;for(const{id:t,name:o}of objectsOf(e,"XCBuildConfiguration")){const n=pbxObject(e,t)??"";for(const e of s)new RegExp(`\\s${e} = `).test(n)&&i.push(`configuration ${t} /* ${o} */ sets ${e}: remove it; ios/appsettings.Compiled.xcconfig sets it`);/\sINFOPLIST_KEY_CFBundleDisplayName = /.test(n)&&i.push(`configuration ${t} /* ${o} */ sets INFOPLIST_KEY_CFBundleDisplayName: remove it; Info.plist reads $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}i.length>0&&fail("appConfigInvalid",`project.pbxproj sets values that ios/appsettings.Compiled.xcconfig owns:\n ${i.join("\n ")}`)};const XCCONFIG_UNSAFE=/\/\/|[$";]/,xcconfigText=(e,t,i)=>{const o=[["APP_NAME",String(e.APP_NAME)],["PRODUCT_BUNDLE_IDENTIFIER",applicationId(String(e.APP_ID),t)],["MARKETING_VERSION",String(e.VERSION_DISPLAY)],["CURRENT_PROJECT_VERSION",String(e.VERSION_INTERNAL)],...i?[["ASSETCATALOG_COMPILER_APPICON_NAME",`AppIcon-${t}`]]:[]];for(const[e,t]of o)XCCONFIG_UNSAFE.test(t)&&fail("appConfigInvalid",`${e} must not contain // $ " or ;: it is written unquoted into ios/appsettings.Compiled.xcconfig`);return["// Written by mobile-tools prebuild from appsettings.Compiled.json for one environment. Not tracked: run prebuild to change it.",...o.map(([e,t])=>`${e} = ${t}`)].map(e=>`${e}\n`).join("")};export const buildCommit=e=>{const t=findOnPath("git",process.env,process.platform);if(!t)return"nogit";const i=capture({file:t,args:["rev-parse","--short","HEAD"]},e);if(0!==i.status)return"nogit";const o=capture({file:t,args:["status","--porcelain","--","."]},e);return 0!==o.status?fail("toolFailed",`git status failed in ${e}: ${o.stderr.trim()}`):""===o.stdout.trim()?i.stdout.trim():`${i.stdout.trim()}-dirty`};export const requireIgnored=(e,t)=>{const i=findOnPath("git",process.env,process.platform);if(!i||0!==capture({file:i,args:["rev-parse","--is-inside-work-tree"]},e).status)return;const o=t.filter(t=>{const o=capture({file:i,args:["check-ignore","-q","--",t]},e);return 0!==o.status&&1!==o.status&&fail("toolFailed",`git check-ignore failed for ${t}: ${o.stderr.trim()}`),1===o.status});o.length>0&&fail("appConfigInvalid",`add these lines to ${path.basename(e)}/.gitignore; prebuild writes them per environment:\n${o.join("\n")}`)};const writeIfChanged=(e,t)=>(!existsSync(e)||readFileSync(e,"utf8")!==t)&&(writeFileSync(e,t,"utf8"),!0),report=(e,t,i)=>{say(`prebuild: ${i?"wrote":"unchanged"} ${path.relative(e,t)}`)},dependsOn=(e,t)=>{const i=path.join(e,"package.json");if(!existsSync(i))return!1;const o=JSON.parse(readFileSync(i,"utf8"));return Boolean(o.dependencies?.[t])};export const usesFirebase=e=>dependsOn(e,"@react-native-firebase/app");export const checkNdkHook=e=>{const t=path.join(e,"android","build.gradle");if(!existsSync(t))return;const i=readFileSync(t,"utf8");/withId\(\s*["']com\.android\.library["']\s*\)/.test(i)&&/\.ndkVersion\s*=\s*rootProject\.ext\.ndkVersion/.test(i)||fail("appConfigInvalid",'android/build.gradle does not hand the app NDK to library modules; add after apply plugin "com.facebook.react.rootproject": subprojects { project -> project.plugins.withId("com.android.library") { project.android.ndkVersion = rootProject.ext.ndkVersion } }')};const MANAGED_GRADLE_KEYS=/^\s*(APP_NAME|APP_ID|VERSION_DISPLAY|VERSION_INTERNAL)\s*[=:]/gm;export const stampAndroid=(e,t,i,o,n)=>{const s=path.join(e,"android","gradle.properties");existsSync(s)||fail("appConfigInvalid",`android/gradle.properties not found in ${e}`),usesFirebase(e)&&!existsSync(path.join(e,"android","app","google-services.json"))&&fail("appConfigInvalid","android/app/google-services.json is missing; the app uses @react-native-firebase, whose Gradle plugin needs it"),checkNdkHook(e);const r=[...new Set([...readFileSync(s,"utf8").matchAll(MANAGED_GRADLE_KEYS)].map(([,e])=>e))];r.length>0&&fail("appConfigInvalid",`android/gradle.properties sets ${r.join(", ")}: remove them; android/app/build.gradle reads them from appsettings.Compiled.json`);const a=path.join(e,"android","app","build.gradle");if(existsSync(a)&&readFileSync(a,"utf8").includes("appsettings.Compiled.json")||fail("appConfigInvalid","android/app/build.gradle does not read appsettings.Compiled.json; add the compiledSettings loader (mobile-tools README, prebuild)"),usesExpoUpdates(e)){o.flavors||fail("appConfigInvalid",'expo-updates settings go into the flavor\'s manifest; set "flavors": true');const s=path.join(e,"android","app","src","main","AndroidManifest.xml");existsSync(s)||fail("appConfigInvalid","android/app/src/main/AndroidManifest.xml not found");const r=[...readFileSync(s,"utf8").matchAll(/android:name="(expo\.modules\.updates\.[^"]*)"/g)].map(([,e])=>e);r.length>0&&fail("appConfigInvalid",`android/app/src/main/AndroidManifest.xml sets ${r.join(", ")}: remove them from android/app/src/main/AndroidManifest.xml; prebuild writes them into ${androidFlavorManifest(i)}`);const a=otaNativeSettings(e,t,i,"android",n),p=path.join(e,androidFlavorManifest(i));mkdirSync(path.dirname(p),{recursive:!0}),report(e,p,writeIfChanged(p,androidOtaManifest(a)))}};export const stampIos=(e,t,i,o,n,s)=>{const r=path.join(e,"ios",n),a=path.join(r,"Info.plist"),p=path.join(e,"ios",`${n}.xcodeproj`,"project.pbxproj");for(const t of[a,p])existsSync(t)||fail("appConfigInvalid",`${path.relative(e,t)} not found: check "iosProjectName"`);checkInfoPlistReferences(e,n);const c=`AppIcon-${i}`,d=path.join(r,"Images.xcassets"),l=existsSync(path.join(d,`${c}.appiconset`)),f=ENVIRONMENTS.filter(e=>e!==i&&existsSync(path.join(d,`AppIcon-${e}.appiconset`)));!l&&f.length>0&&fail("appConfigInvalid",`ios/${n}/Images.xcassets has AppIcon-${f[0]} but no ${c}: run mobile-tools icons`),checkPbxprojSettings(readFileSync(p,"utf8"),l);const u=path.join(e,IOS_COMPILED_XCCONFIG);report(e,u,writeIfChanged(u,xcconfigText(t,i,l))),l||say(`prebuild: no AppIcon-${i} set, so ios/appsettings.Compiled.xcconfig sets no app icon name`);const g=path.join(r,"GoogleService-Info.plist"),I=path.join(e,o.firebasePlistDir,`GoogleService-Info.${i}.plist`);if(!existsSync(I)&&usesFirebase(e)&&fail("appConfigInvalid",`${path.relative(e,I)} is missing; the app uses @react-native-firebase, and an iOS build without it reports no crashes`),existsSync(I)){const t=!existsSync(g)||!readFileSync(I).equals(readFileSync(g));t&&copyFileSync(I,g),report(e,g,t)}else existsSync(g)&&(rmSync(g),say(`prebuild: removed ${path.relative(e,g)}, no ${path.relative(e,I)}`));if(usesExpoUpdates(e)){readFileSync(p,"utf8").includes("Expo.plist in Resources")||fail("appConfigInvalid","add Supporting/Expo.plist to the Xcode project's Copy Bundle Resources; prebuild writes its contents");const o=otaNativeSettings(e,t,i,"ios",s),r=path.join(e,expoPlistPath(n));mkdirSync(path.dirname(r),{recursive:!0}),report(e,r,writeIfChanged(r,expoPlist(o)))}};const resolveEnvironment=(e,t,i,o)=>{o&&i&&fail("badInput","pass --env or --same-env, not both");return(o?lastCompiledEnvironment(t):i)??fail("badInput",`${e} needs --env <Development|Staging|Production> or --same-env`)},checkedSettings=(e,t,i)=>{const o=loadAppSettings(e,t,i.requiredSettings);return checkAppSettings(e,o,t),o},writeCompiledSettings=(e,t,i,o)=>{const n={...i,COMMIT:buildCommit(t),BUILD_TIME:(new Date).toISOString()};return writeFileSync(path.join(t,COMPILED_FILE),`${JSON.stringify(n,null,2)}\n`,"utf8"),say(`${e}: wrote ${COMPILED_FILE} (${o}, ${n.COMMIT})`),n};export const compileSettings=e=>{const{appRoot:t}=e,i=resolveEnvironment("settings",t,e.env,e.sameEnv),o=checkedSettings(t,i,loadToolsConfig(t));return requireIgnored(t,[COMPILED_FILE]),writeCompiledSettings("settings",t,o,i)};export const prebuild=e=>{const{appRoot:t,platform:i}=e,o=!0===e.otaTest,n=resolveEnvironment("prebuild",t,e.env,e.sameEnv),s=loadToolsConfig(t),r=resolveIosProjectName(t,s),a=checkedSettings(t,n,s),p="android"===i||!i&&existsSync(path.join(t,"android")),c="android"===i?void 0:r;if("ios"===i&&void 0===c)return fail("appConfigInvalid",`no ios/ folder in ${t}`);const d=[...p?generatedNativeFiles(t,c,n,"android"):[],...void 0!==c?generatedNativeFiles(t,c,n,"ios"):[]];requireIgnored(t,[COMPILED_FILE,...d]);const l=writeCompiledSettings("prebuild",t,a,n);return p&&stampAndroid(t,l,n,s,o),void 0!==c&&stampIos(t,l,n,s,c,o),l};
package/lib/sync.d.ts CHANGED
@@ -6,7 +6,7 @@ export type PackageManager = "npm" | "pnpm";
6
6
  export interface InstallStamp {
7
7
  hash: string;
8
8
  manager: PackageManager;
9
- nativePackages?: Record<string, string>;
9
+ nativePackages: Record<string, string>;
10
10
  }
11
11
  export declare const lockfileOf: (appRoot: string) => {
12
12
  manager: PackageManager;
package/lib/sync.js CHANGED
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import path from"node:path";import{isRecord}from"./config.js";import{capture,runInherit}from"./exec.js";import{CliError,fail,say}from"./output.js";import{findOnPath,gradleInvocation,npmInvocation,pnpmInvocation}from"./platform.js";import{prependXosShims,xosPath}from"./xos.js";export const STAMP_FILE=path.join("node_modules",".webority-install.json");export const PODS_RECORD=path.join("ios","Pods",".webority-native.json");const INSTALL_FIELDS=["dependencies","devDependencies","optionalDependencies","peerDependencies","bundleDependencies","overrides","resolutions","pnpm","workspaces"];export const lockfileOf=e=>{const s=path.join(e,"pnpm-lock.yaml"),o=path.join(e,"package-lock.json");return existsSync(s)&&existsSync(o)?fail("appConfigInvalid","both pnpm-lock.yaml and package-lock.json exist: delete the one not in use"):existsSync(s)?{manager:"pnpm",file:s}:existsSync(o)?{manager:"npm",file:o}:fail("appConfigInvalid",`no package-lock.json or pnpm-lock.yaml in ${e}`)};const filesUnder=(e,s="")=>readdirSync(e,{withFileTypes:!0}).flatMap(o=>{const n=""===s?o.name:`${s}/${o.name}`;return o.isDirectory()?filesUnder(path.join(e,o.name),n):[n]}).sort();export const installHash=e=>{const{file:s}=lockfileOf(e),o=JSON.parse(readFileSync(path.join(e,"package.json"),"utf8"));if(!isRecord(o))return fail("appConfigInvalid",`${path.join(e,"package.json")} must hold a JSON object`);const n=createHash("sha256");n.update(`lockfile:${path.basename(s)}\0`),n.update(readFileSync(s)),n.update("\0package.json\0"),n.update(JSON.stringify(INSTALL_FIELDS.map(e=>[e,o[e]??null])));const t=path.join(e,"patches");if(existsSync(t))for(const e of filesUnder(t))n.update(`\0patches/${e}\0`),n.update(readFileSync(path.join(t,...e.split("/"))));return n.digest("hex")};const isInstallStamp=e=>isRecord(e)&&"string"==typeof e.hash&&("npm"===e.manager||"pnpm"===e.manager)&&(void 0===e.nativePackages||isRecord(e.nativePackages)&&Object.values(e.nativePackages).every(e=>"string"==typeof e));export const readStamp=e=>{const s=path.join(e,STAMP_FILE);if(existsSync(s))try{const e=JSON.parse(readFileSync(s,"utf8"));return isInstallStamp(e)?e:void 0}catch{return}};const POD_FIX="cd ios && pod install",hasXos=e=>void 0!==findOnPath("xos",process.env,e),installsPods=e=>"darwin"===e||hasXos(e);export const podsStale=e=>{const s=path.join(e,"ios","Podfile.lock"),o=path.join(e,"ios","Pods","Manifest.lock");return!(!existsSync(s)||!existsSync(o))&&!readFileSync(s).equals(readFileSync(o))};const nodeModulesNewerThanPods=e=>{const s=[path.join(e,"node_modules",".modules.yaml"),path.join(e,"node_modules",".pnpm","lock.yaml")].find(e=>existsSync(e)),o=path.join(e,"ios","Pods","Manifest.lock");return!(!s||!existsSync(o))&&statSync(s).mtimeMs>statSync(o).mtimeMs};export const checkSync=(e,s,o=!0)=>{const n=[],t=readStamp(e),{file:a}=lockfileOf(e);if(t?t.hash!==installHash(e)&&n.push(`node_modules is stale: ${path.basename(a)}, package.json or patches/ changed since the last install. Fix: npx mobile-tools sync`):n.push("node_modules has no install stamp (never installed through mobile-tools). Fix: npx mobile-tools sync"),t){const s=changedNativePackages(t.nativePackages??{},nativePackages(e));s.length>0&&n.push(`node_modules native packages changed since the last install: ${s.join(", ")}. Fix: npx mobile-tools sync`)}const i=o&&installsPods(s);return i&&podsStale(e)&&n.push(`ios/Pods is stale: ios/Podfile.lock differs from ios/Pods/Manifest.lock. Fix: ${POD_FIX}`),i&&existsSync(path.join(e,"ios","Podfile.lock"))&&nodeModulesNewerThanPods(e)&&n.push("node_modules changed after the last pod install; run pod install in ios/ (or mobile-tools sync)"),n};export const requireSynced=(e,{pods:s})=>{const o=checkSync(e,process.platform,s);o.length>0&&fail("installStale",o.join("\n"))};export const nativePackages=e=>{const s=path.join(e,"node_modules");if(!existsSync(s))return{};const o=[];for(const e of readdirSync(s,{withFileTypes:!0}))if(!e.name.startsWith(".")&&e.isDirectory())if(e.name.startsWith("@"))for(const n of readdirSync(path.join(s,e.name),{withFileTypes:!0}))n.isDirectory()&&o.push(path.join(s,e.name,n.name));else o.push(path.join(s,e.name));const n={};for(const e of o){const s=path.join(e,"android"),o=path.join(e,"package.json");if(existsSync(s)&&statSync(s).isDirectory()&&existsSync(o))try{const e=JSON.parse(readFileSync(o,"utf8"));isRecord(e)&&"string"==typeof e.name&&"string"==typeof e.version&&""!==e.name&&""!==e.version&&(n[e.name]=e.version)}catch(e){fail("toolFailed",`${o} is not valid package.json, so its native package cannot be read: ${e instanceof Error?e.message:String(e)}`)}}return n};export const changedNativePackages=(e,s)=>[...new Set([...Object.keys(e),...Object.keys(s)])].filter(o=>e[o]!==s[o]).sort();const POD_INPUT_FILES=["ios/Podfile","ios/Podfile.properties.json"],podInputsHash=e=>{const s=createHash("sha256");for(const o of POD_INPUT_FILES){const n=path.join(e,...o.split("/"));s.update(`${o}\0`),existsSync(n)&&s.update(readFileSync(n))}return s.digest("hex")};export const podsRecord=e=>JSON.stringify({nativePackages:nativePackages(e),podInputs:podInputsHash(e)});export const writeStamp=e=>{const{manager:s}=lockfileOf(e),o={hash:installHash(e),manager:s,nativePackages:nativePackages(e)};return writeFileSync(path.join(e,STAMP_FILE),`${JSON.stringify(o,null,2)}\n`,"utf8"),o};export const installInvocation=(e,s)=>"pnpm"===e?pnpmInvocation(["install","--frozen-lockfile"],process.env,s,process.execPath):npmInvocation(["ci"],process.env,s,process.execPath);export const localPathPods=e=>{const s=[];let o,n=!1;for(const t of e.split(/\r?\n/)){if(/^\S/.test(t)){n="EXTERNAL SOURCES:"===t,o=void 0;continue}if(!n)continue;const e=/^ {2}"?([^"\s:]+)"?:$/.exec(t);e?o=e[1]:void 0!==o&&/^ {4}:path:/.test(t)&&(s.push(o),o=void 0)}return s};const recordChange=(e,s)=>{let o;try{o=JSON.parse(e)}catch{return"the pod install record is from an older mobile-tools"}return isRecord(o)&&"string"==typeof o.podInputs&&isRecord(o.nativePackages)?o.podInputs!==podInputsHash(s)?"ios/Podfile or ios/Podfile.properties.json changed since the last pod install":JSON.stringify(o.nativePackages)!==JSON.stringify(nativePackages(s))?"native packages changed since the last pod install":void 0:"the pod install record is from an older mobile-tools"},POD_VERSION_MOVED=/changed the version of the dependency|pod update/,runPod=(e,s,o)=>{const n=capture({file:e,args:s},o);return-1===n.status&&fail("toolFailed",`pod ${s[0]} could not start: ${n.stderr}`),process.stdout.write(n.stdout),process.stderr.write(n.stderr),n};export const ensurePods=(e,s)=>{if(!existsSync(path.join(e,"ios","Podfile")))return;const o=path.join(e,"ios","Pods"),n=path.join(e,PODS_RECORD);let t;if(t=existsSync(o)?existsSync(path.join(e,"ios","Podfile.lock"))?existsSync(path.join(o,"Manifest.lock"))?podsStale(e)?"ios/Podfile.lock differs from ios/Pods/Manifest.lock":nodeModulesNewerThanPods(e)?"node_modules changed after the last pod install":existsSync(n)?recordChange(readFileSync(n,"utf8"),e):"no pod install record":"ios/Pods/Manifest.lock is missing":"ios/Podfile.lock is missing":"ios/Pods is missing",void 0===t)return void say("pods: up to date with ios/Podfile.lock and the Podfile settings");say(`pods: ${t}; running pod install`);const a=findOnPath("pod",process.env,s);if(!a){const e=hasXos(s)?"check xos doctor --json names its shims folder":"install CocoaPods (brew install cocoapods)";throw new CliError("toolMissing",`pod not found on PATH; ${e}, then ${POD_FIX}`)}const i=path.join(e,"ios");let c=runPod(a,["install"],i);if(0!==c.status&&POD_VERSION_MOVED.test(`${c.stdout}${c.stderr}`)){const e=path.join(i,"Podfile.lock"),s=existsSync(e)?localPathPods(readFileSync(e,"utf8")):[];s.length>0&&(say(`pods: updating ${s.length} local pods moved by a package upgrade`),c=runPod(a,["update",...s,"--no-repo-update"],i),0!==c.status&&fail("toolFailed",`pod update failed (exit ${c.status})`))}0!==c.status&&fail("toolFailed",`pod install failed (exit ${c.status})`);const r=path.join(e,"ios","build","ModuleCache.noindex");existsSync(r)&&(rmSync(r,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,r)}`)),writeFileSync(n,podsRecord(e),"utf8")};export const sync=(e,s)=>{const{manager:o}=lockfileOf(e),n=readStamp(e)?.nativePackages??nativePackages(e);say("sync: "+("pnpm"===o?"pnpm install --frozen-lockfile":"npm ci")),runInherit(installInvocation(o,s),e,`${o} install`);const t=writeStamp(e).nativePackages,a=changedNativePackages(n,t),i=path.join(e,"android"),c=existsSync(path.join(i,"app",".cxx"))||existsSync(path.join(i,"app","build"));if(a.length>0&&c){say(`sync: native packages changed (${a.join(", ")}): regenerating codegen`),runInherit(gradleInvocation(i,["generateCodegenArtifactsFromSchema"],s,process.env),i,"gradlew generateCodegenArtifactsFromSchema");for(const s of[path.join(i,"app",".cxx"),path.join(i,"app","build","generated","autolinking")])rmSync(s,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,s)}`)}installsPods(s)&&existsSync(path.join(e,"ios","Podfile"))&&(hasXos(s)&&prependXosShims(xosPath(process.env,s),e),ensurePods(e,s)),say("sync: done")};
1
+ import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import path from"node:path";import{isRecord}from"./config.js";import{capture,runInherit}from"./exec.js";import{CliError,fail,say}from"./output.js";import{findOnPath,gradleInvocation,npmInvocation,pnpmInvocation}from"./platform.js";import{prependXosToolPath,xosPath}from"./xos.js";export const STAMP_FILE=path.join("node_modules",".webority-install.json");export const PODS_RECORD=path.join("ios","Pods",".webority-native.json");const INSTALL_FIELDS=["dependencies","devDependencies","optionalDependencies","peerDependencies","bundleDependencies","overrides","resolutions","pnpm","workspaces"];export const lockfileOf=e=>{const s=path.join(e,"pnpm-lock.yaml"),o=path.join(e,"package-lock.json");return existsSync(s)&&existsSync(o)?fail("appConfigInvalid","both pnpm-lock.yaml and package-lock.json exist: delete the one not in use"):existsSync(s)?{manager:"pnpm",file:s}:existsSync(o)?{manager:"npm",file:o}:fail("appConfigInvalid",`no package-lock.json or pnpm-lock.yaml in ${e}`)};const filesUnder=(e,s="")=>readdirSync(e,{withFileTypes:!0}).flatMap(o=>{const n=""===s?o.name:`${s}/${o.name}`;return o.isDirectory()?filesUnder(path.join(e,o.name),n):[n]}).sort();export const installHash=e=>{const{file:s}=lockfileOf(e),o=JSON.parse(readFileSync(path.join(e,"package.json"),"utf8"));if(!isRecord(o))return fail("appConfigInvalid",`${path.join(e,"package.json")} must hold a JSON object`);const n=createHash("sha256");n.update(`lockfile:${path.basename(s)}\0`),n.update(readFileSync(s)),n.update("\0package.json\0"),n.update(JSON.stringify(INSTALL_FIELDS.map(e=>[e,o[e]??null])));const t=path.join(e,"patches");if(existsSync(t))for(const e of filesUnder(t))n.update(`\0patches/${e}\0`),n.update(readFileSync(path.join(t,...e.split("/"))));return n.digest("hex")};const isInstallStamp=e=>isRecord(e)&&"string"==typeof e.hash&&("npm"===e.manager||"pnpm"===e.manager)&&isRecord(e.nativePackages)&&Object.values(e.nativePackages).every(e=>"string"==typeof e);export const readStamp=e=>{const s=path.join(e,STAMP_FILE);if(existsSync(s))try{const e=JSON.parse(readFileSync(s,"utf8"));return isInstallStamp(e)?e:void 0}catch{return}};const POD_FIX="cd ios && pod install",hasXos=e=>void 0!==findOnPath("xos",process.env,e),installsPods=e=>"darwin"===e||hasXos(e);export const podsStale=e=>{const s=path.join(e,"ios","Podfile.lock"),o=path.join(e,"ios","Pods","Manifest.lock");return!(!existsSync(s)||!existsSync(o))&&!readFileSync(s).equals(readFileSync(o))};const nodeModulesNewerThanPods=e=>{const s=[path.join(e,"node_modules",".modules.yaml"),path.join(e,"node_modules",".pnpm","lock.yaml")].find(e=>existsSync(e)),o=path.join(e,"ios","Pods","Manifest.lock");return!(!s||!existsSync(o))&&statSync(s).mtimeMs>statSync(o).mtimeMs};export const checkSync=(e,s,o=!0)=>{const n=[],t=readStamp(e),{file:a}=lockfileOf(e);if(t?t.hash!==installHash(e)&&n.push(`node_modules is stale: ${path.basename(a)}, package.json or patches/ changed since the last install. Fix: npx mobile-tools sync`):n.push("node_modules has no install stamp (never installed through mobile-tools). Fix: npx mobile-tools sync"),t){const s=changedNativePackages(t.nativePackages,nativePackages(e));s.length>0&&n.push(`node_modules native packages changed since the last install: ${s.join(", ")}. Fix: npx mobile-tools sync`)}const i=o&&installsPods(s);return i&&podsStale(e)&&n.push(`ios/Pods is stale: ios/Podfile.lock differs from ios/Pods/Manifest.lock. Fix: ${POD_FIX}`),i&&existsSync(path.join(e,"ios","Podfile.lock"))&&nodeModulesNewerThanPods(e)&&n.push("node_modules changed after the last pod install; run pod install in ios/ (or mobile-tools sync)"),n};export const requireSynced=(e,{pods:s})=>{const o=checkSync(e,process.platform,s);o.length>0&&fail("installStale",o.join("\n"))};export const nativePackages=e=>{const s=path.join(e,"node_modules");if(!existsSync(s))return{};const o=[];for(const e of readdirSync(s,{withFileTypes:!0}))if(!e.name.startsWith(".")&&e.isDirectory())if(e.name.startsWith("@"))for(const n of readdirSync(path.join(s,e.name),{withFileTypes:!0}))n.isDirectory()&&o.push(path.join(s,e.name,n.name));else o.push(path.join(s,e.name));const n={};for(const e of o){const s=path.join(e,"android"),o=path.join(e,"package.json");if(existsSync(s)&&statSync(s).isDirectory()&&existsSync(o))try{const e=JSON.parse(readFileSync(o,"utf8"));isRecord(e)&&"string"==typeof e.name&&"string"==typeof e.version&&""!==e.name&&""!==e.version&&(n[e.name]=e.version)}catch(e){fail("toolFailed",`${o} is not valid package.json, so its native package cannot be read: ${e instanceof Error?e.message:String(e)}`)}}return n};export const changedNativePackages=(e,s)=>[...new Set([...Object.keys(e),...Object.keys(s)])].filter(o=>e[o]!==s[o]).sort();const POD_INPUT_FILES=["ios/Podfile","ios/Podfile.properties.json"],podInputsHash=e=>{const s=createHash("sha256");for(const o of POD_INPUT_FILES){const n=path.join(e,...o.split("/"));s.update(`${o}\0`),existsSync(n)&&s.update(readFileSync(n))}return s.digest("hex")};export const podsRecord=e=>JSON.stringify({nativePackages:nativePackages(e),podInputs:podInputsHash(e)});export const writeStamp=e=>{const{manager:s}=lockfileOf(e),o={hash:installHash(e),manager:s,nativePackages:nativePackages(e)};return writeFileSync(path.join(e,STAMP_FILE),`${JSON.stringify(o,null,2)}\n`,"utf8"),o};export const installInvocation=(e,s)=>"pnpm"===e?pnpmInvocation(["install","--frozen-lockfile"],process.env,s,process.execPath):npmInvocation(["ci"],process.env,s,process.execPath);export const localPathPods=e=>{const s=[];let o,n=!1;for(const t of e.split(/\r?\n/)){if(/^\S/.test(t)){n="EXTERNAL SOURCES:"===t,o=void 0;continue}if(!n)continue;const e=/^ {2}"?([^"\s:]+)"?:$/.exec(t);e?o=e[1]:void 0!==o&&/^ {4}:path:/.test(t)&&(s.push(o),o=void 0)}return s};const recordChange=(e,s)=>{let o;try{o=JSON.parse(e)}catch{return"the pod install record is unreadable"}return isRecord(o)&&"string"==typeof o.podInputs&&isRecord(o.nativePackages)?o.podInputs!==podInputsHash(s)?"ios/Podfile or ios/Podfile.properties.json changed since the last pod install":JSON.stringify(o.nativePackages)!==JSON.stringify(nativePackages(s))?"native packages changed since the last pod install":void 0:"the pod install record is incomplete"},POD_VERSION_MOVED=/changed the version of the dependency|pod update/,runPod=(e,s,o)=>{const n=capture({file:e,args:s},o);return-1===n.status&&fail("toolFailed",`pod ${s[0]} could not start: ${n.stderr}`),process.stdout.write(n.stdout),process.stderr.write(n.stderr),n};export const ensurePods=(e,s)=>{if(!existsSync(path.join(e,"ios","Podfile")))return;const o=path.join(e,"ios","Pods"),n=path.join(e,PODS_RECORD);let t;if(t=existsSync(o)?existsSync(path.join(e,"ios","Podfile.lock"))?existsSync(path.join(o,"Manifest.lock"))?podsStale(e)?"ios/Podfile.lock differs from ios/Pods/Manifest.lock":nodeModulesNewerThanPods(e)?"node_modules changed after the last pod install":existsSync(n)?recordChange(readFileSync(n,"utf8"),e):"no pod install record":"ios/Pods/Manifest.lock is missing":"ios/Podfile.lock is missing":"ios/Pods is missing",void 0===t)return void say("pods: up to date with ios/Podfile.lock and the Podfile settings");say(`pods: ${t}; running pod install`);const a=findOnPath("pod",process.env,s);if(!a){const e=hasXos(s)?"check xos doctor --json names its shims folder":"install CocoaPods (brew install cocoapods)";throw new CliError("toolMissing",`pod not found on PATH; ${e}, then ${POD_FIX}`)}const i=path.join(e,"ios");let c=runPod(a,["install"],i);if(0!==c.status&&POD_VERSION_MOVED.test(`${c.stdout}${c.stderr}`)){const e=path.join(i,"Podfile.lock"),s=existsSync(e)?localPathPods(readFileSync(e,"utf8")):[];s.length>0&&(say(`pods: updating ${s.length} local pods moved by a package upgrade`),c=runPod(a,["update",...s,"--no-repo-update"],i),0!==c.status&&fail("toolFailed",`pod update failed (exit ${c.status})`))}0!==c.status&&fail("toolFailed",`pod install failed (exit ${c.status})`);const r=path.join(e,"ios","build","ModuleCache.noindex");existsSync(r)&&(rmSync(r,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,r)}`)),writeFileSync(n,podsRecord(e),"utf8")};export const sync=(e,s)=>{const{manager:o}=lockfileOf(e),n=readStamp(e)?.nativePackages??nativePackages(e);say("sync: "+("pnpm"===o?"pnpm install --frozen-lockfile":"npm ci")),runInherit(installInvocation(o,s),e,`${o} install`);const t=writeStamp(e).nativePackages,a=changedNativePackages(n,t),i=path.join(e,"android"),c=existsSync(path.join(i,"app",".cxx"))||existsSync(path.join(i,"app","build"));if(a.length>0&&c){say(`sync: native packages changed (${a.join(", ")}): regenerating codegen`),runInherit(gradleInvocation(i,["generateCodegenArtifactsFromSchema"],s,process.env),i,"gradlew generateCodegenArtifactsFromSchema");for(const s of[path.join(i,"app",".cxx"),path.join(i,"app","build","generated","autolinking")])rmSync(s,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,s)}`)}installsPods(s)&&existsSync(path.join(e,"ios","Podfile"))&&(hasXos(s)&&prependXosToolPath(xosPath(process.env,s),e),ensurePods(e,s)),say("sync: done")};
package/lib/xos.d.ts CHANGED
@@ -13,7 +13,7 @@ export declare const XOS_MISSING_MESSAGE = "xos not found on PATH. iOS simulator
13
13
  /** xos on PATH, else toolMissing with the recipe for building on a host that has xos. */
14
14
  export declare const xosPath: (env: Env, platform: HostPlatform) => string;
15
15
  /** Puts the shim folder `xos doctor --json` names (field `shims`) first on this process's PATH, as ios-release.sh does before pod install. */
16
- export declare const prependXosShims: (xos: string, cwd: string) => void;
16
+ export declare const prependXosToolPath: (xos: string, cwd: string) => void;
17
17
  /** Where an ios-sim build writes its pods, intermediates and app. */
18
18
  export declare const simulatorBuildDir: (appRoot: string, configuration: IosConfiguration) => string;
19
19
  /** `xos build --pods` then `xos app` for the simulator, both into `log`; returns the absolute path of <projectName>.app. */
package/lib/xos.js CHANGED
@@ -1 +1 @@
1
- import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail}from"./buildLog.js";import{capture}from"./exec.js";import{fail}from"./output.js";import{findOnPath}from"./platform.js";export const SIMULATOR_ARCHS=["x86_64","arm64"];export const XOS_MISSING_MESSAGE="xos not found on PATH. iOS simulator apps build with xOS Tools on a build host, not on this machine. Run npx mobile-tools build --env <Env> --artifact ios-sim --debug --arch arm64 on a host that has xos, copy the resulting .app here, then npx mobile-tools run --env <Env> --platform ios --app <path.app>.";export const xosPath=(o,t)=>findOnPath("xos",o,t)??fail("toolMissing",XOS_MISSING_MESSAGE);export const prependXosShims=(o,t)=>{const i=capture({file:o,args:["doctor","--json"]},t);let s;0!==i.status&&fail("toolMissing",`xos doctor failed: ${i.stderr.trim()}`);try{s=JSON.parse(i.stdout).shims}catch{s=void 0}"string"!=typeof s&&fail("toolFailed","xos doctor --json printed no string field shims: reinstall xOS Tools, then run xos doctor --json and check it prints shims"),process.env.PATH=s+path.delimiter+(process.env.PATH??"")};export const simulatorBuildDir=(o,t)=>path.join(o,"ios","build","xos",`${t}-iphonesimulator`);export const xosSimulatorBuild=async(o,t,i)=>{const{appRoot:s,projectName:a,configuration:r,arch:n}=t,e=simulatorBuildDir(s,r);await buildOrFail({file:o,args:["build","--pods",path.join("ios","Pods"),"--build-dir",e,"--configuration",r,"--platform","iossimulator","--arch",n,"--jobs","0"]},s,i,"xos build --pods"),await buildOrFail({file:o,args:["app","--project",path.join("ios",`${a}.xcodeproj`),"--target",a,"--configuration",r,"--platform","iossimulator","--arch",n,"--build-dir",e,"--assets",path.join("ios",a,"Images.xcassets"),"--jobs","0"]},s,i,"xos app");const subfolders=o=>existsSync(o)?readdirSync(o,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(t=>path.join(o,t.name)):[],p=`${a}.app`,l=subfolders(e),d=[...l,...l.flatMap(subfolders)].find(o=>path.basename(o)===p)??fail("artifactMissing",`the build produced no ${p} in ${e}: read the xos log at ${i}`);return path.resolve(d)};
1
+ import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail}from"./buildLog.js";import{capture}from"./exec.js";import{fail}from"./output.js";import{findOnPath}from"./platform.js";export const SIMULATOR_ARCHS=["x86_64","arm64"];export const XOS_MISSING_MESSAGE="xos not found on PATH. iOS simulator apps build with xOS Tools on a build host, not on this machine. Run npx mobile-tools build --env <Env> --artifact ios-sim --debug --arch arm64 on a host that has xos, copy the resulting .app here, then npx mobile-tools run --env <Env> --platform ios --app <path.app>.";export const xosPath=(o,t)=>findOnPath("xos",o,t)??fail("toolMissing",XOS_MISSING_MESSAGE);export const prependXosToolPath=(o,t)=>{const i=capture({file:o,args:["doctor","--json"]},t);let s;0!==i.status&&fail("toolMissing",`xos doctor failed: ${i.stderr.trim()}`);try{s=JSON.parse(i.stdout).shims}catch{s=void 0}"string"!=typeof s&&fail("toolFailed","xos doctor --json printed no string field shims: reinstall xOS Tools, then run xos doctor --json and check it prints shims"),process.env.PATH=s+path.delimiter+(process.env.PATH??"")};export const simulatorBuildDir=(o,t)=>path.join(o,"ios","build","xos",`${t}-iphonesimulator`);export const xosSimulatorBuild=async(o,t,i)=>{const{appRoot:s,projectName:a,configuration:r,arch:n}=t,e=simulatorBuildDir(s,r);await buildOrFail({file:o,args:["build","--pods",path.join("ios","Pods"),"--build-dir",e,"--configuration",r,"--platform","iossimulator","--arch",n,"--jobs","0"]},s,i,"xos build --pods"),await buildOrFail({file:o,args:["app","--project",path.join("ios",`${a}.xcodeproj`),"--target",a,"--configuration",r,"--platform","iossimulator","--arch",n,"--build-dir",e,"--assets",path.join("ios",a,"Images.xcassets"),"--jobs","0"]},s,i,"xos app");const subfolders=o=>existsSync(o)?readdirSync(o,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(t=>path.join(o,t.name)):[],p=`${a}.app`,l=subfolders(e),d=[...l,...l.flatMap(subfolders)].find(o=>path.basename(o)===p)??fail("artifactMissing",`the build produced no ${p} in ${e}: read the xos log at ${i}`);return path.resolve(d)};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/mobile-tools",
3
- "version": "0.176.0",
3
+ "version": "0.178.0",
4
4
  "description": "Dev-time CLI for Webority React Native apps: one prebuild, a dependency guard, a device-aware run and per-environment launcher icons, the same on Windows and macOS.",
5
5
  "keywords": [
6
6
  "react-native",