From 09d99ba22677c28bd651f2d3a8f39f33565e0bc0 Mon Sep 17 00:00:00 2001 From: jcesarmobile Date: Thu, 10 Oct 2024 18:23:31 +0200 Subject: [PATCH] chore(deps): Update lint packages and run fmt (#7710) --- .eslintrc.js | 44 -- .../main/java/com/getcapacitor/Bridge.java | 9 +- .../java/com/getcapacitor/BridgeFragment.java | 13 +- .../getcapacitor/BridgeWebChromeClient.java | 217 ++++------ .../main/java/com/getcapacitor/CapConfig.java | 32 +- .../java/com/getcapacitor/MessageHandler.java | 8 +- .../java/com/getcapacitor/UriMatcher.java | 8 +- .../cordova/MockCordovaWebViewImpl.java | 12 +- .../getcapacitor/plugin/CapacitorCookies.java | 47 +- .../com/getcapacitor/ConfigBuildingTest.java | 31 +- .../plugin/util/HttpRequestHandlerTest.java | 7 +- cli/src/android/add.ts | 16 +- cli/src/android/build.ts | 33 +- cli/src/android/common.ts | 63 +-- cli/src/android/doctor.ts | 151 +++---- cli/src/android/open.ts | 12 +- cli/src/android/run.ts | 22 +- cli/src/android/update.ts | 204 ++------- cli/src/common.ts | 183 ++------ cli/src/config.ts | 130 ++---- cli/src/cordova.ts | 401 ++++-------------- cli/src/errors.ts | 10 +- cli/src/framework-configs.ts | 39 +- cli/src/index.ts | 119 ++---- cli/src/ios/add.ts | 12 +- cli/src/ios/build.ts | 17 +- cli/src/ios/common.ts | 28 +- cli/src/ios/doctor.ts | 6 +- cli/src/ios/run.ts | 26 +- cli/src/ios/update.ts | 278 +++--------- cli/src/ipc.ts | 21 +- cli/src/log.ts | 9 +- cli/src/plugin.ts | 66 +-- cli/src/tasks/add.ts | 50 +-- cli/src/tasks/build.ts | 36 +- cli/src/tasks/config.ts | 16 +- cli/src/tasks/copy.ts | 167 ++------ cli/src/tasks/create.ts | 5 +- cli/src/tasks/doctor.ts | 49 +-- cli/src/tasks/init.ts | 64 +-- cli/src/tasks/list.ts | 21 +- cli/src/tasks/migrate.ts | 338 ++++----------- cli/src/tasks/new-plugin.ts | 5 +- cli/src/tasks/open.ts | 24 +- cli/src/tasks/run.ts | 49 +-- cli/src/tasks/sourcemaps.ts | 19 +- cli/src/tasks/sync.ts | 42 +- cli/src/tasks/telemetry.ts | 10 +- cli/src/tasks/update.ts | 45 +- cli/src/telemetry.ts | 30 +- cli/src/util/fn.ts | 5 +- cli/src/util/fs.ts | 10 +- cli/src/util/iosplugin.ts | 29 +- cli/src/util/livereload.ts | 32 +- cli/src/util/monorepotools.ts | 8 +- cli/src/util/native-run.ts | 15 +- cli/src/util/node.ts | 10 +- cli/src/util/promise.ts | 22 +- cli/src/util/spm.ts | 23 +- cli/src/util/subprocess.ts | 8 +- cli/src/util/term.ts | 9 +- cli/src/util/uuid.ts | 2 +- cli/src/util/xml.ts | 7 +- cli/test/add.android.spec.ts | 146 +++---- cli/test/add.ios.spec.ts | 15 +- cli/test/framework-detection.spec.ts | 3 +- cli/test/update.android.spec.ts | 67 ++- cli/test/update.ios.spec.ts | 16 +- cli/test/util.ts | 46 +- core/cordova.js | 196 ++------- core/native-bridge.ts | 278 ++++-------- core/rollup.bridge.config.js | 2 +- core/src/core-plugins.ts | 95 ++--- core/src/definitions-internal.ts | 41 +- core/src/definitions.ts | 40 +- core/src/global.ts | 15 +- core/src/index.ts | 7 +- core/src/legacy/legacy-web-plugin-merge.ts | 9 +- core/src/platforms.ts | 20 +- core/src/runtime.ts | 90 ++-- core/src/tests/bridge.spec.ts | 22 +- core/src/tests/build-treeshaking.js | 6 +- core/src/tests/convert-file-src.spec.ts | 17 +- core/src/tests/events.spec.ts | 5 +- core/src/tests/legacy.spec.ts | 4 +- core/src/tests/plugin.spec.ts | 25 +- core/src/tests/runtime.spec.ts | 5 +- core/src/tests/web-plugin.spec.ts | 5 +- core/src/util.ts | 4 +- core/src/web-plugin.ts | 27 +- package.json | 22 +- scripts/lib/cli.mjs | 4 +- scripts/lib/fn.mjs | 4 +- scripts/lib/fs.mjs | 2 +- scripts/lib/git.mjs | 6 +- scripts/lib/lerna.mjs | 6 +- scripts/lib/repo.mjs | 5 +- scripts/lib/subprocess.mjs | 6 +- scripts/lib/version.mjs | 6 +- scripts/sync-peer-dependencies.mjs | 14 +- swiftlint.config.js | 12 +- 101 files changed, 1280 insertions(+), 3437 deletions(-) delete mode 100644 .eslintrc.js diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 4cdd1d9a3..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,44 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint', 'import'], - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'prettier', - 'plugin:import/typescript', - ], - rules: { - // https://eslint.org/docs/rules/ - 'no-fallthrough': 'off', // https://github.com/ionic-team/eslint-config/issues/7 - 'no-constant-condition': 'off', - - // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin/docs/rules - '@typescript-eslint/no-this-alias': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/explicit-module-boundary-types': [ - 'error', - { allowArgumentsExplicitlyTypedAsAny: true }, - ], - - // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin/docs/rules - '@typescript-eslint/array-type': 'error', - '@typescript-eslint/consistent-type-assertions': 'error', - '@typescript-eslint/consistent-type-imports': 'error', - '@typescript-eslint/prefer-for-of': 'error', - '@typescript-eslint/prefer-optional-chain': 'error', - - // https://github.com/benmosher/eslint-plugin-import - 'import/first': 'error', - 'import/order': [ - 'error', - { - 'alphabetize': { order: 'asc', caseInsensitive: false }, - 'groups': [['builtin', 'external'], 'parent', ['sibling', 'index']], - 'newlines-between': 'always', - }, - ], - 'import/newline-after-import': 'error', - 'import/no-duplicates': 'error', - 'import/no-mutable-exports': 'error', - }, -}; diff --git a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java index d08a00d99..dd623ae65 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java +++ b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java @@ -1024,8 +1024,13 @@ public void restoreInstanceState(Bundle savedInstanceState) { try { JSObject options = new JSObject(lastOptionsJson); - pluginCallForLastActivity = - new PluginCall(msgHandler, lastPluginId, PluginCall.CALLBACK_ID_DANGLING, lastPluginCallMethod, options); + pluginCallForLastActivity = new PluginCall( + msgHandler, + lastPluginId, + PluginCall.CALLBACK_ID_DANGLING, + lastPluginCallMethod, + options + ); } catch (JSONException ex) { Logger.error("Unable to restore plugin call, unable to parse persisted JSON object", ex); } diff --git a/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java b/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java index f269bd561..eae2fcc4f 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java +++ b/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java @@ -77,13 +77,12 @@ protected void load(Bundle savedInstanceState) { startDir = getArguments().getString(ARG_START_DIR); } - bridge = - new Bridge.Builder(this) - .setInstanceState(savedInstanceState) - .setPlugins(initialPlugins) - .setConfig(config) - .addWebViewListeners(webViewListeners) - .create(); + bridge = new Bridge.Builder(this) + .setInstanceState(savedInstanceState) + .setPlugins(initialPlugins) + .setConfig(config) + .addWebViewListeners(webViewListeners) + .create(); if (startDir != null) { bridge.setServerAssetPath(startDir); diff --git a/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java b/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java index 469d58dc3..3afa8d3d1 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java +++ b/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java @@ -67,15 +67,11 @@ public BridgeWebChromeClient(Bridge bridge) { }; permissionLauncher = bridge.registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissionCallback); - activityLauncher = - bridge.registerForActivityResult( - new ActivityResultContracts.StartActivityForResult(), - result -> { - if (activityListener != null) { - activityListener.onActivityResult(result); - } - } - ); + activityLauncher = bridge.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { + if (activityListener != null) { + activityListener.onActivityResult(result); + } + }); } /** @@ -114,14 +110,13 @@ public void onPermissionRequest(final PermissionRequest request) { } if (!permissionList.isEmpty()) { String[] permissions = permissionList.toArray(new String[0]); - permissionListener = - isGranted -> { - if (isGranted) { - request.grant(request.getResources()); - } else { - request.deny(); - } - }; + permissionListener = isGranted -> { + if (isGranted) { + request.grant(request.getResources()); + } else { + request.deny(); + } + }; permissionLauncher.launch(permissions); } else { request.grant(request.getResources()); @@ -145,19 +140,14 @@ public boolean onJsAlert(WebView view, String url, String message, final JsResul AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); builder .setMessage(message) - .setPositiveButton( - "OK", - (dialog, buttonIndex) -> { - dialog.dismiss(); - result.confirm(); - } - ) - .setOnCancelListener( - dialog -> { - dialog.dismiss(); - result.cancel(); - } - ); + .setPositiveButton("OK", (dialog, buttonIndex) -> { + dialog.dismiss(); + result.confirm(); + }) + .setOnCancelListener(dialog -> { + dialog.dismiss(); + result.cancel(); + }); AlertDialog dialog = builder.create(); @@ -184,26 +174,18 @@ public boolean onJsConfirm(WebView view, String url, String message, final JsRes builder .setMessage(message) - .setPositiveButton( - "OK", - (dialog, buttonIndex) -> { - dialog.dismiss(); - result.confirm(); - } - ) - .setNegativeButton( - "Cancel", - (dialog, buttonIndex) -> { - dialog.dismiss(); - result.cancel(); - } - ) - .setOnCancelListener( - dialog -> { - dialog.dismiss(); - result.cancel(); - } - ); + .setPositiveButton("OK", (dialog, buttonIndex) -> { + dialog.dismiss(); + result.confirm(); + }) + .setNegativeButton("Cancel", (dialog, buttonIndex) -> { + dialog.dismiss(); + result.cancel(); + }) + .setOnCancelListener(dialog -> { + dialog.dismiss(); + result.cancel(); + }); AlertDialog dialog = builder.create(); @@ -233,28 +215,20 @@ public boolean onJsPrompt(WebView view, String url, String message, String defau builder .setMessage(message) .setView(input) - .setPositiveButton( - "OK", - (dialog, buttonIndex) -> { - dialog.dismiss(); - - String inputText1 = input.getText().toString().trim(); - result.confirm(inputText1); - } - ) - .setNegativeButton( - "Cancel", - (dialog, buttonIndex) -> { - dialog.dismiss(); - result.cancel(); - } - ) - .setOnCancelListener( - dialog -> { - dialog.dismiss(); - result.cancel(); - } - ); + .setPositiveButton("OK", (dialog, buttonIndex) -> { + dialog.dismiss(); + + String inputText1 = input.getText().toString().trim(); + result.confirm(inputText1); + }) + .setNegativeButton("Cancel", (dialog, buttonIndex) -> { + dialog.dismiss(); + result.cancel(); + }) + .setOnCancelListener(dialog -> { + dialog.dismiss(); + result.cancel(); + }); AlertDialog dialog = builder.create(); @@ -275,22 +249,21 @@ public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermiss final String[] geoPermissions = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }; if (!PermissionHelper.hasPermissions(bridge.getContext(), geoPermissions)) { - permissionListener = - isGranted -> { - if (isGranted) { + permissionListener = isGranted -> { + if (isGranted) { + callback.invoke(origin, true, false); + } else { + final String[] coarsePermission = { Manifest.permission.ACCESS_COARSE_LOCATION }; + if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && + PermissionHelper.hasPermissions(bridge.getContext(), coarsePermission) + ) { callback.invoke(origin, true, false); } else { - final String[] coarsePermission = { Manifest.permission.ACCESS_COARSE_LOCATION }; - if ( - Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && - PermissionHelper.hasPermissions(bridge.getContext(), coarsePermission) - ) { - callback.invoke(origin, true, false); - } else { - callback.invoke(origin, false, false); - } + callback.invoke(origin, false, false); } - }; + } + }; permissionLauncher.launch(geoPermissions); } else { // permission is already granted @@ -313,15 +286,14 @@ public boolean onShowFileChooser( if (isMediaCaptureSupported()) { showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo); } else { - permissionListener = - isGranted -> { - if (isGranted) { - showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo); - } else { - Logger.warn(Logger.tags("FileChooser"), "Camera permission not granted"); - filePathCallback.onReceiveValue(null); - } - }; + permissionListener = isGranted -> { + if (isGranted) { + showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo); + } else { + Logger.warn(Logger.tags("FileChooser"), "Camera permission not granted"); + filePathCallback.onReceiveValue(null); + } + }; final String[] camPermission = { Manifest.permission.CAMERA }; permissionLauncher.launch(camPermission); } @@ -373,14 +345,13 @@ private boolean showImageCapturePicker(final ValueCallback filePathCallba return false; } takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); - activityListener = - activityResult -> { - Uri[] result = null; - if (activityResult.getResultCode() == Activity.RESULT_OK) { - result = new Uri[] { imageFileUri }; - } - filePathCallback.onReceiveValue(result); - }; + activityListener = activityResult -> { + Uri[] result = null; + if (activityResult.getResultCode() == Activity.RESULT_OK) { + result = new Uri[] { imageFileUri }; + } + filePathCallback.onReceiveValue(result); + }; activityLauncher.launch(takePictureIntent); return true; @@ -393,14 +364,13 @@ private boolean showVideoCapturePicker(final ValueCallback filePathCallba return false; } - activityListener = - activityResult -> { - Uri[] result = null; - if (activityResult.getResultCode() == Activity.RESULT_OK) { - result = new Uri[] { activityResult.getData().getData() }; - } - filePathCallback.onReceiveValue(result); - }; + activityListener = activityResult -> { + Uri[] result = null; + if (activityResult.getResultCode() == Activity.RESULT_OK) { + result = new Uri[] { activityResult.getData().getData() }; + } + filePathCallback.onReceiveValue(result); + }; activityLauncher.launch(takeVideoIntent); return true; @@ -419,21 +389,20 @@ private void showFilePicker(final ValueCallback filePathCallback, FileCho } } try { - activityListener = - activityResult -> { - Uri[] result; - Intent resultIntent = activityResult.getData(); - if (activityResult.getResultCode() == Activity.RESULT_OK && resultIntent.getClipData() != null) { - final int numFiles = resultIntent.getClipData().getItemCount(); - result = new Uri[numFiles]; - for (int i = 0; i < numFiles; i++) { - result[i] = resultIntent.getClipData().getItemAt(i).getUri(); - } - } else { - result = WebChromeClient.FileChooserParams.parseResult(activityResult.getResultCode(), resultIntent); + activityListener = activityResult -> { + Uri[] result; + Intent resultIntent = activityResult.getData(); + if (activityResult.getResultCode() == Activity.RESULT_OK && resultIntent.getClipData() != null) { + final int numFiles = resultIntent.getClipData().getItemCount(); + result = new Uri[numFiles]; + for (int i = 0; i < numFiles; i++) { + result[i] = resultIntent.getClipData().getItemAt(i).getUri(); } - filePathCallback.onReceiveValue(result); - }; + } else { + result = WebChromeClient.FileChooserParams.parseResult(activityResult.getResultCode(), resultIntent); + } + filePathCallback.onReceiveValue(result); + }; activityLauncher.launch(intent); } catch (ActivityNotFoundException e) { filePathCallback.onReceiveValue(null); diff --git a/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java b/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java index 286453401..c621a9b69 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java +++ b/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java @@ -256,18 +256,26 @@ private void deserializeConfig(@Nullable Context context) { allowNavigation = JSONUtils.getArray(configJSON, "server.allowNavigation", null); // Android - overriddenUserAgentString = - JSONUtils.getString(configJSON, "android.overrideUserAgent", JSONUtils.getString(configJSON, "overrideUserAgent", null)); - appendedUserAgentString = - JSONUtils.getString(configJSON, "android.appendUserAgent", JSONUtils.getString(configJSON, "appendUserAgent", null)); - backgroundColor = - JSONUtils.getString(configJSON, "android.backgroundColor", JSONUtils.getString(configJSON, "backgroundColor", null)); - allowMixedContent = - JSONUtils.getBoolean( - configJSON, - "android.allowMixedContent", - JSONUtils.getBoolean(configJSON, "allowMixedContent", allowMixedContent) - ); + overriddenUserAgentString = JSONUtils.getString( + configJSON, + "android.overrideUserAgent", + JSONUtils.getString(configJSON, "overrideUserAgent", null) + ); + appendedUserAgentString = JSONUtils.getString( + configJSON, + "android.appendUserAgent", + JSONUtils.getString(configJSON, "appendUserAgent", null) + ); + backgroundColor = JSONUtils.getString( + configJSON, + "android.backgroundColor", + JSONUtils.getString(configJSON, "backgroundColor", null) + ); + allowMixedContent = JSONUtils.getBoolean( + configJSON, + "android.allowMixedContent", + JSONUtils.getBoolean(configJSON, "allowMixedContent", allowMixedContent) + ); minWebViewVersion = JSONUtils.getInt(configJSON, "android.minWebViewVersion", DEFAULT_ANDROID_WEBVIEW_VERSION); minHuaweiWebViewVersion = JSONUtils.getInt(configJSON, "android.minHuaweiWebViewVersion", DEFAULT_HUAWEI_WEBVIEW_VERSION); captureInput = JSONUtils.getBoolean(configJSON, "android.captureInput", captureInput); diff --git a/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java b/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java index b71124e83..ceab19032 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java +++ b/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java @@ -150,10 +150,8 @@ private void callPluginMethod(String callbackId, String pluginId, String methodN } private void callCordovaPluginMethod(String callbackId, String service, String action, String actionArgs) { - bridge.execute( - () -> { - cordovaPluginManager.exec(service, action, callbackId, actionArgs); - } - ); + bridge.execute(() -> { + cordovaPluginManager.exec(service, action, callbackId, actionArgs); + }); } } diff --git a/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java b/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java index 715a0a0b3..443277846 100755 --- a/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java +++ b/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java @@ -77,7 +77,9 @@ public void addURI(String scheme, String authority, String path, Object code) { UriMatcher node = this; for (int i = -2; i < numTokens; i++) { String token; - if (i == -2) token = scheme; else if (i == -1) token = authority; else token = tokens[i]; + if (i == -2) token = scheme; + else if (i == -1) token = authority; + else token = tokens[i]; ArrayList children = node.mChildren; int numChildren = children.size(); UriMatcher child; @@ -130,7 +132,9 @@ public Object match(Uri uri) { for (int i = -2; i < li; i++) { String u; - if (i == -2) u = uri.getScheme(); else if (i == -1) u = uri.getAuthority(); else u = pathSegments.get(i); + if (i == -2) u = uri.getScheme(); + else if (i == -1) u = uri.getAuthority(); + else u = pathSegments.get(i); ArrayList list = node.mChildren; if (list == null) { break; diff --git a/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java b/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java index d5b77cddb..7e07a8db2 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java +++ b/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java @@ -72,14 +72,12 @@ public CapacitorEvalBridgeMode(WebView webView, CordovaInterface cordova) { public void onNativeToJsMessageAvailable(final NativeToJsMessageQueue queue) { cordova .getActivity() - .runOnUiThread( - () -> { - String js = queue.popAndEncodeAsJs(); - if (js != null) { - webView.evaluateJavascript(js, null); - } + .runOnUiThread(() -> { + String js = queue.popAndEncodeAsJs(); + if (js != null) { + webView.evaluateJavascript(js, null); } - ); + }); } } diff --git a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java index 64f97d87a..7ffd56e99 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java +++ b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java @@ -46,34 +46,31 @@ public void setCookie(String domain, String action) { @PluginMethod public void getCookies(PluginCall call) { - this.bridge.eval( - "document.cookie", - value -> { - String cookies = value.substring(1, value.length() - 1); - String[] cookieArray = cookies.split(";"); - - JSObject cookieMap = new JSObject(); - - for (String cookie : cookieArray) { - if (cookie.length() > 0) { - String[] keyValue = cookie.split("=", 2); - - if (keyValue.length == 2) { - String key = keyValue[0].trim(); - String val = keyValue[1].trim(); - try { - key = URLDecoder.decode(keyValue[0].trim(), StandardCharsets.UTF_8.name()); - val = URLDecoder.decode(keyValue[1].trim(), StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException ignored) {} - - cookieMap.put(key, val); - } + this.bridge.eval("document.cookie", value -> { + String cookies = value.substring(1, value.length() - 1); + String[] cookieArray = cookies.split(";"); + + JSObject cookieMap = new JSObject(); + + for (String cookie : cookieArray) { + if (cookie.length() > 0) { + String[] keyValue = cookie.split("=", 2); + + if (keyValue.length == 2) { + String key = keyValue[0].trim(); + String val = keyValue[1].trim(); + try { + key = URLDecoder.decode(keyValue[0].trim(), StandardCharsets.UTF_8.name()); + val = URLDecoder.decode(keyValue[1].trim(), StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException ignored) {} + + cookieMap.put(key, val); } } - - call.resolve(cookieMap); } - ); + + call.resolve(cookieMap); + }); } @PluginMethod diff --git a/android/capacitor/src/test/java/com/getcapacitor/ConfigBuildingTest.java b/android/capacitor/src/test/java/com/getcapacitor/ConfigBuildingTest.java index d972e0daa..0a21c144a 100644 --- a/android/capacitor/src/test/java/com/getcapacitor/ConfigBuildingTest.java +++ b/android/capacitor/src/test/java/com/getcapacitor/ConfigBuildingTest.java @@ -40,22 +40,21 @@ public void setup() { pluginConfig.put(TEST_PLUGIN_NAME, testPluginObject); - config = - new CapConfig.Builder(context) - .setAllowMixedContent(true) - .setAllowNavigation(new String[] { "http://www.google.com" }) - .setAndroidScheme("test") - .setCaptureInput(true) - .setLoggingEnabled(true) - .setHTML5mode(false) - .setOverriddenUserAgentString("test-user-agent") - .setAppendedUserAgentString("test-append") - .setWebContentsDebuggingEnabled(true) - .setZoomableWebView(false) - .setBackgroundColor("red") - .setPluginsConfiguration(pluginConfig) - .setServerUrl("http://www.google.com") - .create(); + config = new CapConfig.Builder(context) + .setAllowMixedContent(true) + .setAllowNavigation(new String[] { "http://www.google.com" }) + .setAndroidScheme("test") + .setCaptureInput(true) + .setLoggingEnabled(true) + .setHTML5mode(false) + .setOverriddenUserAgentString("test-user-agent") + .setAppendedUserAgentString("test-append") + .setWebContentsDebuggingEnabled(true) + .setZoomableWebView(false) + .setBackgroundColor("red") + .setPluginsConfiguration(pluginConfig) + .setServerUrl("http://www.google.com") + .create(); } catch (Exception e) { fail(); } diff --git a/android/capacitor/src/test/java/com/getcapacitor/plugin/util/HttpRequestHandlerTest.java b/android/capacitor/src/test/java/com/getcapacitor/plugin/util/HttpRequestHandlerTest.java index f7c492471..2d5f15155 100644 --- a/android/capacitor/src/test/java/com/getcapacitor/plugin/util/HttpRequestHandlerTest.java +++ b/android/capacitor/src/test/java/com/getcapacitor/plugin/util/HttpRequestHandlerTest.java @@ -10,9 +10,10 @@ public class HttpRequestHandlerTest { static final String BASE_URL = "https://httpbin.org/get"; - static final String PARAMS_JSON = """ - {"k": "a&b"} - """; + static final String PARAMS_JSON = + """ + {"k": "a&b"} + """; @Test public void testHttpURLConnectionBuilderSetUrlParamsEncoded() throws Exception { diff --git a/cli/src/android/add.ts b/cli/src/android/add.ts index e4f88f7dd..d4a85960e 100644 --- a/cli/src/android/add.ts +++ b/cli/src/android/add.ts @@ -9,20 +9,12 @@ import { runCommand } from '../util/subprocess'; import { extractTemplate } from '../util/template'; export async function addAndroid(config: Config): Promise { - await runTask( - `Adding native android project in ${c.strong(config.android.platformDir)}`, - async () => { - return extractTemplate( - config.cli.assets.android.platformTemplateArchiveAbs, - config.android.platformDirAbs, - ); - }, - ); + await runTask(`Adding native android project in ${c.strong(config.android.platformDir)}`, async () => { + return extractTemplate(config.cli.assets.android.platformTemplateArchiveAbs, config.android.platformDirAbs); + }); } -export async function createLocalProperties( - platformDir: string, -): Promise { +export async function createLocalProperties(platformDir: string): Promise { const defaultAndroidPath = join(homedir(), 'Library/Android/sdk'); if (await pathExists(defaultAndroidPath)) { const localSettings = ` diff --git a/cli/src/android/build.ts b/cli/src/android/build.ts index 010ef931c..f5b31a211 100644 --- a/cli/src/android/build.ts +++ b/cli/src/android/build.ts @@ -7,16 +7,11 @@ import { logSuccess } from '../log'; import type { BuildCommandOptions } from '../tasks/build'; import { runCommand } from '../util/subprocess'; -export async function buildAndroid( - config: Config, - buildOptions: BuildCommandOptions, -): Promise { +export async function buildAndroid(config: Config, buildOptions: BuildCommandOptions): Promise { const releaseType = buildOptions.androidreleasetype ?? 'AAB'; const releaseTypeIsAAB = releaseType === 'AAB'; const flavor = buildOptions.flavor ?? ''; - const arg = releaseTypeIsAAB - ? `:app:bundle${flavor}Release` - : `assemble${flavor}Release`; + const arg = releaseTypeIsAAB ? `:app:bundle${flavor}Release` : `assemble${flavor}Release`; const gradleArgs = [arg]; try { @@ -40,8 +35,8 @@ export async function buildAndroid( ? `${flavor}Release` : 'release' : flavor !== '' - ? join(flavor, 'release') - : 'release'; + ? join(flavor, 'release') + : 'release'; const releasePath = join( config.android.appDirAbs, @@ -56,28 +51,14 @@ export async function buildAndroid( }.${releaseType.toLowerCase()}`; const signedReleaseName = unsignedReleaseName.replace( - `-release${ - releaseTypeIsAAB ? '' : '-unsigned' - }.${releaseType.toLowerCase()}`, + `-release${releaseTypeIsAAB ? '' : '-unsigned'}.${releaseType.toLowerCase()}`, `-release-signed.${releaseType.toLowerCase()}`, ); if (buildOptions.signingtype == 'jarsigner') { - await signWithJarSigner( - config, - buildOptions, - releasePath, - signedReleaseName, - unsignedReleaseName, - ); + await signWithJarSigner(config, buildOptions, releasePath, signedReleaseName, unsignedReleaseName); } else { - await signWithApkSigner( - config, - buildOptions, - releasePath, - signedReleaseName, - unsignedReleaseName, - ); + await signWithApkSigner(config, buildOptions, releasePath, signedReleaseName, unsignedReleaseName); } logSuccess(`Successfully generated ${signedReleaseName} at: ${releasePath}`); diff --git a/cli/src/android/common.ts b/cli/src/android/common.ts index 18d01320d..41aef222d 100644 --- a/cli/src/android/common.ts +++ b/cli/src/android/common.ts @@ -1,11 +1,4 @@ -import { - copy, - remove, - mkdirp, - readFile, - pathExists, - writeFile, -} from '@ionic/utils-fs'; +import { copy, remove, mkdirp, readFile, pathExists, writeFile } from '@ionic/utils-fs'; import { join, resolve } from 'path'; import { checkCapacitorPlatform } from '../common'; @@ -15,27 +8,19 @@ import { PluginType, getPluginPlatform } from '../plugin'; import type { Plugin } from '../plugin'; import { convertToUnixPath } from '../util/fs'; -export async function checkAndroidPackage( - config: Config, -): Promise { +export async function checkAndroidPackage(config: Config): Promise { return checkCapacitorPlatform(config, 'android'); } -export async function getAndroidPlugins( - allPlugins: Plugin[], -): Promise { - const resolved = await Promise.all( - allPlugins.map(async plugin => await resolvePlugin(plugin)), - ); +export async function getAndroidPlugins(allPlugins: Plugin[]): Promise { + const resolved = await Promise.all(allPlugins.map(async (plugin) => await resolvePlugin(plugin))); return resolved.filter((plugin): plugin is Plugin => !!plugin); } export async function resolvePlugin(plugin: Plugin): Promise { const platform = 'android'; if (plugin.manifest?.android) { - let pluginFilesPath = plugin.manifest.android.src - ? plugin.manifest.android.src - : platform; + let pluginFilesPath = plugin.manifest.android.src ? plugin.manifest.android.src : platform; const absolutePath = join(plugin.rootPath, pluginFilesPath, plugin.id); // Android folder shouldn't have subfolders, but they used to, so search for them for compatibility reasons if (await pathExists(absolutePath)) { @@ -50,10 +35,7 @@ export async function resolvePlugin(plugin: Plugin): Promise { type: PluginType.Cordova, path: 'src/' + platform, }; - if ( - getIncompatibleCordovaPlugins(platform).includes(plugin.id) || - !getPluginPlatform(plugin, platform) - ) { + if (getIncompatibleCordovaPlugins(platform).includes(plugin.id) || !getPluginPlatform(plugin, platform)) { plugin.android.type = PluginType.Incompatible; } } else { @@ -67,9 +49,7 @@ export async function resolvePlugin(plugin: Plugin): Promise { * This is a little trickier for Android because the appId becomes * the package name. */ -export async function editProjectSettingsAndroid( - config: Config, -): Promise { +export async function editProjectSettingsAndroid(config: Config): Promise { const appId = config.app.appId; const appName = config.app.appName .replace(/&/g, '&') @@ -81,27 +61,19 @@ export async function editProjectSettingsAndroid( const domainPath = appId.split('.').join('/'); // Make the package source path to the new plugin Java file - const newJavaPath = resolve( - config.android.srcMainDirAbs, - `java/${domainPath}`, - ); + const newJavaPath = resolve(config.android.srcMainDirAbs, `java/${domainPath}`); if (!(await pathExists(newJavaPath))) { await mkdirp(newJavaPath); } await copy( - resolve( - config.android.srcMainDirAbs, - 'java/com/getcapacitor/myapp/MainActivity.java', - ), + resolve(config.android.srcMainDirAbs, 'java/com/getcapacitor/myapp/MainActivity.java'), resolve(newJavaPath, 'MainActivity.java'), ); if (appId.split('.')[1] !== 'getcapacitor') { - await remove( - resolve(config.android.srcMainDirAbs, 'java/com/getcapacitor'), - ); + await remove(resolve(config.android.srcMainDirAbs, 'java/com/getcapacitor')); } // Remove our template 'com' folder if their ID doesn't have it @@ -113,23 +85,14 @@ export async function editProjectSettingsAndroid( const activityPath = resolve(newJavaPath, 'MainActivity.java'); let activityContent = await readFile(activityPath, { encoding: 'utf-8' }); - activityContent = activityContent.replace( - /package ([^;]*)/, - `package ${appId}`, - ); + activityContent = activityContent.replace(/package ([^;]*)/, `package ${appId}`); await writeFile(activityPath, activityContent, { encoding: 'utf-8' }); // Update the applicationId in build.gradle let gradleContent = await readFile(buildGradlePath, { encoding: 'utf-8' }); - gradleContent = gradleContent.replace( - /applicationId "[^"]+"/, - `applicationId "${appId}"`, - ); + gradleContent = gradleContent.replace(/applicationId "[^"]+"/, `applicationId "${appId}"`); // Update the namespace in build.gradle - gradleContent = gradleContent.replace( - /namespace "[^"]+"/, - `namespace "${appId}"`, - ); + gradleContent = gradleContent.replace(/namespace "[^"]+"/, `namespace "${appId}"`); await writeFile(buildGradlePath, gradleContent, { encoding: 'utf-8' }); diff --git a/cli/src/android/doctor.ts b/cli/src/android/doctor.ts index 652583bb5..2ea3fe7d2 100644 --- a/cli/src/android/doctor.ts +++ b/cli/src/android/doctor.ts @@ -10,11 +10,7 @@ import { readXML } from '../util/xml'; export async function doctorAndroid(config: Config): Promise { try { - await check([ - checkAndroidInstalled, - () => checkGradlew(config), - () => checkAppSrcDirs(config), - ]); + await check([checkAndroidInstalled, () => checkGradlew(config), () => checkAppSrcDirs(config)]); logSuccess('Android looking great! ๐Ÿ‘Œ'); } catch (e: any) { if (!isFatal(e)) { @@ -27,52 +23,35 @@ export async function doctorAndroid(config: Config): Promise { async function checkAppSrcDirs(config: Config): Promise { if (!(await pathExists(config.android.appDirAbs))) { - return `${c.strong( - config.android.appDir, - )} directory is missing in ${c.strong(config.android.platformDir)}`; + return `${c.strong(config.android.appDir)} directory is missing in ${c.strong(config.android.platformDir)}`; } if (!(await pathExists(config.android.srcMainDirAbs))) { - return `${c.strong( - config.android.srcMainDir, - )} directory is missing in ${c.strong(config.android.platformDir)}`; + return `${c.strong(config.android.srcMainDir)} directory is missing in ${c.strong(config.android.platformDir)}`; } if (!(await pathExists(config.android.assetsDirAbs))) { - return `${c.strong( - config.android.assetsDir, - )} directory is missing in ${c.strong(config.android.platformDir)}`; + return `${c.strong(config.android.assetsDir)} directory is missing in ${c.strong(config.android.platformDir)}`; } if (!(await pathExists(config.android.webDirAbs))) { - return `${c.strong( - config.android.webDir, - )} directory is missing in ${c.strong(config.android.platformDir)}`; + return `${c.strong(config.android.webDir)} directory is missing in ${c.strong(config.android.platformDir)}`; } - const appSrcMainAssetsWwwIndexHtmlDir = join( - config.android.webDirAbs, - 'index.html', - ); + const appSrcMainAssetsWwwIndexHtmlDir = join(config.android.webDirAbs, 'index.html'); if (!(await pathExists(appSrcMainAssetsWwwIndexHtmlDir))) { - return `${c.strong('index.html')} file is missing in ${c.strong( - config.android.webDirAbs, - )}`; + return `${c.strong('index.html')} file is missing in ${c.strong(config.android.webDirAbs)}`; } return checkAndroidManifestFile(config); } -async function checkAndroidManifestFile( - config: Config, -): Promise { +async function checkAndroidManifestFile(config: Config): Promise { const manifestFileName = 'AndroidManifest.xml'; const manifestFilePath = join(config.android.srcMainDirAbs, manifestFileName); if (!(await pathExists(manifestFilePath))) { - return `${c.strong(manifestFileName)} is missing in ${c.strong( - config.android.srcMainDir, - )}`; + return `${c.strong(manifestFileName)} is missing in ${c.strong(config.android.srcMainDir)}`; } try { @@ -83,87 +62,73 @@ async function checkAndroidManifestFile( } } -async function checkAndroidManifestData( - config: Config, - xmlData: any, -): Promise { +async function checkAndroidManifestData(config: Config, xmlData: any): Promise { const manifestNode: any = xmlData.manifest; if (!manifestNode) { - return `Missing ${c.input('')} XML node in ${c.strong( - config.android.srcMainDir, - )}`; + return `Missing ${c.input('')} XML node in ${c.strong(config.android.srcMainDir)}`; } const applicationChildNodes: any[] = manifestNode.application; if (!Array.isArray(manifestNode.application)) { - return `Missing ${c.input( - '', - )} XML node as a child node of ${c.input('')} in ${c.strong( + return `Missing ${c.input('')} XML node as a child node of ${c.input('')} in ${c.strong( config.android.srcMainDir, )}`; } let mainActivityClassPath = ''; - const mainApplicationNode = applicationChildNodes.find( - applicationChildNode => { - const activityChildNodes: any[] = applicationChildNode.activity; - if (!Array.isArray(activityChildNodes)) { + const mainApplicationNode = applicationChildNodes.find((applicationChildNode) => { + const activityChildNodes: any[] = applicationChildNode.activity; + if (!Array.isArray(activityChildNodes)) { + return false; + } + + const mainActivityNode = activityChildNodes.find((activityChildNode) => { + const intentFilterChildNodes: any[] = activityChildNode['intent-filter']; + if (!Array.isArray(intentFilterChildNodes)) { return false; } - const mainActivityNode = activityChildNodes.find(activityChildNode => { - const intentFilterChildNodes: any[] = - activityChildNode['intent-filter']; - if (!Array.isArray(intentFilterChildNodes)) { + return intentFilterChildNodes.find((intentFilterChildNode) => { + const actionChildNodes: any[] = intentFilterChildNode.action; + if (!Array.isArray(actionChildNodes)) { + return false; + } + + const mainActionChildNode = actionChildNodes.find((actionChildNode) => { + const androidName = actionChildNode.$['android:name']; + return androidName === 'android.intent.action.MAIN'; + }); + + if (!mainActionChildNode) { + return false; + } + + const categoryChildNodes: any[] = intentFilterChildNode.category; + if (!Array.isArray(categoryChildNodes)) { return false; } - return intentFilterChildNodes.find(intentFilterChildNode => { - const actionChildNodes: any[] = intentFilterChildNode.action; - if (!Array.isArray(actionChildNodes)) { - return false; - } - - const mainActionChildNode = actionChildNodes.find(actionChildNode => { - const androidName = actionChildNode.$['android:name']; - return androidName === 'android.intent.action.MAIN'; - }); - - if (!mainActionChildNode) { - return false; - } - - const categoryChildNodes: any[] = intentFilterChildNode.category; - if (!Array.isArray(categoryChildNodes)) { - return false; - } - - return categoryChildNodes.find(categoryChildNode => { - const androidName = categoryChildNode.$['android:name']; - return androidName === 'android.intent.category.LAUNCHER'; - }); + return categoryChildNodes.find((categoryChildNode) => { + const androidName = categoryChildNode.$['android:name']; + return androidName === 'android.intent.category.LAUNCHER'; }); }); + }); - if (mainActivityNode) { - mainActivityClassPath = mainActivityNode.$['android:name']; - } + if (mainActivityNode) { + mainActivityClassPath = mainActivityNode.$['android:name']; + } - return mainActivityNode; - }, - ); + return mainActivityNode; + }); if (!mainApplicationNode) { - return `Missing main ${c.input('')} XML node in ${c.strong( - config.android.srcMainDir, - )}`; + return `Missing main ${c.input('')} XML node in ${c.strong(config.android.srcMainDir)}`; } if (!mainActivityClassPath) { - return `Missing ${c.input( - '', - )} attribute for MainActivity class in ${c.strong( + return `Missing ${c.input('')} attribute for MainActivity class in ${c.strong( config.android.srcMainDir, )}`; } @@ -174,15 +139,13 @@ async function checkAndroidManifestData( async function checkPackage(config: Config, mainActivityClassPath: string) { const appSrcMainJavaDir = join(config.android.srcMainDirAbs, 'java'); if (!(await pathExists(appSrcMainJavaDir))) { - return `${c.strong('java')} directory is missing in ${c.strong( - appSrcMainJavaDir, - )}`; + return `${c.strong('java')} directory is missing in ${c.strong(appSrcMainJavaDir)}`; } const mainActivityClassName: any = mainActivityClassPath.split('.').pop(); const srcFiles = await readdirp(appSrcMainJavaDir, { - filter: entry => + filter: (entry) => !entry.stats.isDirectory() && ['.java', '.kt'].includes(extname(entry.path)) && mainActivityClassName === parse(entry.path).name, @@ -200,9 +163,7 @@ async function checkBuildGradle(config: Config) { const filePath = join(config.android.appDirAbs, fileName); if (!(await pathExists(filePath))) { - return `${c.strong(fileName)} file is missing in ${c.strong( - config.android.appDir, - )}`; + return `${c.strong(fileName)} file is missing in ${c.strong(config.android.appDir)}`; } let fileContent = await readFile(filePath, { encoding: 'utf-8' }); @@ -212,9 +173,7 @@ async function checkBuildGradle(config: Config) { const searchFor = `applicationId`; if (fileContent.indexOf(searchFor) === -1) { - return `${c.strong('build.gradle')} file missing ${c.input( - `applicationId`, - )} config in ${filePath}`; + return `${c.strong('build.gradle')} file missing ${c.input(`applicationId`)} config in ${filePath}`; } return null; @@ -225,9 +184,7 @@ async function checkGradlew(config: Config) { const filePath = join(config.android.platformDirAbs, fileName); if (!(await pathExists(filePath))) { - return `${c.strong(fileName)} file is missing in ${c.strong( - config.android.platformDir, - )}`; + return `${c.strong(fileName)} file is missing in ${c.strong(config.android.platformDir)}`; } return null; } diff --git a/cli/src/android/open.ts b/cli/src/android/open.ts index d2083fc93..50bbed3b4 100644 --- a/cli/src/android/open.ts +++ b/cli/src/android/open.ts @@ -18,20 +18,14 @@ export async function openAndroid(config: Config): Promise { } await open(dir, { app: { name: androidStudioPath }, wait: false }); - logger.info( - `Opening Android project at: ${c.strong(config.android.platformDir)}.`, - ); + logger.info(`Opening Android project at: ${c.strong(config.android.platformDir)}.`); } catch (e) { debug('Error opening Android Studio: %O', e); logger.error( 'Unable to launch Android Studio. Is it installed?\n' + - `Attempted to open Android Studio at: ${c.strong( - androidStudioPath, - )}\n` + - `You can configure this with the ${c.input( - 'CAPACITOR_ANDROID_STUDIO_PATH', - )} environment variable.`, + `Attempted to open Android Studio at: ${c.strong(androidStudioPath)}\n` + + `You can configure this with the ${c.input('CAPACITOR_ANDROID_STUDIO_PATH')} environment variable.`, ); } } diff --git a/cli/src/android/run.ts b/cli/src/android/run.ts index 226a4259c..f93040ec3 100644 --- a/cli/src/android/run.ts +++ b/cli/src/android/run.ts @@ -2,11 +2,7 @@ import Debug from 'debug'; import { resolve } from 'path'; import c from '../colors'; -import { - parseApkNameFromFlavor, - promptForPlatformTarget, - runTask, -} from '../common'; +import { parseApkNameFromFlavor, promptForPlatformTarget, runTask } from '../common'; import type { Config } from '../definitions'; import type { RunCommandOptions } from '../tasks/run'; import { runNativeRun, getPlatformTargets } from '../util/native-run'; @@ -16,16 +12,9 @@ const debug = Debug('capacitor:android:run'); export async function runAndroid( config: Config, - { - target: selectedTarget, - flavor: selectedFlavor, - forwardPorts: selectedPorts, - }: RunCommandOptions, + { target: selectedTarget, flavor: selectedFlavor, forwardPorts: selectedPorts }: RunCommandOptions, ): Promise { - const target = await promptForPlatformTarget( - await getPlatformTargets('android'), - selectedTarget, - ); + const target = await promptForPlatformTarget(await getPlatformTargets('android'), selectedTarget); const runFlavor = selectedFlavor || config.android?.flavor || ''; @@ -65,8 +54,5 @@ export async function runAndroid( debug('Invoking native-run with args: %O', nativeRunArgs); - await runTask( - `Deploying ${c.strong(apkName)} to ${c.input(target.id)}`, - async () => runNativeRun(nativeRunArgs), - ); + await runTask(`Deploying ${c.strong(apkName)} to ${c.input(target.id)}`, async () => runNativeRun(nativeRunArgs)); } diff --git a/cli/src/android/update.ts b/cli/src/android/update.ts index 04cffab56..8e97adb3e 100644 --- a/cli/src/android/update.ts +++ b/cli/src/android/update.ts @@ -1,22 +1,10 @@ -import { - copy, - remove, - pathExists, - readdirp, - readFile, - writeFile, - writeJSON, -} from '@ionic/utils-fs'; +import { copy, remove, pathExists, readdirp, readFile, writeFile, writeJSON } from '@ionic/utils-fs'; import Debug from 'debug'; import { dirname, extname, join, relative, resolve } from 'path'; import c from '../colors'; import { checkPlatformVersions, runTask } from '../common'; -import { - checkPluginDependencies, - handleCordovaPluginsJS, - writeCordovaAndroidManifest, -} from '../cordova'; +import { checkPluginDependencies, handleCordovaPluginsJS, writeCordovaAndroidManifest } from '../cordova'; import type { Config } from '../definitions'; import { fatal } from '../errors'; import { @@ -44,17 +32,13 @@ const debug = Debug('capacitor:android:update'); export async function updateAndroid(config: Config): Promise { const plugins = await getPluginsTask(config); - const capacitorPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Core, - ); + const capacitorPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Core); printPlugins(capacitorPlugins, 'android'); await writePluginsJson(config, capacitorPlugins); await removePluginsNativeFiles(config); - const cordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Cordova, - ); + const cordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); await patchOldCapacitorPlugins(config); if (cordovaPlugins.length > 0) { await copyPluginsNativeFiles(config, cordovaPlugins); @@ -68,9 +52,7 @@ export async function updateAndroid(config: Config): Promise { await handleCordovaPluginsGradle(config, cordovaPlugins); await writeCordovaAndroidManifest(cordovaPlugins, config, platform); - const incompatibleCordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Incompatible, - ); + const incompatibleCordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Incompatible); printPlugins(incompatibleCordovaPlugins, platform, 'incompatible'); await checkPlatformVersions(config, platform); } @@ -84,22 +66,14 @@ interface PluginsJsonEntry { classpath: string; } -async function writePluginsJson( - config: Config, - plugins: Plugin[], -): Promise { +async function writePluginsJson(config: Config, plugins: Plugin[]): Promise { const classes = await findAndroidPluginClasses(plugins); - const pluginsJsonPath = resolve( - config.android.assetsDirAbs, - 'capacitor.plugins.json', - ); + const pluginsJsonPath = resolve(config.android.assetsDirAbs, 'capacitor.plugins.json'); await writeJSON(pluginsJsonPath, classes, { spaces: '\t' }); } -async function findAndroidPluginClasses( - plugins: Plugin[], -): Promise { +async function findAndroidPluginClasses(plugins: Plugin[]): Promise { const entries: PluginsJsonEntry[] = []; for (const plugin of plugins) { @@ -109,30 +83,20 @@ async function findAndroidPluginClasses( return entries; } -async function findAndroidPluginClassesInPlugin( - plugin: Plugin, -): Promise { +async function findAndroidPluginClassesInPlugin(plugin: Plugin): Promise { if (!plugin.android || getPluginType(plugin, platform) !== PluginType.Core) { return []; } const srcPath = resolve(plugin.rootPath, plugin.android.path, 'src/main'); const srcFiles = await readdirp(srcPath, { - filter: entry => - !entry.stats.isDirectory() && - ['.java', '.kt'].includes(extname(entry.path)), + filter: (entry) => !entry.stats.isDirectory() && ['.java', '.kt'].includes(extname(entry.path)), }); - const classRegex = - /^@(?:CapacitorPlugin|NativePlugin)[\s\S]+?class ([\w]+)/gm; + const classRegex = /^@(?:CapacitorPlugin|NativePlugin)[\s\S]+?class ([\w]+)/gm; const packageRegex = /^package ([\w.]+);?$/gm; - debug( - 'Searching %O source files in %O by %O regex', - srcFiles.length, - srcPath, - classRegex, - ); + debug('Searching %O source files in %O by %O regex', srcFiles.length, srcPath, classRegex); const entries = await Promise.all( srcFiles.map(async (srcFile): Promise => { @@ -146,15 +110,10 @@ async function findAndroidPluginClassesInPlugin( debug('Searching %O for package by %O regex', srcFile, packageRegex); packageRegex.lastIndex = 0; - const packageMatch = packageRegex.exec( - srcFileContents.substring(0, classMatch.index), - ); + const packageMatch = packageRegex.exec(srcFileContents.substring(0, classMatch.index)); if (!packageMatch) { - fatal( - `Package could not be parsed from Android plugin.\n` + - `Location: ${c.strong(srcFile)}`, - ); + fatal(`Package could not be parsed from Android plugin.\n` + `Location: ${c.strong(srcFile)}`); } const packageName = packageMatch[1]; @@ -178,11 +137,7 @@ export async function installGradlePlugins( capacitorPlugins: Plugin[], cordovaPlugins: Plugin[], ): Promise { - const capacitorAndroidPackagePath = resolveNode( - config.app.rootDir, - '@capacitor/android', - 'package.json', - ); + const capacitorAndroidPackagePath = resolveNode(config.app.rootDir, '@capacitor/android', 'package.json'); if (!capacitorAndroidPackagePath) { fatal( `Unable to find ${c.strong('node_modules/@capacitor/android')}.\n` + @@ -190,34 +145,25 @@ export async function installGradlePlugins( ); } - const capacitorAndroidPath = resolve( - dirname(capacitorAndroidPackagePath), - 'capacitor', - ); + const capacitorAndroidPath = resolve(dirname(capacitorAndroidPackagePath), 'capacitor'); const settingsPath = config.android.platformDirAbs; const dependencyPath = config.android.appDirAbs; - const relativeCapcitorAndroidPath = convertToUnixPath( - relative(settingsPath, capacitorAndroidPath), - ); + const relativeCapcitorAndroidPath = convertToUnixPath(relative(settingsPath, capacitorAndroidPath)); const settingsLines = `// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN include ':capacitor-android' project(':capacitor-android').projectDir = new File('${relativeCapcitorAndroidPath}') ${capacitorPlugins - .map(p => { + .map((p) => { if (!p.android) { return ''; } - const relativePluginPath = convertToUnixPath( - relative(settingsPath, p.rootPath), - ); + const relativePluginPath = convertToUnixPath(relative(settingsPath, p.rootPath)); return ` include ':${getGradlePackageName(p.id)}' -project(':${getGradlePackageName( - p.id, - )}').projectDir = new File('${relativePluginPath}/${p.android.path}') +project(':${getGradlePackageName(p.id)}').projectDir = new File('${relativePluginPath}/${p.android.path}') `; }) .join('')}`; @@ -225,10 +171,8 @@ project(':${getGradlePackageName( const applyArray: any[] = []; const frameworksArray: any[] = []; let prefsArray: any[] = []; - cordovaPlugins.map(p => { - const relativePluginPath = convertToUnixPath( - relative(dependencyPath, p.rootPath), - ); + cordovaPlugins.map((p) => { + const relativePluginPath = convertToUnixPath(relative(dependencyPath, p.rootPath)); const frameworks = getPlatformElement(p, platform, 'framework'); frameworks.map((framework: any) => { if ( @@ -237,9 +181,7 @@ project(':${getGradlePackageName( framework.$.type && framework.$.type === 'gradleReference' ) { - applyArray.push( - `apply from: "${relativePluginPath}/${framework.$.src}"`, - ); + applyArray.push(`apply from: "${relativePluginPath}/${framework.$.src}"`); } else if (!framework.$.type && !framework.$.custom) { if (framework.$.src.startsWith('platform(')) { frameworksArray.push(` implementation ${framework.$.src}`); @@ -251,11 +193,7 @@ project(':${getGradlePackageName( prefsArray = prefsArray.concat(getAllElements(p, platform, 'preference')); }); let frameworkString = frameworksArray.join('\n'); - frameworkString = await replaceFrameworkVariables( - config, - prefsArray, - frameworkString, - ); + frameworkString = await replaceFrameworkVariables(config, prefsArray, frameworkString); const dependencyLines = `// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN android { @@ -268,7 +206,7 @@ android { apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" dependencies { ${capacitorPlugins - .map(p => { + .map((p) => { return ` implementation project(':${getGradlePackageName(p.id)}')`; }) .join('\n')} @@ -281,36 +219,20 @@ if (hasProperty('postBuildExtras')) { } `; - await writeFile( - join(settingsPath, 'capacitor.settings.gradle'), - settingsLines, - ); - await writeFile( - join(dependencyPath, 'capacitor.build.gradle'), - dependencyLines, - ); + await writeFile(join(settingsPath, 'capacitor.settings.gradle'), settingsLines); + await writeFile(join(dependencyPath, 'capacitor.build.gradle'), dependencyLines); } -export async function handleCordovaPluginsGradle( - config: Config, - cordovaPlugins: Plugin[], -): Promise { - const pluginsGradlePath = join( - config.android.cordovaPluginsDirAbs, - 'build.gradle', - ); +export async function handleCordovaPluginsGradle(config: Config, cordovaPlugins: Plugin[]): Promise { + const pluginsGradlePath = join(config.android.cordovaPluginsDirAbs, 'build.gradle'); const kotlinNeeded = await kotlinNeededCheck(config, cordovaPlugins); - const kotlinVersionString = - config.app.extConfig.cordova?.preferences?.GradlePluginKotlinVersion ?? - '1.8.20'; + const kotlinVersionString = config.app.extConfig.cordova?.preferences?.GradlePluginKotlinVersion ?? '1.8.20'; const frameworksArray: any[] = []; let prefsArray: any[] = []; const applyArray: any[] = []; applyArray.push(`apply from: "cordova.variables.gradle"`); - cordovaPlugins.map(p => { - const relativePluginPath = convertToUnixPath( - relative(config.android.cordovaPluginsDirAbs, p.rootPath), - ); + cordovaPlugins.map((p) => { + const relativePluginPath = convertToUnixPath(relative(config.android.cordovaPluginsDirAbs, p.rootPath)); const frameworks = getPlatformElement(p, platform, 'framework'); frameworks.map((framework: any) => { if (!framework.$.type && !framework.$.custom) { @@ -321,15 +243,13 @@ export async function handleCordovaPluginsGradle( framework.$.type && framework.$.type === 'gradleReference' ) { - applyArray.push( - `apply from: "${relativePluginPath}/${framework.$.src}"`, - ); + applyArray.push(`apply from: "${relativePluginPath}/${framework.$.src}"`); } }); prefsArray = prefsArray.concat(getAllElements(p, platform, 'preference')); }); let frameworkString = frameworksArray - .map(f => { + .map((f) => { if (f.startsWith('platform(')) { return ` implementation ${f}`; } else { @@ -337,11 +257,7 @@ export async function handleCordovaPluginsGradle( } }) .join('\n'); - frameworkString = await replaceFrameworkVariables( - config, - prefsArray, - frameworkString, - ); + frameworkString = await replaceFrameworkVariables(config, prefsArray, frameworkString); if (kotlinNeeded) { frameworkString += `\n implementation "androidx.core:core-ktx:$androidxCoreKTXVersion"`; frameworkString += `\n implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"`; @@ -386,17 +302,11 @@ ext { cdvPluginPostBuildExtras = [] cordovaConfig = [:] }`; - await writeFile( - join(config.android.cordovaPluginsDirAbs, 'cordova.variables.gradle'), - cordovaVariables, - ); + await writeFile(join(config.android.cordovaPluginsDirAbs, 'cordova.variables.gradle'), cordovaVariables); } async function kotlinNeededCheck(config: Config, cordovaPlugins: Plugin[]) { - if ( - config.app.extConfig.cordova?.preferences?.GradlePluginKotlinEnabled !== - 'true' - ) { + if (config.app.extConfig.cordova?.preferences?.GradlePluginKotlinEnabled !== 'true') { for (const plugin of cordovaPlugins) { const androidPlatform = getPluginPlatform(plugin, platform); const sourceFiles = androidPlatform['source-file']; @@ -414,10 +324,7 @@ async function kotlinNeededCheck(config: Config, cordovaPlugins: Plugin[]) { } } -async function copyPluginsNativeFiles( - config: Config, - cordovaPlugins: Plugin[], -) { +async function copyPluginsNativeFiles(config: Config, cordovaPlugins: Plugin[]) { const pluginsPath = join(config.android.cordovaPluginsDirAbs, 'src', 'main'); for (const p of cordovaPlugins) { const androidPlatform = getPluginPlatform(p, platform); @@ -430,13 +337,8 @@ async function copyPluginsNativeFiles( if (fileName.split('.').pop() === 'aidl') { baseFolder = 'aidl/'; } - const target = sourceFile.$['target-dir'] - .replace('app/src/main/', '') - .replace('src/', baseFolder); - await copy( - getFilePath(config, p, sourceFile.$.src), - join(pluginsPath, target, fileName), - ); + const target = sourceFile.$['target-dir'].replace('app/src/main/', '').replace('src/', baseFolder); + await copy(getFilePath(config, p, sourceFile.$.src), join(pluginsPath, target, fileName)); } } const resourceFiles = androidPlatform['resource-file']; @@ -444,24 +346,15 @@ async function copyPluginsNativeFiles( for (const resourceFile of resourceFiles) { const target = resourceFile.$['target']; if (resourceFile.$.src.split('.').pop() === 'aar') { - await copy( - getFilePath(config, p, resourceFile.$.src), - join(pluginsPath, 'libs', target.split('/').pop()), - ); + await copy(getFilePath(config, p, resourceFile.$.src), join(pluginsPath, 'libs', target.split('/').pop())); } else if (target !== '.') { - await copy( - getFilePath(config, p, resourceFile.$.src), - join(pluginsPath, target), - ); + await copy(getFilePath(config, p, resourceFile.$.src), join(pluginsPath, target)); } } } const libFiles = getPlatformElement(p, platform, 'lib-file'); for (const libFile of libFiles) { - await copy( - getFilePath(config, p, libFile.$.src), - join(pluginsPath, 'libs', libFile.$.src.split('/').pop()), - ); + await copy(getFilePath(config, p, libFile.$.src), join(pluginsPath, 'libs', libFile.$.src.split('/').pop())); } } } @@ -484,10 +377,7 @@ async function getPluginsTask(config: Config) { } async function getVariablesGradleFile(config: Config) { - const variablesFile = resolve( - config.android.platformDirAbs, - 'variables.gradle', - ); + const variablesFile = resolve(config.android.platformDirAbs, 'variables.gradle'); let variablesGradle = ''; if (await pathExists(variablesFile)) { variablesGradle = await readFile(variablesFile, { encoding: 'utf-8' }); @@ -495,11 +385,7 @@ async function getVariablesGradleFile(config: Config) { return variablesGradle; } -async function replaceFrameworkVariables( - config: Config, - prefsArray: any[], - frameworkString: string, -) { +async function replaceFrameworkVariables(config: Config, prefsArray: any[], frameworkString: string) { const variablesGradle = await getVariablesGradleFile(config); prefsArray.map((preference: any) => { if (!variablesGradle.includes(preference.$.name)) { diff --git a/cli/src/common.ts b/cli/src/common.ts index 4f9fe8288..fec3d0fc1 100644 --- a/cli/src/common.ts +++ b/cli/src/common.ts @@ -14,8 +14,8 @@ import { runCommand } from './util/subprocess'; export type CheckFunction = () => Promise; export async function check(checks: CheckFunction[]): Promise { - const results = await Promise.all(checks.map(f => f())); - const errors = results.filter(r => r != null) as string[]; + const results = await Promise.all(checks.map((f) => f())); + const errors = results.filter((r) => r != null) as string[]; if (errors.length > 0) { throw errors.join('\n'); } @@ -33,20 +33,14 @@ export async function checkWebDir(config: Config): Promise { } if (!(await pathExists(config.app.webDirAbs))) { return ( - `Could not find the web assets directory: ${c.strong( - prettyPath(config.app.webDirAbs), - )}.\n` + + `Could not find the web assets directory: ${c.strong(prettyPath(config.app.webDirAbs))}.\n` + `Please create it and make sure it has an ${c.strong( 'index.html', - )} file. You can change the path of this directory in ${c.strong( - config.app.extConfigName, - )} (${c.input( + )} file. You can change the path of this directory in ${c.strong(config.app.extConfigName)} (${c.input( 'webDir', )} option). You may need to compile the web assets for your app (typically ${c.input( 'npm run build', - )}). More info: ${c.strong( - 'https://capacitorjs.com/docs/basics/workflow#sync-your-project', - )}` + )}). More info: ${c.strong('https://capacitorjs.com/docs/basics/workflow#sync-your-project')}` ); } @@ -76,18 +70,13 @@ export async function checkPackage(): Promise { return null; } -export async function checkCapacitorPlatform( - config: Config, - platform: string, -): Promise { +export async function checkCapacitorPlatform(config: Config, platform: string): Promise { const pkg = await getCapacitorPackage(config, platform); if (!pkg) { return ( `Could not find the ${c.input(platform)} platform.\n` + - `You must install it in your project first, e.g. w/ ${c.input( - `npm install @capacitor/${platform}`, - )}` + `You must install it in your project first, e.g. w/ ${c.input(`npm install @capacitor/${platform}`)}` ); } @@ -98,17 +87,13 @@ export async function checkAppConfig(config: Config): Promise { if (!config.app.appId) { return ( `Missing ${c.input('appId')} for new platform.\n` + - `Please add it in ${config.app.extConfigName} or run ${c.input( - 'npx cap init', - )}.` + `Please add it in ${config.app.extConfigName} or run ${c.input('npx cap init')}.` ); } if (!config.app.appName) { return ( `Missing ${c.input('appName')} for new platform.\n` + - `Please add it in ${config.app.extConfigName} or run ${c.input( - 'npx cap init', - )}.` + `Please add it in ${config.app.extConfigName} or run ${c.input('npx cap init')}.` ); } @@ -125,20 +110,14 @@ export async function checkAppConfig(config: Config): Promise { return null; } -export async function checkAppDir( - config: Config, - dir: string, -): Promise { +export async function checkAppDir(config: Config, dir: string): Promise { if (!/^\S*$/.test(dir)) { return `Your app directory should not contain spaces`; } return null; } -export async function checkAppId( - config: Config, - id: string, -): Promise { +export async function checkAppId(config: Config, id: string): Promise { if (!id) { return `Invalid App ID. App ID is required and cannot be blank.`; } @@ -156,10 +135,7 @@ export async function checkAppId( `; } -export async function checkAppName( - config: Config, - name: string, -): Promise { +export async function checkAppName(config: Config, name: string): Promise { // We allow pretty much anything right now, have fun if (!name?.length) { return `Must provide an app name. For example: 'Spacebook'`; @@ -168,19 +144,14 @@ export async function checkAppName( } export async function wait(time: number): Promise { - return new Promise(resolve => setTimeout(resolve, time)); + return new Promise((resolve) => setTimeout(resolve, time)); } -export async function runHooks( - config: Config, - platformName: string, - dir: string, - hook: string, -): Promise { +export async function runHooks(config: Config, platformName: string, dir: string, hook: string): Promise { await runPlatformHook(config, platformName, dir, hook); const allPlugins = await getPlugins(config, platformName); - allPlugins.forEach(async p => { + allPlugins.forEach(async (p) => { await runPlatformHook(config, platformName, p.rootPath, hook); }); } @@ -221,7 +192,7 @@ export async function runPlatformHook( p.on('close', () => { resolve(); }); - p.on('error', err => { + p.on('error', (err) => { reject(err); }); }); @@ -231,10 +202,7 @@ export interface RunTaskOptions { spinner?: boolean; } -export async function runTask( - title: string, - fn: () => Promise, -): Promise { +export async function runTask(title: string, fn: () => Promise): Promise { const chain = output.createTaskChain(); chain.next(title); @@ -248,15 +216,8 @@ export async function runTask( } } -export async function getCapacitorPackage( - config: Config, - name: string, -): Promise { - const packagePath = resolveNode( - config.app.rootDir, - `@capacitor/${name}`, - 'package.json', - ); +export async function getCapacitorPackage(config: Config, name: string): Promise { + const packagePath = resolveNode(config.app.rootDir, `@capacitor/${name}`, 'package.json'); if (!packagePath) { return null; @@ -265,10 +226,7 @@ export async function getCapacitorPackage( return readJSON(packagePath); } -export async function requireCapacitorPackage( - config: Config, - name: string, -): Promise { +export async function requireCapacitorPackage(config: Config, name: string): Promise { const pkg = await getCapacitorPackage(config, name); if (!pkg) { @@ -280,10 +238,7 @@ export async function requireCapacitorPackage( return pkg; } -export async function getCapacitorPackageVersion( - config: Config, - platform: string, -): Promise { +export async function getCapacitorPackageVersion(config: Config, platform: string): Promise { return (await requireCapacitorPackage(config, platform)).version; } @@ -308,10 +263,7 @@ function getPlatformDirectory(config: Config, platform: string): string | null { return null; } -export async function getProjectPlatformDirectory( - config: Config, - platform: string, -): Promise { +export async function getProjectPlatformDirectory(config: Config, platform: string): Promise { const platformPath = getPlatformDirectory(config, platform); if (platformPath && (await pathExists(platformPath))) { @@ -321,10 +273,7 @@ export async function getProjectPlatformDirectory( return null; } -export async function selectPlatforms( - config: Config, - selectedPlatformName?: string, -): Promise { +export async function selectPlatforms(config: Config, selectedPlatformName?: string): Promise { if (selectedPlatformName) { // already passed in a platform name const platformName = selectedPlatformName.toLowerCase().trim(); @@ -333,16 +282,11 @@ export async function selectPlatforms( fatal(`Invalid platform: ${c.input(platformName)}`); } else if (!(await getProjectPlatformDirectory(config, platformName))) { if (platformName === 'web') { - fatal( - `Could not find the web platform directory.\n` + - `Make sure ${c.strong(config.app.webDir)} exists.`, - ); + fatal(`Could not find the web platform directory.\n` + `Make sure ${c.strong(config.app.webDir)} exists.`); } fatal( `${c.strong(platformName)} platform has not been added yet.\n` + - `See the docs for adding the ${c.strong( - platformName, - )} platform: ${c.strong( + `See the docs for adding the ${c.strong(platformName)} platform: ${c.strong( `https://capacitorjs.com/docs/${platformName}#adding-the-${platformName}-platform`, )}`, ); @@ -369,9 +313,7 @@ export async function getKnownCommunityPlatforms(): Promise { return ['electron']; } -export async function isValidCommunityPlatform( - platform: string, -): Promise { +export async function isValidCommunityPlatform(platform: string): Promise { return (await getKnownCommunityPlatforms()).includes(platform); } @@ -379,9 +321,7 @@ export async function getKnownEnterprisePlatforms(): Promise { return ['windows']; } -export async function isValidEnterprisePlatform( - platform: string, -): Promise { +export async function isValidEnterprisePlatform(platform: string): Promise { return (await getKnownEnterprisePlatforms()).includes(platform); } @@ -399,7 +339,7 @@ export async function promptForPlatform( type: 'select', name: 'mode', message: promptMessage, - choices: platforms.map(p => ({ title: p, value: p })), + choices: platforms.map((p) => ({ title: p, value: p })), }, ], { onCancel: () => process.exit(1) }, @@ -413,10 +353,7 @@ export async function promptForPlatform( if (!(await isValidPlatform(platformName))) { const knownPlatforms = await getKnownPlatforms(); - fatal( - `Invalid platform: ${c.input(platformName)}.\n` + - `Valid platforms include: ${knownPlatforms.join(', ')}`, - ); + fatal(`Invalid platform: ${c.input(platformName)}.\n` + `Valid platforms include: ${knownPlatforms.join(', ')}`); } return platformName; @@ -436,7 +373,7 @@ export async function promptForPlatformTarget( selectedTarget?: string, ): Promise { const { prompt } = await import('prompts'); - const validTargets = targets.filter(t => t.id !== undefined); + const validTargets = targets.filter((t) => t.id !== undefined); if (!selectedTarget) { if (validTargets.length === 1) { return validTargets[0]; @@ -447,7 +384,7 @@ export async function promptForPlatformTarget( type: 'select', name: 'target', message: 'Please choose a target device:', - choices: validTargets.map(t => ({ + choices: validTargets.map((t) => ({ title: `${getPlatformTargetName(t)} (${t.id})`, value: t, })), @@ -461,13 +398,10 @@ export async function promptForPlatformTarget( } const targetID = selectedTarget.trim(); - const target = targets.find(t => t.id === targetID); + const target = targets.find((t) => t.id === targetID); if (!target) { - fatal( - `Invalid target ID: ${c.input(targetID)}.\n` + - `Valid targets are: ${targets.map(t => t.id).join(', ')}`, - ); + fatal(`Invalid target ID: ${c.input(targetID)}.\n` + `Valid targets are: ${targets.map((t) => t.id).join(', ')}`); } return target; @@ -475,9 +409,7 @@ export async function promptForPlatformTarget( export function getPlatformTargetName(target: PlatformTarget): string { return `${target.name ?? target.model ?? target.id ?? '?'}${ - target.virtual - ? ` (${target.platform === 'ios' ? 'simulator' : 'emulator'})` - : '' + target.virtual ? ` (${target.platform === 'ios' ? 'simulator' : 'emulator'})` : '' }`; } @@ -497,61 +429,36 @@ export async function getAddedPlatforms(config: Config): Promise { return platforms; } -export async function checkPlatformVersions( - config: Config, - platform: string, -): Promise { +export async function checkPlatformVersions(config: Config, platform: string): Promise { const semver = await import('semver'); const coreVersion = await getCoreVersion(config); const platformVersion = await getCapacitorPackageVersion(config, platform); - if ( - semver.diff(coreVersion, platformVersion) === 'minor' || - semver.diff(coreVersion, platformVersion) === 'major' - ) { + if (semver.diff(coreVersion, platformVersion) === 'minor' || semver.diff(coreVersion, platformVersion) === 'major') { logger.warn( `${c.strong('@capacitor/core')}${c.weak( `@${coreVersion}`, - )} version doesn't match ${c.strong(`@capacitor/${platform}`)}${c.weak( - `@${platformVersion}`, - )} version.\n` + - `Consider updating to a matching version, e.g. w/ ${c.input( - `npm install @capacitor/core@${platformVersion}`, - )}`, + )} version doesn't match ${c.strong(`@capacitor/${platform}`)}${c.weak(`@${platformVersion}`)} version.\n` + + `Consider updating to a matching version, e.g. w/ ${c.input(`npm install @capacitor/core@${platformVersion}`)}`, ); } } -export function resolvePlatform( - config: Config, - platform: string, -): string | null { +export function resolvePlatform(config: Config, platform: string): string | null { if (platform[0] !== '@') { - const core = resolveNode( - config.app.rootDir, - `@capacitor/${platform}`, - 'package.json', - ); + const core = resolveNode(config.app.rootDir, `@capacitor/${platform}`, 'package.json'); if (core) { return dirname(core); } - const community = resolveNode( - config.app.rootDir, - `@capacitor-community/${platform}`, - 'package.json', - ); + const community = resolveNode(config.app.rootDir, `@capacitor-community/${platform}`, 'package.json'); if (community) { return dirname(community); } - const enterprise = resolveNode( - config.app.rootDir, - `@ionic-enterprise/capacitor-${platform}`, - 'package.json', - ); + const enterprise = resolveNode(config.app.rootDir, `@ionic-enterprise/capacitor-${platform}`, 'package.json'); if (enterprise) { return dirname(enterprise); @@ -583,11 +490,7 @@ export async function checkJDKMajorVersion(): Promise { if (typeof firstVersionNumber === 'number' && firstVersionNumber != 1) { return firstVersionNumber; - } else if ( - typeof secondVersionNumber === 'number' && - firstVersionNumber == 1 && - secondVersionNumber < 9 - ) { + } else if (typeof secondVersionNumber === 'number' && firstVersionNumber == 1 && secondVersionNumber < 9) { return secondVersionNumber; } else { return -1; diff --git a/cli/src/config.ts b/cli/src/config.ts index 212a03298..c88590185 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -1,24 +1,10 @@ -import { - pathExists, - readFile, - readJSON, - writeFile, - writeJSON, -} from '@ionic/utils-fs'; +import { pathExists, readFile, readJSON, writeFile, writeJSON } from '@ionic/utils-fs'; import Debug from 'debug'; import { dirname, extname, join, relative, resolve } from 'path'; import c from './colors'; import { parseApkNameFromFlavor } from './common'; -import type { - AndroidConfig, - AppConfig, - CLIConfig, - Config, - ExternalConfig, - IOSConfig, - WebConfig, -} from './definitions'; +import type { AndroidConfig, AppConfig, CLIConfig, Config, ExternalConfig, IOSConfig, WebConfig } from './definitions'; import { OS } from './definitions'; import { fatal, isFatal } from './errors'; import { logger } from './log'; @@ -40,15 +26,10 @@ export async function loadConfig(): Promise { const cliRootDir = dirname(__dirname); const conf = await loadExtConfig(appRootDir); - const depsForNx = await (async (): Promise< - { devDependencies: any; dependencies: any } | object - > => { + const depsForNx = await (async (): Promise<{ devDependencies: any; dependencies: any } | object> => { if (isNXMonorepo(appRootDir)) { const rootOfNXMonorepo = findNXMonorepoRoot(appRootDir); - const pkgJSONOfMonorepoRoot: any = await tryFn( - readJSON, - resolve(rootOfNXMonorepo, 'package.json'), - ); + const pkgJSONOfMonorepoRoot: any = await tryFn(readJSON, resolve(rootOfNXMonorepo, 'package.json')); const devDependencies = pkgJSONOfMonorepoRoot?.devDependencies ?? {}; const dependencies = pkgJSONOfMonorepoRoot?.dependencies ?? {}; return { @@ -89,10 +70,7 @@ export async function loadConfig(): Promise { return config; } -export async function writeConfig( - extConfig: ExternalConfig, - extConfigFilePath: string, -): Promise { +export async function writeConfig(extConfig: ExternalConfig, extConfigFilePath: string): Promise { switch (extname(extConfigFilePath)) { case '.json': { await writeJSON(extConfigFilePath, extConfig, { spaces: 2 }); @@ -105,10 +83,7 @@ export async function writeConfig( } } -type ExtConfigPairs = Pick< - AppConfig, - 'extConfigType' | 'extConfigName' | 'extConfigFilePath' | 'extConfig' ->; +type ExtConfigPairs = Pick; async function loadExtConfigTS( rootDir: string, @@ -121,9 +96,7 @@ async function loadExtConfigTS( if (!tsPath) { fatal( 'Could not find installation of TypeScript.\n' + - `To use ${c.strong( - extConfigName, - )} files, you must install TypeScript in your project, e.g. w/ ${c.input( + `To use ${c.strong(extConfigName)} files, you must install TypeScript in your project, e.g. w/ ${c.input( 'npm install -D typescript', )}`, ); @@ -131,9 +104,7 @@ async function loadExtConfigTS( const ts = require(tsPath); // eslint-disable-line @typescript-eslint/no-var-requires const extConfigObject = requireTS(ts, extConfigFilePath) as any; - const extConfig = extConfigObject.default - ? await extConfigObject.default - : extConfigObject; + const extConfig = extConfigObject.default ? await extConfigObject.default : extConfigObject; return { extConfigType: 'ts', @@ -194,11 +165,9 @@ async function loadCLIConfig(rootDir: string): Promise { const assetsDir = 'assets'; const assetsDirAbs = join(rootDir, assetsDir); const iosPlatformTemplateArchive = 'ios-pods-template.tar.gz'; - const iosCordovaPluginsTemplateArchive = - 'capacitor-cordova-ios-plugins.tar.gz'; + const iosCordovaPluginsTemplateArchive = 'capacitor-cordova-ios-plugins.tar.gz'; const androidPlatformTemplateArchive = 'android-template.tar.gz'; - const androidCordovaPluginsTemplateArchive = - 'capacitor-cordova-android-plugins.tar.gz'; + const androidCordovaPluginsTemplateArchive = 'capacitor-cordova-android-plugins.tar.gz'; return { rootDir, @@ -207,27 +176,15 @@ async function loadCLIConfig(rootDir: string): Promise { assets: { ios: { platformTemplateArchive: iosPlatformTemplateArchive, - platformTemplateArchiveAbs: resolve( - assetsDirAbs, - iosPlatformTemplateArchive, - ), + platformTemplateArchiveAbs: resolve(assetsDirAbs, iosPlatformTemplateArchive), cordovaPluginsTemplateArchive: iosCordovaPluginsTemplateArchive, - cordovaPluginsTemplateArchiveAbs: resolve( - assetsDirAbs, - iosCordovaPluginsTemplateArchive, - ), + cordovaPluginsTemplateArchiveAbs: resolve(assetsDirAbs, iosCordovaPluginsTemplateArchive), }, android: { platformTemplateArchive: androidPlatformTemplateArchive, - platformTemplateArchiveAbs: resolve( - assetsDirAbs, - androidPlatformTemplateArchive, - ), + platformTemplateArchiveAbs: resolve(assetsDirAbs, androidPlatformTemplateArchive), cordovaPluginsTemplateArchive: androidCordovaPluginsTemplateArchive, - cordovaPluginsTemplateArchiveAbs: resolve( - assetsDirAbs, - androidCordovaPluginsTemplateArchive, - ), + cordovaPluginsTemplateArchiveAbs: resolve(assetsDirAbs, androidCordovaPluginsTemplateArchive), }, }, package: await readJSON(resolve(rootDir, 'package.json')), @@ -262,8 +219,7 @@ async function loadAndroidConfig( keystorePath: extConfig.android?.buildOptions?.keystorePath, keystorePassword: extConfig.android?.buildOptions?.keystorePassword, keystoreAlias: extConfig.android?.buildOptions?.keystoreAlias, - keystoreAliasPassword: - extConfig.android?.buildOptions?.keystoreAliasPassword, + keystoreAliasPassword: extConfig.android?.buildOptions?.keystoreAliasPassword, signingType: extConfig.android?.buildOptions?.signingType, releaseType: extConfig.android?.buildOptions?.releaseType, }; @@ -296,10 +252,7 @@ async function loadAndroidConfig( }; } -async function loadIOSConfig( - rootDir: string, - extConfig: ExternalConfig, -): Promise { +async function loadIOSConfig(rootDir: string, extConfig: ExternalConfig): Promise { const name = 'ios'; const platformDir = extConfig.ios?.path ?? 'ios'; const platformDirAbs = resolve(rootDir, platformDir); @@ -310,23 +263,9 @@ async function loadIOSConfig( const nativeTargetDirAbs = resolve(platformDirAbs, nativeTargetDir); const nativeXcodeProjDir = `${nativeProjectDir}/App.xcodeproj`; const nativeXcodeProjDirAbs = resolve(platformDirAbs, nativeXcodeProjDir); - const nativeXcodeWorkspaceDirAbs = lazy(() => - determineXcodeWorkspaceDirAbs(nativeProjectDirAbs), - ); - const podPath = lazy(() => - determineGemfileOrCocoapodPath( - rootDir, - platformDirAbs, - nativeProjectDirAbs, - ), - ); - const webDirAbs = lazy(() => - determineIOSWebDirAbs( - nativeProjectDirAbs, - nativeTargetDirAbs, - nativeXcodeProjDirAbs, - ), - ); + const nativeXcodeWorkspaceDirAbs = lazy(() => determineXcodeWorkspaceDirAbs(nativeProjectDirAbs)); + const podPath = lazy(() => determineGemfileOrCocoapodPath(rootDir, platformDirAbs, nativeProjectDirAbs)); + const webDirAbs = lazy(() => determineIOSWebDirAbs(nativeProjectDirAbs, nativeTargetDirAbs, nativeXcodeProjDirAbs)); const cordovaPluginsDir = 'capacitor-cordova-ios-plugins'; return { @@ -343,9 +282,7 @@ async function loadIOSConfig( nativeTargetDirAbs, nativeXcodeProjDir, nativeXcodeProjDirAbs, - nativeXcodeWorkspaceDir: lazy(async () => - relative(platformDirAbs, await nativeXcodeWorkspaceDirAbs), - ), + nativeXcodeWorkspaceDir: lazy(async () => relative(platformDirAbs, await nativeXcodeWorkspaceDirAbs)), nativeXcodeWorkspaceDirAbs, webDir: lazy(async () => relative(platformDirAbs, await webDirAbs)), webDirAbs, @@ -353,10 +290,7 @@ async function loadIOSConfig( }; } -async function loadWebConfig( - rootDir: string, - webDir: string, -): Promise { +async function loadWebConfig(rootDir: string, webDir: string): Promise { const platformDir = webDir; const platformDirAbs = resolve(rootDir, platformDir); @@ -380,9 +314,7 @@ function determineOS(os: NodeJS.Platform): OS { return OS.Unknown; } -async function determineXcodeWorkspaceDirAbs( - nativeProjectDirAbs: string, -): Promise { +async function determineXcodeWorkspaceDirAbs(nativeProjectDirAbs: string): Promise { return resolve(nativeProjectDirAbs, 'App.xcworkspace'); } @@ -400,12 +332,8 @@ async function determineIOSWebDirAbs( if (m && m[1] === 'SOURCE_ROOT') { logger.warn( - `Using the iOS project root for the ${c.strong( - 'public', - )} directory is deprecated.\n` + - `Please follow the Upgrade Guide to move ${c.strong( - 'public', - )} inside the iOS target directory: ${c.strong( + `Using the iOS project root for the ${c.strong('public')} directory is deprecated.\n` + + `Please follow the Upgrade Guide to move ${c.strong('public')} inside the iOS target directory: ${c.strong( 'https://capacitorjs.com/docs/updating/3-0#move-public-into-the-ios-target-directory', )}`, ); @@ -483,11 +411,7 @@ async function determineGemfileOrCocoapodPath( // Multi-app projects might share a single global 'Gemfile' at the Git repository root directory. if (!appSpecificGemfileExists) { try { - const output = await getCommandOutput( - 'git', - ['rev-parse', '--show-toplevel'], - { cwd: rootDir }, - ); + const output = await getCommandOutput('git', ['rev-parse', '--show-toplevel'], { cwd: rootDir }); if (output != null) { gemfilePath = resolve(output, 'Gemfile'); } @@ -501,9 +425,7 @@ async function determineGemfileOrCocoapodPath( if (!gemfileText) { return 'pod'; } - const cocoapodsInGemfile = new RegExp(/gem\s+['"]cocoapods/).test( - gemfileText, - ); + const cocoapodsInGemfile = new RegExp(/gem\s+['"]cocoapods/).test(gemfileText); if (cocoapodsInGemfile) { return 'bundle exec pod'; diff --git a/cli/src/cordova.ts b/cli/src/cordova.ts index 0fa6be758..31f05221c 100644 --- a/cli/src/cordova.ts +++ b/cli/src/cordova.ts @@ -1,12 +1,4 @@ -import { - copy, - ensureDir, - mkdirp, - pathExists, - readFile, - remove, - writeFile, -} from '@ionic/utils-fs'; +import { copy, ensureDir, mkdirp, pathExists, readFile, remove, writeFile } from '@ionic/utils-fs'; import { basename, extname, join, resolve } from 'path'; import plist from 'plist'; import type { PlistObject } from 'plist'; @@ -37,14 +29,10 @@ import { buildXmlElement, parseXML, readXML, writeXML } from './util/xml'; /** * Build the root cordova_plugins.js file referencing each Plugin JS file. */ -export function generateCordovaPluginsJSFile( - config: Config, - plugins: Plugin[], - platform: string, -): string { +export function generateCordovaPluginsJSFile(config: Config, plugins: Plugin[], platform: string): string { const pluginModules: any[] = []; const pluginExports: string[] = []; - plugins.map(p => { + plugins.map((p) => { const pluginId = p.xml.$.id; const jsModules = getJSModules(p, platform); jsModules.map((jsModule: any) => { @@ -83,11 +71,7 @@ export function generateCordovaPluginsJSFile( merge: mergeKey, // mimics Cordova's module name logic if the name attr is missing pluginContent: `{ - "id": "${ - pluginId + - '.' + - (jsModule.$.name || jsModule.$.src.match(/([^/]+)\.js/)[1]) - }", + "id": "${pluginId + '.' + (jsModule.$.name || jsModule.$.src.match(/([^/]+)\.js/)[1])}", "file": "plugins/${pluginId}/${jsModule.$.src}", "pluginId": "${pluginId}"${clobbersModule}${mergesModule}${runsModule} }`, @@ -105,10 +89,10 @@ export function generateCordovaPluginsJSFile( a.clobber && b.clobber // Clobbers in alpha order ? a.clobber.localeCompare(b.clobber) : a.clobber || b.clobber // Clobbers before anything else - ? b.clobber.localeCompare(a.clobber) - : a.merge.localeCompare(b.merge), // Merges in alpha order + ? b.clobber.localeCompare(a.clobber) + : a.merge.localeCompare(b.merge), // Merges in alpha order ) - .map(e => e.pluginContent) + .map((e) => e.pluginContent) .join(',\n ')} ]; module.exports.metadata = @@ -124,17 +108,13 @@ export function generateCordovaPluginsJSFile( /** * Build the plugins/* files for each Cordova plugin installed. */ -export async function copyPluginsJS( - config: Config, - cordovaPlugins: Plugin[], - platform: string, -): Promise { +export async function copyPluginsJS(config: Config, cordovaPlugins: Plugin[], platform: string): Promise { const webDir = await getWebDir(config, platform); const pluginsDir = join(webDir, 'plugins'); const cordovaPluginsJSFile = join(webDir, 'cordova_plugins.js'); await removePluginFiles(config, platform); await Promise.all( - cordovaPlugins.map(async p => { + cordovaPlugins.map(async (p) => { const pluginId = p.xml.$.id; const pluginDir = join(pluginsDir, pluginId, 'www'); await ensureDir(pluginDir); @@ -146,16 +126,9 @@ export async function copyPluginsJS( let data = await readFile(filePath, { encoding: 'utf-8' }); data = data.trim(); // mimics Cordova's module name logic if the name attr is missing - const name = - pluginId + - '.' + - (jsModule.$.name || - basename(jsModule.$.src, extname(jsModule.$.src))); + const name = pluginId + '.' + (jsModule.$.name || basename(jsModule.$.src, extname(jsModule.$.src))); data = `cordova.define("${name}", function(require, exports, module) { \n${data}\n});`; - data = data.replace( - /)<[^<]*)*<\/script\s*>/gi, - '', - ); + data = data.replace(/)<[^<]*)*<\/script\s*>/gi, ''); await writeFile(filePath, data, { encoding: 'utf-8' }); }), ); @@ -168,48 +141,28 @@ export async function copyPluginsJS( ); }), ); - await writeFile( - cordovaPluginsJSFile, - generateCordovaPluginsJSFile(config, cordovaPlugins, platform), - ); + await writeFile(cordovaPluginsJSFile, generateCordovaPluginsJSFile(config, cordovaPlugins, platform)); } -export async function copyCordovaJS( - config: Config, - platform: string, -): Promise { - const cordovaPath = resolveNode( - config.app.rootDir, - '@capacitor/core', - 'cordova.js', - ); +export async function copyCordovaJS(config: Config, platform: string): Promise { + const cordovaPath = resolveNode(config.app.rootDir, '@capacitor/core', 'cordova.js'); if (!cordovaPath) { fatal( - `Unable to find ${c.strong( - 'node_modules/@capacitor/core/cordova.js', - )}.\n` + `Are you sure ${c.strong('@capacitor/core')} is installed?`, + `Unable to find ${c.strong('node_modules/@capacitor/core/cordova.js')}.\n` + + `Are you sure ${c.strong('@capacitor/core')} is installed?`, ); } - return copy( - cordovaPath, - join(await getWebDir(config, platform), 'cordova.js'), - ); + return copy(cordovaPath, join(await getWebDir(config, platform), 'cordova.js')); } -export async function createEmptyCordovaJS( - config: Config, - platform: string, -): Promise { +export async function createEmptyCordovaJS(config: Config, platform: string): Promise { const webDir = await getWebDir(config, platform); await writeFile(join(webDir, 'cordova.js'), ''); await writeFile(join(webDir, 'cordova_plugins.js'), ''); } -export async function removePluginFiles( - config: Config, - platform: string, -): Promise { +export async function removePluginFiles(config: Config, platform: string): Promise { const webDir = await getWebDir(config, platform); const pluginsDir = join(webDir, 'plugins'); const cordovaPluginsJSFile = join(webDir, 'cordova_plugins.js'); @@ -217,11 +170,7 @@ export async function removePluginFiles( await remove(cordovaPluginsJSFile); } -export async function autoGenerateConfig( - config: Config, - cordovaPlugins: Plugin[], - platform: string, -): Promise { +export async function autoGenerateConfig(config: Config, cordovaPlugins: Plugin[], platform: string): Promise { let xmlDir = join(config.android.resDirAbs, 'xml'); const fileName = 'config.xml'; if (platform === 'ios') { @@ -231,7 +180,7 @@ export async function autoGenerateConfig( const cordovaConfigXMLFile = join(xmlDir, fileName); await remove(cordovaConfigXMLFile); const pluginEntries: any[] = []; - cordovaPlugins.map(p => { + cordovaPlugins.map((p) => { const currentPlatform = getPluginPlatform(p, platform); if (currentPlatform) { const configFiles = currentPlatform['config-file']; @@ -252,12 +201,10 @@ export async function autoGenerateConfig( let accessOriginString: string[] = []; if (config.app.extConfig?.cordova?.accessOrigins) { accessOriginString = await Promise.all( - config.app.extConfig.cordova.accessOrigins.map( - async (host): Promise => { - return ` + config.app.extConfig.cordova.accessOrigins.map(async (host): Promise => { + return ` `; - }, - ), + }), ); } else { accessOriginString.push(``); @@ -271,12 +218,10 @@ export async function autoGenerateConfig( let pluginPreferencesString: string[] = []; if (config.app.extConfig?.cordova?.preferences) { pluginPreferencesString = await Promise.all( - Object.entries(config.app.extConfig.cordova.preferences).map( - async ([key, value]): Promise => { - return ` + Object.entries(config.app.extConfig.cordova.preferences).map(async ([key, value]): Promise => { + return ` `; - }, - ), + }), ); } const content = ` @@ -317,10 +262,7 @@ export async function handleCordovaPluginsJS( await autoGenerateConfig(config, cordovaPlugins, platform); } -export async function getCordovaPlugins( - config: Config, - platform: string, -): Promise { +export async function getCordovaPlugins(config: Config, platform: string): Promise { const allPlugins = await getPlugins(config, platform); let plugins: Plugin[] = []; if (platform === config.ios.name) { @@ -328,15 +270,11 @@ export async function getCordovaPlugins( } else if (platform === config.android.name) { plugins = await getAndroidPlugins(allPlugins); } - return plugins.filter(p => getPluginType(p, platform) === PluginType.Cordova); + return plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); } -export async function logCordovaManualSteps( - cordovaPlugins: Plugin[], - config: Config, - platform: string, -): Promise { - cordovaPlugins.map(p => { +export async function logCordovaManualSteps(cordovaPlugins: Plugin[], config: Config, platform: string): Promise { + cordovaPlugins.map((p) => { const editConfig = getPlatformElement(p, platform, 'edit-config'); const configFile = getPlatformElement(p, platform, 'config-file'); editConfig.concat(configFile).map(async (configElement: any) => { @@ -354,17 +292,10 @@ export async function logCordovaManualSteps( async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { let plistPath = resolve(config.ios.nativeTargetDirAbs, 'Info.plist'); if (config.app.extConfig.ios?.scheme) { - plistPath = resolve( - config.ios.nativeProjectDirAbs, - `${config.app.extConfig.ios?.scheme}-Info.plist`, - ); + plistPath = resolve(config.ios.nativeProjectDirAbs, `${config.app.extConfig.ios?.scheme}-Info.plist`); } if (!(await pathExists(plistPath))) { - plistPath = resolve( - config.ios.nativeTargetDirAbs, - 'Base.lproj', - 'Info.plist', - ); + plistPath = resolve(config.ios.nativeTargetDirAbs, 'Base.lproj', 'Info.plist'); } if (await pathExists(plistPath)) { const xmlMeta = await readXML(plistPath); @@ -374,20 +305,10 @@ async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { const dict = xmlMeta.plist.dict.pop(); if (!dict.key.includes(configElement.$.parent)) { let xml = buildConfigFileXml(configElement); - xml = `${configElement.$.parent}${getConfigFileTagContent( - xml, - )}`; - logger.warn( - `Configuration required for ${c.strong(plugin.id)}.\n` + - `Add the following to Info.plist:\n` + - xml, - ); + xml = `${configElement.$.parent}${getConfigFileTagContent(xml)}`; + logger.warn(`Configuration required for ${c.strong(plugin.id)}.\n` + `Add the following to Info.plist:\n` + xml); } else if (configElement.array || configElement.dict) { - if ( - configElement.array && - configElement.array.length > 0 && - configElement.array[0].string - ) { + if (configElement.array && configElement.array.length > 0 && configElement.array[0].string) { let xml = ''; configElement.array[0].string.map((element: any) => { const d = plistData[configElement.$.parent]; @@ -398,23 +319,16 @@ async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { if (xml.length > 0) { logger.warn( `Configuration required for ${c.strong(plugin.id)}.\n` + - `Add the following in the existing ${c.strong( - configElement.$.parent, - )} array of your Info.plist:\n` + + `Add the following in the existing ${c.strong(configElement.$.parent)} array of your Info.plist:\n` + xml, ); } } else { let xml = buildConfigFileXml(configElement); - xml = `${configElement.$.parent}${getConfigFileTagContent( - xml, - )}`; + xml = `${configElement.$.parent}${getConfigFileTagContent(xml)}`; xml = `${xml}`; - const parseXmlToSearchable = ( - childElementsObj: any[], - arrayToAddTo: any[], - ) => { + const parseXmlToSearchable = (childElementsObj: any[], arrayToAddTo: any[]) => { for (const childElement of childElementsObj) { const childElementName = childElement['#name']; const toAdd: { @@ -484,15 +398,9 @@ async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { ); parsedRequiredElements.push(rootOfRequiredElementsToAdd); - const doesContainElements = ( - requiredElementsArray: any[], - existingElementsArray: any[], - ) => { + const doesContainElements = (requiredElementsArray: any[], existingElementsArray: any[]) => { for (const requiredElement of requiredElementsArray) { - if ( - requiredElement.name === 'key' || - requiredElement.name === 'string' - ) { + if (requiredElement.name === 'key' || requiredElement.name === 'string') { let foundMatch = false; for (const existingElement of existingElementsArray) { if ( @@ -511,16 +419,8 @@ async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { let foundMatch = false; for (const existingElement of existingElementsArray) { if (existingElement.name === requiredElement.name) { - if ( - (requiredElement.children !== undefined) === - (existingElement.children !== undefined) - ) { - if ( - doesContainElements( - requiredElement.children, - existingElement.children, - ) - ) { + if ((requiredElement.children !== undefined) === (existingElement.children !== undefined)) { + if (doesContainElements(requiredElement.children, existingElement.children)) { foundMatch = true; break; } @@ -535,9 +435,7 @@ async function logiOSPlist(configElement: any, config: Config, plugin: Plugin) { return true; }; - if ( - !doesContainElements(parsedRequiredElements, parsedExistingElements) - ) { + if (!doesContainElements(parsedRequiredElements, parsedExistingElements)) { logPossibleMissingItem(configElement, plugin); } } @@ -553,9 +451,7 @@ function logPossibleMissingItem(configElement: any, plugin: Plugin) { xml = removeOuterTags(xml); logger.warn( `Configuration might be missing for ${c.strong(plugin.id)}.\n` + - `Add the following to the existing ${c.strong( - configElement.$.parent, - )} entry of Info.plist:\n` + + `Add the following to the existing ${c.strong(configElement.$.parent)} entry of Info.plist:\n` + xml, ); } @@ -574,31 +470,21 @@ function removeOuterTags(str: string) { return str.substring(start, end); } -export async function checkPluginDependencies( - plugins: Plugin[], - platform: string, -): Promise { +export async function checkPluginDependencies(plugins: Plugin[], platform: string): Promise { const pluginDeps: Map = new Map(); - const cordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Cordova, - ); - const incompatible = plugins.filter( - p => getPluginType(p, platform) === PluginType.Incompatible, - ); + const cordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); + const incompatible = plugins.filter((p) => getPluginType(p, platform) === PluginType.Incompatible); await Promise.all( - cordovaPlugins.map(async p => { + cordovaPlugins.map(async (p) => { let allDependencies: string[] = []; - allDependencies = allDependencies.concat( - getPlatformElement(p, platform, 'dependency'), - ); + allDependencies = allDependencies.concat(getPlatformElement(p, platform, 'dependency')); if (p.xml['dependency']) { allDependencies = allDependencies.concat(p.xml['dependency']); } allDependencies = allDependencies.filter( (dep: any) => !getIncompatibleCordovaPlugins(platform).includes(dep.$.id) && - incompatible.filter(p => p.id === dep.$.id || p.xml.$.id === dep.$.id) - .length === 0, + incompatible.filter((p) => p.id === dep.$.id || p.xml.$.id === dep.$.id).length === 0, ); if (allDependencies) { await Promise.all( @@ -608,11 +494,7 @@ export async function checkPluginDependencies( if (plugin.includes('@') && plugin.indexOf('@') !== 0) { [plugin, version] = plugin.split('@'); } - if ( - cordovaPlugins.filter( - p => p.id === plugin || p.xml.$.id === plugin, - ).length === 0 - ) { + if (cordovaPlugins.filter((p) => p.id === plugin || p.xml.$.id === plugin).length === 0) { if (dep.$.url?.startsWith('http')) { plugin = dep.$.url; version = dep.$.commit; @@ -630,13 +512,9 @@ export async function checkPluginDependencies( if (pluginDeps.size > 0) { let msg = `${c.failure(c.strong('Plugins are missing dependencies.'))}\n` + - `Cordova plugin dependencies must be installed in your project (e.g. w/ ${c.input( - 'npm install', - )}).\n`; + `Cordova plugin dependencies must be installed in your project (e.g. w/ ${c.input('npm install')}).\n`; for (const [plugin, deps] of pluginDeps.entries()) { - msg += - `\n ${c.strong(plugin)} is missing dependencies:\n` + - deps.map(d => ` - ${d}`).join('\n'); + msg += `\n ${c.strong(plugin)} is missing dependencies:\n` + deps.map((d) => ` - ${d}`).join('\n'); } logger.warn(`${msg}\n`); @@ -660,11 +538,7 @@ export function getIncompatibleCordovaPlugins(platform: string): string[] { 'cordova-support-google-services', ]; if (platform === 'ios') { - pluginList.push( - 'cordova-plugin-statusbar', - '@ionic-enterprise/statusbar', - 'SalesforceMobileSDK-CordovaPlugin', - ); + pluginList.push('cordova-plugin-statusbar', '@ionic-enterprise/statusbar', 'SalesforceMobileSDK-CordovaPlugin'); } if (platform === 'android') { pluginList.push('cordova-plugin-compat'); @@ -679,10 +553,7 @@ export function needsStaticPod(plugin: Plugin): boolean { function useFrameworks(plugin: Plugin): boolean { const podspecs = getPlatformElement(plugin, 'ios', 'podspec'); const frameworkPods = podspecs.filter( - (podspec: any) => - podspec.pods.filter( - (pods: any) => pods.$ && pods.$['use-frameworks'] === 'true', - ).length > 0, + (podspec: any) => podspec.pods.filter((pods: any) => pods.$ && pods.$['use-frameworks'] === 'true').length > 0, ); return frameworkPods.length > 0; } @@ -702,17 +573,11 @@ export async function getCordovaPreferences(config: Config): Promise { if (cordova.preferences && Object.keys(cordova.preferences).length > 0) { if (isInteractive()) { const answers = await logPrompt( - `${c.strong( - `Cordova preferences can be automatically ported to ${c.strong( - config.app.extConfigName, - )}.`, - )}\n` + + `${c.strong(`Cordova preferences can be automatically ported to ${c.strong(config.app.extConfigName)}.`)}\n` + `Keep in mind: Not all values can be automatically migrated from ${c.strong( 'config.xml', )}. There may be more work to do.\n` + - `More info: ${c.strong( - 'https://capacitorjs.com/docs/cordova/migrating-from-cordova-to-capacitor', - )}`, + `More info: ${c.strong('https://capacitorjs.com/docs/cordova/migrating-from-cordova-to-capacitor')}`, { type: 'confirm', name: 'confirm', @@ -752,17 +617,12 @@ export async function writeCordovaAndroidManifest( platform: string, cleartext?: boolean, ): Promise { - const manifestPath = join( - config.android.cordovaPluginsDirAbs, - 'src', - 'main', - 'AndroidManifest.xml', - ); + const manifestPath = join(config.android.cordovaPluginsDirAbs, 'src', 'main', 'AndroidManifest.xml'); const rootXMLEntries: any[] = []; const applicationXMLEntries: any[] = []; const applicationXMLAttributes: any[] = []; let prefsArray: any[] = []; - cordovaPlugins.map(async p => { + cordovaPlugins.map(async (p) => { const editConfig = getPlatformElement(p, platform, 'edit-config'); const configFile = getPlatformElement(p, platform, 'config-file'); prefsArray = prefsArray.concat(getAllElements(p, platform, 'preference')); @@ -772,20 +632,14 @@ export async function writeCordovaAndroidManifest( (configElement.$.target?.includes('AndroidManifest.xml') || configElement.$.file?.includes('AndroidManifest.xml')) ) { - const keys = Object.keys(configElement).filter(k => k !== '$'); - keys.map(k => { + const keys = Object.keys(configElement).filter((k) => k !== '$'); + keys.map((k) => { configElement[k].map(async (e: any) => { const xmlElement = buildXmlElement(e, k); - const pathParts = getPathParts( - configElement.$.parent || configElement.$.target, - ); + const pathParts = getPathParts(configElement.$.parent || configElement.$.target); if (pathParts.length > 1) { if (pathParts.pop() === 'application') { - if ( - configElement.$.mode && - configElement.$.mode === 'merge' && - xmlElement.startsWith(' { applicationXMLAttributes.push(`${ek}="${e.$[ek]}"`); }); @@ -796,15 +650,8 @@ export async function writeCordovaAndroidManifest( applicationXMLEntries.push(xmlElement); } } else { - const manifestPathOfCapApp = join( - config.android.appDirAbs, - 'src', - 'main', - 'AndroidManifest.xml', - ); - const manifestContentTrimmed = ( - await readFile(manifestPathOfCapApp) - ) + const manifestPathOfCapApp = join(config.android.appDirAbs, 'src', 'main', 'AndroidManifest.xml'); + const manifestContentTrimmed = (await readFile(manifestPathOfCapApp)) .toString() .trim() .replace(/\n|\t|\r/g, '') @@ -817,19 +664,14 @@ export async function writeCordovaAndroidManifest( .replace(/[\s]{1,}[\s]{1,}/g, '>') .replace(/[\s]{2,}/g, ' '); - const pathPartList = getPathParts( - configElement.$.parent || configElement.$.target, - ); + const pathPartList = getPathParts(configElement.$.parent || configElement.$.target); const doesXmlManifestContainRequiredInfo = ( requiredElements: any, existingElements: any, pathTarget: string[], ): boolean => { - const findElementsToSearchIn = ( - existingElements: any[], - pathTarget: string[], - ): any[] => { + const findElementsToSearchIn = (existingElements: any[], pathTarget: string[]): any[] => { const parts = [...pathTarget]; const elementsToSearchNextIn = []; for (const existingElement of existingElements) { @@ -850,23 +692,13 @@ export async function writeCordovaAndroidManifest( if (parts.length <= 0) { return elementsToSearchNextIn; } else { - return findElementsToSearchIn( - elementsToSearchNextIn, - parts, - ); + return findElementsToSearchIn(elementsToSearchNextIn, parts); } } }; - const parseXmlToSearchable = ( - childElementsObj: any, - arrayToAddTo: any[], - ) => { - for (const childElementKey of Object.keys( - childElementsObj, - )) { - for (const occurannceOfElement of childElementsObj[ - childElementKey - ]) { + const parseXmlToSearchable = (childElementsObj: any, arrayToAddTo: any[]) => { + for (const childElementKey of Object.keys(childElementsObj)) { + for (const occurannceOfElement of childElementsObj[childElementKey]) { const toAdd: { name: string; attrs?: { [key: string]: any } | undefined; @@ -877,42 +709,24 @@ export async function writeCordovaAndroidManifest( } if (occurannceOfElement['$$']) { toAdd.children = []; - parseXmlToSearchable( - occurannceOfElement['$$'], - toAdd['children'], - ); + parseXmlToSearchable(occurannceOfElement['$$'], toAdd['children']); } arrayToAddTo.push(toAdd); } } }; - const doesElementMatch = ( - requiredElement: any, - existingElement: any, - ): boolean => { + const doesElementMatch = (requiredElement: any, existingElement: any): boolean => { if (requiredElement.name !== existingElement.name) { return false; } - if ( - (requiredElement.attrs !== undefined) !== - (existingElement.attrs !== undefined) - ) { + if ((requiredElement.attrs !== undefined) !== (existingElement.attrs !== undefined)) { return false; } else { if (requiredElement.attrs !== undefined) { - const requiredELementAttrKeys = Object.keys( - requiredElement.attrs, - ); + const requiredELementAttrKeys = Object.keys(requiredElement.attrs); for (const key of requiredELementAttrKeys) { - if ( - !/^[$].{1,}$/.test( - (requiredElement.attrs[key] as string).trim(), - ) - ) { - if ( - requiredElement.attrs[key] !== - existingElement.attrs[key] - ) { + if (!/^[$].{1,}$/.test((requiredElement.attrs[key] as string).trim())) { + if (requiredElement.attrs[key] !== existingElement.attrs[key]) { return false; } } @@ -920,8 +734,7 @@ export async function writeCordovaAndroidManifest( } } if ( - (requiredElement.children !== undefined) !== - (existingElement.children !== undefined) && + (requiredElement.children !== undefined) !== (existingElement.children !== undefined) && requiredElement.children?.length !== 0 ) { return false; @@ -931,10 +744,7 @@ export async function writeCordovaAndroidManifest( for (const requiredElementItem of requiredElement.children) { let foundRequiredElement = false; for (const existingElementItem of existingElement.children) { - const foundRequiredElementIn = doesElementMatch( - requiredElementItem, - existingElementItem, - ); + const foundRequiredElementIn = doesElementMatch(requiredElementItem, existingElementItem); if (foundRequiredElementIn) { foundRequiredElement = true; break; @@ -945,18 +755,12 @@ export async function writeCordovaAndroidManifest( } } } else { - if ( - requiredElement.children === undefined && - existingElement.children === undefined - ) { + if (requiredElement.children === undefined && existingElement.children === undefined) { return true; } else { let foundRequiredElement = false; for (const existingElementItem of existingElement.children) { - const foundRequiredElementIn = doesElementMatch( - requiredElement, - existingElementItem, - ); + const foundRequiredElementIn = doesElementMatch(requiredElement, existingElementItem); if (foundRequiredElementIn) { foundRequiredElement = true; break; @@ -971,8 +775,7 @@ export async function writeCordovaAndroidManifest( return true; }; const parsedExistingElements: any[] = []; - const rootKeyOfExistingElements = - Object.keys(existingElements)[0]; + const rootKeyOfExistingElements = Object.keys(existingElements)[0]; const rootOfExistingElementsToAdd: { name: string; attrs?: { [key: string]: any } | undefined; @@ -989,8 +792,7 @@ export async function writeCordovaAndroidManifest( ); parsedExistingElements.push(rootOfExistingElementsToAdd); const parsedRequiredElements: any[] = []; - const rootKeyOfRequiredElements = - Object.keys(requiredElements)[0]; + const rootKeyOfRequiredElements = Object.keys(requiredElements)[0]; const rootOfRequiredElementsToAdd: { name: string; attrs?: { [key: string]: any } | undefined; @@ -1001,28 +803,19 @@ export async function writeCordovaAndroidManifest( ...requiredElements[rootKeyOfRequiredElements]['$'], }; } - if ( - requiredElements[rootKeyOfRequiredElements]['$$'] !== - undefined - ) { + if (requiredElements[rootKeyOfRequiredElements]['$$'] !== undefined) { parseXmlToSearchable( requiredElements[rootKeyOfRequiredElements]['$$'], rootOfRequiredElementsToAdd['children'], ); } parsedRequiredElements.push(rootOfRequiredElementsToAdd); - const elementsToSearch = findElementsToSearchIn( - parsedExistingElements, - pathTarget, - ); + const elementsToSearch = findElementsToSearchIn(parsedExistingElements, pathTarget); for (const requiredElement of parsedRequiredElements) { let foundMatch = false; for (const existingElement of elementsToSearch) { - const doesContain = doesElementMatch( - requiredElement, - existingElement, - ); + const doesContain = doesElementMatch(requiredElement, existingElement); if (doesContain) { foundMatch = true; break; @@ -1056,10 +849,7 @@ export async function writeCordovaAndroidManifest( } } } else { - if ( - !rootXMLEntries.includes(xmlElement) && - !contains(rootXMLEntries, xmlElement, k) - ) { + if (!rootXMLEntries.includes(xmlElement) && !contains(rootXMLEntries, xmlElement, k)) { rootXMLEntries.push(xmlElement); } } @@ -1070,8 +860,7 @@ export async function writeCordovaAndroidManifest( }); const cleartextString = 'android:usesCleartextTraffic="true"'; const cleartextValue = - (cleartext || config.app.extConfig.server?.cleartext) && - !applicationXMLAttributes.includes(cleartextString) + (cleartext || config.app.extConfig.server?.cleartext) && !applicationXMLAttributes.includes(cleartextString) ? cleartextString : ''; let content = ` @@ -1082,15 +871,9 @@ ${applicationXMLEntries.join('\n')} ${rootXMLEntries.join('\n')} `; - content = content.replace( - new RegExp('$PACKAGE_NAME'.replace('$', '\\$&'), 'g'), - '${applicationId}', - ); + content = content.replace(new RegExp('$PACKAGE_NAME'.replace('$', '\\$&'), 'g'), '${applicationId}'); for (const preference of prefsArray) { - content = content.replace( - new RegExp(('$' + preference.$.name).replace('$', '\\$&'), 'g'), - preference.$.default, - ); + content = content.replace(new RegExp(('$' + preference.$.name).replace('$', '\\$&'), 'g'), preference.$.default); } if (await pathExists(manifestPath)) { await writeFile(manifestPath, content); @@ -1100,7 +883,7 @@ ${rootXMLEntries.join('\n')} function getPathParts(path: string) { const rootPath = 'manifest'; path = path.replace('/*', rootPath); - const parts = path.split('/').filter(part => part !== ''); + const parts = path.split('/').filter((part) => part !== ''); if (parts.length > 1 || parts.includes(rootPath)) { return parts; } diff --git a/cli/src/errors.ts b/cli/src/errors.ts index eebc0d206..aa2d5103d 100644 --- a/cli/src/errors.ts +++ b/cli/src/errors.ts @@ -1,11 +1,17 @@ export abstract class BaseException extends Error { - constructor(readonly message: string, readonly code: T) { + constructor( + readonly message: string, + readonly code: T, + ) { super(message); } } export class FatalException extends BaseException<'FATAL'> { - constructor(readonly message: string, readonly exitCode = 1) { + constructor( + readonly message: string, + readonly exitCode = 1, + ) { super(message, 'FATAL'); } } diff --git a/cli/src/framework-configs.ts b/cli/src/framework-configs.ts index 9fce3769d..9d476bbcd 100644 --- a/cli/src/framework-configs.ts +++ b/cli/src/framework-configs.ts @@ -3,93 +3,90 @@ import type { Config, FrameworkConfig } from './definitions'; const FRAMEWORK_CONFIGS: FrameworkConfig[] = [ { name: 'Angular', - isMatch: config => hasDependency(config, '@angular/cli'), + isMatch: (config) => hasDependency(config, '@angular/cli'), webDir: 'dist', priority: 3, }, { name: 'Create React App', - isMatch: config => hasDependency(config, 'react-scripts'), + isMatch: (config) => hasDependency(config, 'react-scripts'), webDir: 'build', priority: 3, }, { name: 'Ember', - isMatch: config => hasDependency(config, 'ember-cli'), + isMatch: (config) => hasDependency(config, 'ember-cli'), webDir: 'dist', priority: 3, }, { name: 'Gatsby', - isMatch: config => hasDependency(config, 'gatsby'), + isMatch: (config) => hasDependency(config, 'gatsby'), webDir: 'public', priority: 2, }, { name: 'Ionic Angular', - isMatch: config => hasDependency(config, '@ionic/angular'), + isMatch: (config) => hasDependency(config, '@ionic/angular'), webDir: 'www', priority: 1, }, { name: 'Ionic React', - isMatch: config => hasDependency(config, '@ionic/react'), + isMatch: (config) => hasDependency(config, '@ionic/react'), webDir: 'build', priority: 1, }, { name: 'Ionic Vue', - isMatch: config => hasDependency(config, '@ionic/vue'), + isMatch: (config) => hasDependency(config, '@ionic/vue'), webDir: 'public', priority: 1, }, { name: 'Next', - isMatch: config => hasDependency(config, 'next'), + isMatch: (config) => hasDependency(config, 'next'), webDir: 'public', priority: 2, }, { name: 'Preact', - isMatch: config => hasDependency(config, 'preact-cli'), + isMatch: (config) => hasDependency(config, 'preact-cli'), webDir: 'build', priority: 3, }, { name: 'Stencil', - isMatch: config => hasDependency(config, '@stencil/core'), + isMatch: (config) => hasDependency(config, '@stencil/core'), webDir: 'www', priority: 3, }, { name: 'Svelte', - isMatch: config => - hasDependency(config, 'svelte') && hasDependency(config, 'sirv-cli'), + isMatch: (config) => hasDependency(config, 'svelte') && hasDependency(config, 'sirv-cli'), webDir: 'public', priority: 3, }, { name: 'Vite', - isMatch: config => hasDependency(config, 'vite'), + isMatch: (config) => hasDependency(config, 'vite'), webDir: 'dist', priority: 2, }, { name: 'Vue', - isMatch: config => hasDependency(config, '@vue/cli-service'), + isMatch: (config) => hasDependency(config, '@vue/cli-service'), webDir: 'dist', priority: 3, }, ]; export function detectFramework(config: Config): FrameworkConfig | undefined { - const frameworks = FRAMEWORK_CONFIGS.filter(f => f.isMatch(config)).sort( - (a, b) => { - if (a.priority < b.priority) return -1; - if (a.priority > b.priority) return 1; - return 0; - }, - ); + const frameworks = FRAMEWORK_CONFIGS.filter((f) => f.isMatch(config)).sort((a, b) => { + if (a.priority < b.priority) return -1; + if (a.priority > b.priority) return 1; + return 0; + }); return frameworks[0]; } diff --git a/cli/src/index.ts b/cli/src/index.ts index 58dae35d2..1c014fbd1 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -11,11 +11,9 @@ import { telemetryAction } from './telemetry'; import { wrapAction } from './util/cli'; import { emoji as _e } from './util/emoji'; -type Writable = T extends object - ? { -readonly [K in keyof T]: Writable } - : T; +type Writable = T extends object ? { -readonly [K in keyof T]: Writable } : T; -process.on('unhandledRejection', error => { +process.on('unhandledRejection', (error) => { console.error(c.failure('[fatal]'), error); }); @@ -58,29 +56,14 @@ export function runProgram(config: Config): void { program .command('init [appName] [appId]') .description(`Initialize Capacitor configuration`) - .option( - '--web-dir ', - 'Optional: Directory of your projects built web assets', - ) - .option( - '--skip-appid-validation', - 'Optional: Skip validating the app ID for iOS and Android compatibility', - ) + .option('--web-dir ', 'Optional: Directory of your projects built web assets') + .option('--skip-appid-validation', 'Optional: Skip validating the app ID for iOS and Android compatibility') .action( wrapAction( - telemetryAction( - config, - async (appName, appId, { webDir, skipAppidValidation }) => { - const { initCommand } = await import('./tasks/init'); - await initCommand( - config, - appName, - appId, - webDir, - skipAppidValidation, - ); - }, - ), + telemetryAction(config, async (appName, appId, { webDir, skipAppidValidation }) => { + const { initCommand } = await import('./tasks/init'); + await initCommand(config, appName, appId, webDir, skipAppidValidation); + }), ), ); @@ -97,10 +80,7 @@ export function runProgram(config: Config): void { program .command('sync [platform]') .description(`${c.input('copy')} + ${c.input('update')}`) - .option( - '--deployment', - 'Optional: if provided, pod install will use --deployment option', - ) + .option('--deployment', 'Optional: if provided, pod install will use --deployment option') .option( '--inline', 'Optional: if true, all source maps will be inlined for easier debugging on mobile devices', @@ -117,15 +97,8 @@ export function runProgram(config: Config): void { program .command('update [platform]') - .description( - `updates the native plugins and dependencies based on ${c.strong( - 'package.json', - )}`, - ) - .option( - '--deployment', - 'Optional: if provided, pod install will use --deployment option', - ) + .description(`updates the native plugins and dependencies based on ${c.strong('package.json')}`) + .option('--deployment', 'Optional: if provided, pod install will use --deployment option') .action( wrapAction( telemetryAction(config, async (platform, { deployment }) => { @@ -161,21 +134,18 @@ export function runProgram(config: Config): void { .option('--keystorepass ', 'Password to the keystore') .option('--keystorealias ', 'Key Alias in the keystore') .option('--configuration ', 'Configuration name of the iOS Scheme') - .option( - '--keystorealiaspass ', - 'Password for the Key Alias', - ) + .option('--keystorealiaspass ', 'Password for the Key Alias') .addOption( - new Option( - '--androidreleasetype ', - 'Android release type; APK or AAB', - ).choices(['AAB', 'APK']), + new Option('--androidreleasetype ', 'Android release type; APK or AAB').choices([ + 'AAB', + 'APK', + ]), ) .addOption( - new Option( - '--signing-type ', - 'Program used to sign apps (default: jarsigner)', - ).choices(['apksigner', 'jarsigner']), + new Option('--signing-type ', 'Program used to sign apps (default: jarsigner)').choices([ + 'apksigner', + 'jarsigner', + ]), ) .action( wrapAction( @@ -213,23 +183,15 @@ export function runProgram(config: Config): void { ); program .command(`run [platform]`) - .description( - `runs ${c.input('sync')}, then builds and deploys the native app`, - ) + .description(`runs ${c.input('sync')}, then builds and deploys the native app`) .option('--scheme ', 'set the scheme of the iOS project') - .option( - '--flavor ', - 'set the flavor of the Android project (flavor dimensions not yet supported)', - ) + .option('--flavor ', 'set the flavor of the Android project (flavor dimensions not yet supported)') .option('--list', 'list targets, then quit') // TODO: remove once --json is a hidden option (https://github.com/tj/commander.js/issues/1106) .allowUnknownOption(true) .option('--target ', 'use a specific target') .option('--no-sync', `do not run ${c.input('sync')}`) - .option( - '--forwardPorts ', - 'Automatically run "adb reverse" for better live-reloading support', - ) + .option('--forwardPorts ', 'Automatically run "adb reverse" for better live-reloading support') .option('-l, --live-reload', 'Enable Live Reload') .option('--host ', 'Host used for live reload') .option('--port ', 'Port used for live reload') @@ -240,18 +202,7 @@ export function runProgram(config: Config): void { config, async ( platform, - { - scheme, - flavor, - list, - target, - sync, - forwardPorts, - liveReload, - host, - port, - configuration, - }, + { scheme, flavor, list, target, sync, forwardPorts, liveReload, host, port, configuration }, ) => { const { runCommand } = await import('./tasks/run'); await runCommand(config, platform, { @@ -276,7 +227,7 @@ export function runProgram(config: Config): void { .description('opens the native project workspace (Xcode for iOS)') .action( wrapAction( - telemetryAction(config, async platform => { + telemetryAction(config, async (platform) => { const { openCommand } = await import('./tasks/open'); await openCommand(config, platform); }), @@ -297,8 +248,7 @@ export function runProgram(config: Config): void { const configWritable: Writable = config as Writable; if (packagemanager === 'SPM') { - configWritable.cli.assets.ios.platformTemplateArchive = - 'ios-spm-template.tar.gz'; + configWritable.cli.assets.ios.platformTemplateArchive = 'ios-spm-template.tar.gz'; configWritable.cli.assets.ios.platformTemplateArchiveAbs = resolve( configWritable.cli.assetsDirAbs, configWritable.cli.assets.ios.platformTemplateArchive, @@ -315,7 +265,7 @@ export function runProgram(config: Config): void { .description('list installed Cordova and Capacitor plugins') .action( wrapAction( - telemetryAction(config, async platform => { + telemetryAction(config, async (platform) => { const { listCommand } = await import('./tasks/list'); await listCommand(config, platform); }), @@ -327,7 +277,7 @@ export function runProgram(config: Config): void { .description('checks the current setup for common errors') .action( wrapAction( - telemetryAction(config, async platform => { + telemetryAction(config, async (platform) => { const { doctorCommand } = await import('./tasks/doctor'); await doctorCommand(config, platform); }), @@ -338,7 +288,7 @@ export function runProgram(config: Config): void { .command('telemetry [on|off]', { hidden: true }) .description('enable or disable telemetry') .action( - wrapAction(async onOrOff => { + wrapAction(async (onOrOff) => { const { telemetryCommand } = await import('./tasks/telemetry'); await telemetryCommand(onOrOff); }), @@ -364,13 +314,8 @@ export function runProgram(config: Config): void { program .command('migrate') .option('--noprompt', 'do not prompt for confirmation') - .option( - '--packagemanager ', - 'The package manager to use for dependency installs (npm, pnpm, yarn)', - ) - .description( - 'Migrate your current Capacitor app to the latest major version of Capacitor.', - ) + .option('--packagemanager ', 'The package manager to use for dependency installs (npm, pnpm, yarn)') + .description('Migrate your current Capacitor app to the latest major version of Capacitor.') .action( wrapAction(async ({ noprompt, packagemanager }) => { const { migrateCommand } = await import('./tasks/migrate'); @@ -379,7 +324,7 @@ export function runProgram(config: Config): void { ); program.arguments('[command]').action( - wrapAction(async cmd => { + wrapAction(async (cmd) => { if (typeof cmd === 'undefined') { output.write( `\n ${_e('โšก๏ธ', '--')} ${c.strong( diff --git a/cli/src/ios/add.ts b/cli/src/ios/add.ts index e41e7c132..aee1c2092 100644 --- a/cli/src/ios/add.ts +++ b/cli/src/ios/add.ts @@ -4,13 +4,7 @@ import type { Config } from '../definitions'; import { extractTemplate } from '../util/template'; export async function addIOS(config: Config): Promise { - await runTask( - `Adding native Xcode project in ${c.strong(config.ios.platformDir)}`, - () => { - return extractTemplate( - config.cli.assets.ios.platformTemplateArchiveAbs, - config.ios.platformDirAbs, - ); - }, - ); + await runTask(`Adding native Xcode project in ${c.strong(config.ios.platformDir)}`, () => { + return extractTemplate(config.cli.assets.ios.platformTemplateArchiveAbs, config.ios.platformDirAbs); + }); } diff --git a/cli/src/ios/build.ts b/cli/src/ios/build.ts index d79050ae5..838a4b451 100644 --- a/cli/src/ios/build.ts +++ b/cli/src/ios/build.ts @@ -9,10 +9,7 @@ import type { BuildCommandOptions } from '../tasks/build'; import { checkPackageManager } from '../util/spm'; import { runCommand } from '../util/subprocess'; -export async function buildiOS( - config: Config, - buildOptions: BuildCommandOptions, -): Promise { +export async function buildiOS(config: Config, buildOptions: BuildCommandOptions): Promise { const theScheme = buildOptions.scheme ?? 'App'; const packageManager = await checkPackageManager(config); @@ -57,10 +54,7 @@ export async function buildiOS( `; - const archivePlistPath = join( - `${config.ios.nativeProjectDirAbs}`, - 'archive.plist', - ); + const archivePlistPath = join(`${config.ios.nativeProjectDirAbs}`, 'archive.plist'); writeFileSync(archivePlistPath, archivePlistContents); @@ -91,10 +85,5 @@ export async function buildiOS( rimraf.sync(join(config.ios.nativeProjectDirAbs, `${theScheme}.xcarchive`)); }); - logSuccess( - `Successfully generated an IPA at: ${join( - config.ios.nativeProjectDirAbs, - 'output', - )}`, - ); + logSuccess(`Successfully generated an IPA at: ${join(config.ios.nativeProjectDirAbs, 'output')}`); } diff --git a/cli/src/ios/common.ts b/cli/src/ios/common.ts index 4209244bd..925ee64a4 100644 --- a/cli/src/ios/common.ts +++ b/cli/src/ios/common.ts @@ -43,24 +43,17 @@ export async function checkBundler(config: Config): Promise { } export async function checkCocoaPods(config: Config): Promise { - if ( - !(await isInstalled(await config.ios.podPath)) && - config.cli.os === OS.Mac - ) { + if (!(await isInstalled(await config.ios.podPath)) && config.cli.os === OS.Mac) { return ( `CocoaPods is not installed.\n` + - `See this install guide: ${c.strong( - 'https://capacitorjs.com/docs/getting-started/environment-setup#homebrew', - )}` + `See this install guide: ${c.strong('https://capacitorjs.com/docs/getting-started/environment-setup#homebrew')}` ); } return null; } export async function getIOSPlugins(allPlugins: Plugin[]): Promise { - const resolved = await Promise.all( - allPlugins.map(async plugin => await resolvePlugin(plugin)), - ); + const resolved = await Promise.all(allPlugins.map(async (plugin) => await resolvePlugin(plugin))); return resolved.filter((plugin): plugin is Plugin => !!plugin); } @@ -78,10 +71,7 @@ export async function resolvePlugin(plugin: Plugin): Promise { type: PluginType.Cordova, path: 'src/' + platform, }; - if ( - getIncompatibleCordovaPlugins(platform).includes(plugin.id) || - !getPluginPlatform(plugin, platform) - ) { + if (getIncompatibleCordovaPlugins(platform).includes(plugin.id) || !getPluginPlatform(plugin, platform)) { plugin.ios.type = PluginType.Incompatible; } } else { @@ -95,10 +85,7 @@ export async function resolvePlugin(plugin: Plugin): Promise { */ export async function editProjectSettingsIOS(config: Config): Promise { const appId = config.app.appId; - const appName = config.app.appName - .replace(/&/g, '&') - .replace(//g, '>'); + const appName = config.app.appName.replace(/&/g, '&').replace(//g, '>'); const pbxPath = `${config.ios.nativeXcodeProjDirAbs}/project.pbxproj`; const plistPath = resolve(config.ios.nativeTargetDirAbs, 'Info.plist'); @@ -111,10 +98,7 @@ export async function editProjectSettingsIOS(config: Config): Promise { ); let pbxContent = await readFile(pbxPath, { encoding: 'utf-8' }); - pbxContent = pbxContent.replace( - /PRODUCT_BUNDLE_IDENTIFIER = ([^;]+)/g, - `PRODUCT_BUNDLE_IDENTIFIER = ${appId}`, - ); + pbxContent = pbxContent.replace(/PRODUCT_BUNDLE_IDENTIFIER = ([^;]+)/g, `PRODUCT_BUNDLE_IDENTIFIER = ${appId}`); await writeFile(plistPath, plistContent, { encoding: 'utf-8' }); await writeFile(pbxPath, pbxContent, { encoding: 'utf-8' }); diff --git a/cli/src/ios/doctor.ts b/cli/src/ios/doctor.ts index bb9937bb2..77d9b8b17 100644 --- a/cli/src/ios/doctor.ts +++ b/cli/src/ios/doctor.ts @@ -19,11 +19,7 @@ export async function doctorIOS(config: Config): Promise { // check online datebase of common errors // check if www folder is empty (index.html does not exist) try { - await check([ - () => checkBundler(config) || checkCocoaPods(config), - () => checkWebDir(config), - checkXcode, - ]); + await check([() => checkBundler(config) || checkCocoaPods(config), () => checkWebDir(config), checkXcode]); logSuccess('iOS looking great! ๐Ÿ‘Œ'); } catch (e: any) { fatal(e.stack ?? e); diff --git a/cli/src/ios/run.ts b/cli/src/ios/run.ts index 860596361..0c414494a 100644 --- a/cli/src/ios/run.ts +++ b/cli/src/ios/run.ts @@ -13,25 +13,14 @@ const debug = Debug('capacitor:ios:run'); export async function runIOS( config: Config, - { - target: selectedTarget, - scheme: selectedScheme, - configuration: selectedConfiguration, - }: RunCommandOptions, + { target: selectedTarget, scheme: selectedScheme, configuration: selectedConfiguration }: RunCommandOptions, ): Promise { - const target = await promptForPlatformTarget( - await getPlatformTargets('ios'), - selectedTarget, - ); + const target = await promptForPlatformTarget(await getPlatformTargets('ios'), selectedTarget); const runScheme = selectedScheme || config.ios.scheme; const configuration = selectedConfiguration || 'Debug'; - const derivedDataPath = resolve( - config.ios.platformDirAbs, - 'DerivedData', - target.id, - ); + const derivedDataPath = resolve(config.ios.platformDirAbs, 'DerivedData', target.id); const packageManager = await checkPackageManager(config); @@ -71,9 +60,7 @@ export async function runIOS( const appPath = resolve( derivedDataPath, 'Build/Products', - target.virtual - ? `${configuration}-iphonesimulator` - : `${configuration}-iphoneos`, + target.virtual ? `${configuration}-iphonesimulator` : `${configuration}-iphoneos`, appName, ); @@ -81,8 +68,5 @@ export async function runIOS( debug('Invoking native-run with args: %O', nativeRunArgs); - await runTask( - `Deploying ${c.strong(appName)} to ${c.input(target.id)}`, - async () => runNativeRun(nativeRunArgs), - ); + await runTask(`Deploying ${c.strong(appName)} to ${c.input(target.id)}`, async () => runNativeRun(nativeRunArgs)); } diff --git a/cli/src/ios/update.ts b/cli/src/ios/update.ts index 7005de58f..3345bfcc4 100644 --- a/cli/src/ios/update.ts +++ b/cli/src/ios/update.ts @@ -1,21 +1,9 @@ -import { - copy, - remove, - pathExists, - readFile, - realpath, - writeFile, -} from '@ionic/utils-fs'; +import { copy, remove, pathExists, readFile, realpath, writeFile } from '@ionic/utils-fs'; import { basename, dirname, join, relative } from 'path'; import c from '../colors'; import { checkPlatformVersions, runTask } from '../common'; -import { - checkPluginDependencies, - handleCordovaPluginsJS, - logCordovaManualSteps, - needsStaticPod, -} from '../cordova'; +import { checkPluginDependencies, handleCordovaPluginsJS, logCordovaManualSteps, needsStaticPod } from '../cordova'; import type { Config } from '../definitions'; import { fatal } from '../errors'; import { logger } from '../log'; @@ -41,15 +29,10 @@ import { getIOSPlugins } from './common'; const platform = 'ios'; -export async function updateIOS( - config: Config, - deployment: boolean, -): Promise { +export async function updateIOS(config: Config, deployment: boolean): Promise { const plugins = await getPluginsTask(config); - const capacitorPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Core, - ); + const capacitorPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Core); if ((await checkPackageManager(config)) === 'SPM') { await generatePackageFile(config, capacitorPlugins); @@ -62,15 +45,9 @@ export async function updateIOS( printPlugins(capacitorPlugins, 'ios'); } -async function updateIOSCocoaPods( - config: Config, - plugins: Plugin[], - deployment: boolean, -) { +async function updateIOSCocoaPods(config: Config, plugins: Plugin[], deployment: boolean) { await removePluginsNativeFiles(config); - const cordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Cordova, - ); + const cordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); if (cordovaPlugins.length > 0) { await copyPluginsNativeFiles(config, cordovaPlugins); } @@ -83,41 +60,23 @@ async function updateIOSCocoaPods( await installCocoaPodsPlugins(config, plugins, deployment); await logCordovaManualSteps(cordovaPlugins, config, platform); - const incompatibleCordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Incompatible, - ); + const incompatibleCordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Incompatible); printPlugins(incompatibleCordovaPlugins, platform, 'incompatible'); await checkPlatformVersions(config, platform); } -export async function installCocoaPodsPlugins( - config: Config, - plugins: Plugin[], - deployment: boolean, -): Promise { - await runTask( - `Updating iOS native dependencies with ${c.input( - `${await config.ios.podPath} install`, - )}`, - () => { - return updatePodfile(config, plugins, deployment); - }, - ); +export async function installCocoaPodsPlugins(config: Config, plugins: Plugin[], deployment: boolean): Promise { + await runTask(`Updating iOS native dependencies with ${c.input(`${await config.ios.podPath} install`)}`, () => { + return updatePodfile(config, plugins, deployment); + }); } -async function updatePodfile( - config: Config, - plugins: Plugin[], - deployment: boolean, -): Promise { +async function updatePodfile(config: Config, plugins: Plugin[], deployment: boolean): Promise { const dependenciesContent = await generatePodFile(config, plugins); const relativeCapacitoriOSPath = await getRelativeCapacitoriOSPath(config); const podfilePath = join(config.ios.nativeProjectDirAbs, 'Podfile'); let podfileContent = await readFile(podfilePath, { encoding: 'utf-8' }); - podfileContent = podfileContent.replace( - /(def capacitor_pods)[\s\S]+?(\nend)/, - `$1${dependenciesContent}$2`, - ); + podfileContent = podfileContent.replace(/(def capacitor_pods)[\s\S]+?(\nend)/, `$1${dependenciesContent}$2`); podfileContent = podfileContent.replace( /(require_relative)[\s\S]+?(@capacitor\/ios\/scripts\/pods_helpers')/, `require_relative '${relativeCapacitoriOSPath}/scripts/pods_helpers'`, @@ -129,17 +88,13 @@ async function updatePodfile( const podCommandExists = await isInstalled('pod'); if (useBundler || podCommandExists) { if (useBundler) { - await runCommand( - 'bundle', - ['exec', 'pod', 'install', ...(deployment ? ['--deployment'] : [])], - { cwd: config.ios.nativeProjectDirAbs }, - ); + await runCommand('bundle', ['exec', 'pod', 'install', ...(deployment ? ['--deployment'] : [])], { + cwd: config.ios.nativeProjectDirAbs, + }); } else { - await runCommand( - podPath, - ['install', ...(deployment ? ['--deployment'] : [])], - { cwd: config.ios.nativeProjectDirAbs }, - ); + await runCommand(podPath, ['install', ...(deployment ? ['--deployment'] : [])], { + cwd: config.ios.nativeProjectDirAbs, + }); } } else { logger.warn('Skipping pod install because CocoaPods is not installed'); @@ -147,26 +102,16 @@ async function updatePodfile( const isXcodebuildAvailable = await isInstalled('xcodebuild'); if (isXcodebuildAvailable) { - await runCommand( - 'xcodebuild', - ['-project', basename(`${config.ios.nativeXcodeProjDirAbs}`), 'clean'], - { - cwd: config.ios.nativeProjectDirAbs, - }, - ); + await runCommand('xcodebuild', ['-project', basename(`${config.ios.nativeXcodeProjDirAbs}`), 'clean'], { + cwd: config.ios.nativeProjectDirAbs, + }); } else { - logger.warn( - 'Unable to find "xcodebuild". Skipping xcodebuild clean step...', - ); + logger.warn('Unable to find "xcodebuild". Skipping xcodebuild clean step...'); } } async function getRelativeCapacitoriOSPath(config: Config) { - const capacitoriOSPath = resolveNode( - config.app.rootDir, - '@capacitor/ios', - 'package.json', - ); + const capacitoriOSPath = resolveNode(config.app.rootDir, '@capacitor/ios', 'package.json'); if (!capacitoriOSPath) { fatal( @@ -175,25 +120,15 @@ async function getRelativeCapacitoriOSPath(config: Config) { ); } - return convertToUnixPath( - relative( - config.ios.nativeProjectDirAbs, - await realpath(dirname(capacitoriOSPath)), - ), - ); + return convertToUnixPath(relative(config.ios.nativeProjectDirAbs, await realpath(dirname(capacitoriOSPath)))); } -async function generatePodFile( - config: Config, - plugins: Plugin[], -): Promise { +async function generatePodFile(config: Config, plugins: Plugin[]): Promise { const relativeCapacitoriOSPath = await getRelativeCapacitoriOSPath(config); - const capacitorPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Core, - ); + const capacitorPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Core); const pods = await Promise.all( - capacitorPlugins.map(async p => { + capacitorPlugins.map(async (p) => { if (!p.ios) { return ''; } @@ -203,10 +138,8 @@ async function generatePodFile( )}'\n`; }), ); - const cordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Cordova, - ); - cordovaPlugins.map(async p => { + const cordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); + cordovaPlugins.map(async (p) => { const podspecs = getPlatformElement(p, platform, 'podspec'); podspecs.map((podspec: any) => { podspec.pods.map((pPods: any) => { @@ -220,33 +153,23 @@ async function generatePodFile( } else if (pod.$.commit) { gitRef = `, :commit => '${pod.$.commit}'`; } - pods.push( - ` pod '${pod.$.name}', :git => '${pod.$.git}'${gitRef}\n`, - ); + pods.push(` pod '${pod.$.name}', :git => '${pod.$.git}'${gitRef}\n`); } }); }); }); }); - const staticPlugins = cordovaPlugins.filter(p => needsStaticPod(p)); - const noStaticPlugins = cordovaPlugins.filter( - el => !staticPlugins.includes(el), - ); + const staticPlugins = cordovaPlugins.filter((p) => needsStaticPod(p)); + const noStaticPlugins = cordovaPlugins.filter((el) => !staticPlugins.includes(el)); if (noStaticPlugins.length > 0) { - pods.push( - ` pod 'CordovaPlugins', :path => '../capacitor-cordova-ios-plugins'\n`, - ); + pods.push(` pod 'CordovaPlugins', :path => '../capacitor-cordova-ios-plugins'\n`); } if (staticPlugins.length > 0) { - pods.push( - ` pod 'CordovaPluginsStatic', :path => '../capacitor-cordova-ios-plugins'\n`, - ); + pods.push(` pod 'CordovaPluginsStatic', :path => '../capacitor-cordova-ios-plugins'\n`); } const resourcesPlugins = cordovaPlugins.filter(filterResources); if (resourcesPlugins.length > 0) { - pods.push( - ` pod 'CordovaPluginsResources', :path => '../capacitor-cordova-ios-plugins'\n`, - ); + pods.push(` pod 'CordovaPluginsResources', :path => '../capacitor-cordova-ios-plugins'\n`); } return ` pod 'Capacitor', :path => '${relativeCapacitoriOSPath}' @@ -261,32 +184,21 @@ function getFrameworkName(framework: any) { } return framework.$.src.substr(0, framework.$.src.indexOf('.')); } - return framework.$.src - .substr(0, framework.$.src.indexOf('.')) - .replace('lib', ''); + return framework.$.src.substr(0, framework.$.src.indexOf('.')).replace('lib', ''); } function isFramework(framework: any) { return framework.$.src.split('.').pop().includes('framework'); } -async function generateCordovaPodspecs( - cordovaPlugins: Plugin[], - config: Config, -) { - const staticPlugins = cordovaPlugins.filter(p => needsStaticPod(p)); - const noStaticPlugins = cordovaPlugins.filter( - el => !staticPlugins.includes(el), - ); +async function generateCordovaPodspecs(cordovaPlugins: Plugin[], config: Config) { + const staticPlugins = cordovaPlugins.filter((p) => needsStaticPod(p)); + const noStaticPlugins = cordovaPlugins.filter((el) => !staticPlugins.includes(el)); generateCordovaPodspec(noStaticPlugins, config, false); generateCordovaPodspec(staticPlugins, config, true); } -async function generateCordovaPodspec( - cordovaPlugins: Plugin[], - config: Config, - isStatic: boolean, -) { +async function generateCordovaPodspec(cordovaPlugins: Plugin[], config: Config, isStatic: boolean) { const weakFrameworks: string[] = []; const linkedFrameworks: string[] = []; const customFrameworks: string[] = []; @@ -337,9 +249,7 @@ async function generateCordovaPodspec( } } }); - prefsArray = prefsArray.concat( - getAllElements(plugin, platform, 'preference'), - ); + prefsArray = prefsArray.concat(getAllElements(plugin, platform, 'preference')); const podspecs = getPlatformElement(plugin, platform, 'podspec'); podspecs.map((podspec: any) => { podspec.pods.map((pods: any) => { @@ -373,9 +283,7 @@ async function generateCordovaPodspec( } }); }); - const onlySystemLibraries = systemLibraries.filter(library => - removeNoSystem(library, sourceFrameworks), - ); + const onlySystemLibraries = systemLibraries.filter((library) => removeNoSystem(library, sourceFrameworks)); if (weakFrameworks.length > 0) { frameworkDeps.push(`s.weak_frameworks = '${weakFrameworks.join(`', '`)}'`); } @@ -386,17 +294,13 @@ async function generateCordovaPodspec( frameworkDeps.push(`s.libraries = '${onlySystemLibraries.join(`', '`)}'`); } if (customFrameworks.length > 0) { - frameworkDeps.push( - `s.vendored_frameworks = '${customFrameworks.join(`', '`)}'`, - ); + frameworkDeps.push(`s.vendored_frameworks = '${customFrameworks.join(`', '`)}'`); frameworkDeps.push( `s.exclude_files = 'sources/**/*.framework/Headers/*.h', 'sources/**/*.framework/PrivateHeaders/*.h'`, ); } if (sourceFrameworks.length > 0) { - frameworkDeps.push( - `s.vendored_libraries = '${sourceFrameworks.join(`', '`)}'`, - ); + frameworkDeps.push(`s.vendored_libraries = '${sourceFrameworks.join(`', '`)}'`); } if (compilerFlags.length > 0) { frameworkDeps.push(`s.compiler_flags = '${compilerFlags.join(' ')}'`); @@ -409,11 +313,7 @@ async function generateCordovaPodspec( end`); } let frameworksString = frameworkDeps.join('\n '); - frameworksString = await replaceFrameworkVariables( - config, - prefsArray, - frameworksString, - ); + frameworksString = await replaceFrameworkVariables(config, prefsArray, frameworksString); const content = ` Pod::Spec.new do |s| s.name = '${name}' @@ -422,9 +322,7 @@ async function generateCordovaPodspec( s.license = 'Unknown' s.homepage = 'https://example.com' s.authors = { 'Capacitor Generator' => 'hi@example.com' } - s.source = { :git => 'https://github.com/ionic-team/does-not-exist.git', :tag => '${ - config.cli.package.version - }' } + s.source = { :git => 'https://github.com/ionic-team/does-not-exist.git', :tag => '${config.cli.package.version}' } s.source_files = '${sourcesFolderName}/**/*.{swift,h,m,c,cc,mm,cpp}' s.ios.deployment_target = '${config.ios.minVersion}' s.xcconfig = {'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) COCOAPODS=1 WK_WEB_VIEW_ONLY=1' } @@ -432,10 +330,7 @@ async function generateCordovaPodspec( s.swift_version = '5.1' ${frameworksString} end`; - await writeFile( - join(config.ios.cordovaPluginsDirAbs, `${name}.podspec`), - content, - ); + await writeFile(join(config.ios.cordovaPluginsDirAbs, `${name}.podspec`), content); } function getLinkerFlags(config: Config) { @@ -447,10 +342,7 @@ function getLinkerFlags(config: Config) { return ''; } -async function copyPluginsNativeFiles( - config: Config, - cordovaPlugins: Plugin[], -) { +async function copyPluginsNativeFiles(config: Config, cordovaPlugins: Plugin[]) { for (const p of cordovaPlugins) { const sourceFiles = getPlatformElement(p, platform, 'source-file'); const headerFiles = getPlatformElement(p, platform, 'header-file'); @@ -460,11 +352,7 @@ async function copyPluginsNativeFiles( if (needsStaticPod(p)) { sourcesFolderName += 'static'; } - const sourcesFolder = join( - config.ios.cordovaPluginsDirAbs, - sourcesFolderName, - p.name, - ); + const sourcesFolder = join(config.ios.cordovaPluginsDirAbs, sourcesFolderName, p.name); for (const codeFile of codeFiles) { let fileName = codeFile.$.src.split('/').pop(); const fileExt = codeFile.$.src.split('.').pop(); @@ -472,19 +360,11 @@ async function copyPluginsNativeFiles( fileName = 'lib' + fileName; } let destFolder = sourcesFolderName; - if ( - codeFile.$['compiler-flags'] && - codeFile.$['compiler-flags'] === '-fno-objc-arc' - ) { + if (codeFile.$['compiler-flags'] && codeFile.$['compiler-flags'] === '-fno-objc-arc') { destFolder = 'noarc'; } const filePath = getFilePath(config, p, codeFile.$.src); - const fileDest = join( - config.ios.cordovaPluginsDirAbs, - destFolder, - p.name, - fileName, - ); + const fileDest = join(config.ios.cordovaPluginsDirAbs, destFolder, p.name, fileName); await copy(filePath, fileDest); if (!codeFile.$.framework) { let fileContent = await readFile(fileDest, { encoding: 'utf-8' }); @@ -493,38 +373,20 @@ async function copyPluginsNativeFiles( await writeFile(fileDest, fileContent, { encoding: 'utf-8' }); } else { if (fileContent.includes('@import Firebase;')) { - fileContent = fileContent.replace( - '@import Firebase;', - '#import ', - ); + fileContent = fileContent.replace('@import Firebase;', '#import '); await writeFile(fileDest, fileContent, { encoding: 'utf-8' }); } if ( fileContent.includes('[NSBundle bundleForClass:[self class]]') || fileContent.includes('[NSBundle bundleForClass:[CDVCapture class]]') ) { - fileContent = fileContent.replace( - '[NSBundle bundleForClass:[self class]]', - '[NSBundle mainBundle]', - ); - fileContent = fileContent.replace( - '[NSBundle bundleForClass:[CDVCapture class]]', - '[NSBundle mainBundle]', - ); + fileContent = fileContent.replace('[NSBundle bundleForClass:[self class]]', '[NSBundle mainBundle]'); + fileContent = fileContent.replace('[NSBundle bundleForClass:[CDVCapture class]]', '[NSBundle mainBundle]'); await writeFile(fileDest, fileContent, { encoding: 'utf-8' }); } - if ( - fileContent.includes('[self.webView superview]') || - fileContent.includes('self.webView.superview') - ) { - fileContent = fileContent.replace( - /\[self.webView superview\]/g, - 'self.viewController.view', - ); - fileContent = fileContent.replace( - /self.webView.superview/g, - 'self.viewController.view', - ); + if (fileContent.includes('[self.webView superview]') || fileContent.includes('self.webView.superview')) { + fileContent = fileContent.replace(/\[self.webView superview\]/g, 'self.viewController.view'); + fileContent = fileContent.replace(/self.webView.superview/g, 'self.viewController.view'); await writeFile(fileDest, fileContent, { encoding: 'utf-8' }); } } @@ -540,10 +402,7 @@ async function copyPluginsNativeFiles( } for (const framework of frameworks) { if (framework.$.custom && framework.$.custom === 'true') { - await copy( - getFilePath(config, p, framework.$.src), - join(sourcesFolder, framework.$.src), - ); + await copy(getFilePath(config, p, framework.$.src), join(sourcesFolder, framework.$.src)); } } } @@ -551,10 +410,7 @@ async function copyPluginsNativeFiles( async function removePluginsNativeFiles(config: Config) { await remove(config.ios.cordovaPluginsDirAbs); - await extractTemplate( - config.cli.assets.ios.cordovaPluginsTemplateArchiveAbs, - config.ios.cordovaPluginsDirAbs, - ); + await extractTemplate(config.cli.assets.ios.cordovaPluginsTemplateArchiveAbs, config.ios.cordovaPluginsDirAbs); } function filterResources(plugin: Plugin) { @@ -565,17 +421,13 @@ function filterResources(plugin: Plugin) { function filterARCFiles(plugin: Plugin) { const sources = getPlatformElement(plugin, platform, 'source-file'); const sourcesARC = sources.filter( - (sourceFile: any) => - sourceFile.$['compiler-flags'] && - sourceFile.$['compiler-flags'] === '-fno-objc-arc', + (sourceFile: any) => sourceFile.$['compiler-flags'] && sourceFile.$['compiler-flags'] === '-fno-objc-arc', ); return sourcesARC.length > 0; } function removeNoSystem(library: string, sourceFrameworks: string[]) { - const libraries = sourceFrameworks.filter(framework => - framework.includes(library), - ); + const libraries = sourceFrameworks.filter((framework) => framework.includes(library)); return libraries.length === 0; } @@ -587,11 +439,7 @@ async function getPluginsTask(config: Config) { }); } -async function replaceFrameworkVariables( - config: Config, - prefsArray: any[], - frameworkString: string, -) { +async function replaceFrameworkVariables(config: Config, prefsArray: any[], frameworkString: string) { prefsArray.map((preference: any) => { frameworkString = frameworkString.replace( new RegExp(('$' + preference.$.name).replace('$', '\\$&'), 'g'), diff --git a/cli/src/ipc.ts b/cli/src/ipc.ts index 2344ff054..4bf1668ff 100644 --- a/cli/src/ipc.ts +++ b/cli/src/ipc.ts @@ -24,11 +24,7 @@ export async function send(msg: IPCMessage): Promise { await mkdirp(dir); const logPath = resolve(dir, 'ipc.log'); - debug( - 'Sending %O IPC message to forked process (logs: %O)', - msg.type, - logPath, - ); + debug('Sending %O IPC message to forked process (logs: %O)', msg.type, logPath); const fd = await open(logPath, 'a'); const p = fork(process.argv[1], ['๐Ÿ“ก'], { stdio: ['ignore', fd, fd, 'ipc'] }); @@ -61,19 +57,12 @@ export async function receive(msg: IPCMessage): Promise { 'Content-Type': 'application/json', }, }, - response => { - debug( - 'Sent %O metric to events service (status: %O)', - data.name, - response.statusCode, - ); + (response) => { + debug('Sent %O metric to events service (status: %O)', data.name, response.statusCode); if (response.statusCode !== 204) { - response.on('data', chunk => { - debug( - 'Bad response from events service. Request body: %O', - chunk.toString(), - ); + response.on('data', (chunk) => { + debug('Bad response from events service. Request body: %O', chunk.toString()); }); } }, diff --git a/cli/src/log.ts b/cli/src/log.ts index a43ea83f8..0092d9e5e 100644 --- a/cli/src/log.ts +++ b/cli/src/log.ts @@ -15,9 +15,7 @@ const options = { stream: process.argv.includes('--json') ? process.stderr : process.stdout, }; -export const output = isInteractive() - ? new TTYOutputStrategy(options) - : new StreamOutputStrategy(options); +export const output = isInteractive() ? new TTYOutputStrategy(options) : new StreamOutputStrategy(options); export const logger = createDefaultLogger({ output, @@ -32,10 +30,7 @@ export const logger = createDefaultLogger({ }, }); -export async function logPrompt( - msg: string, - promptObject: PromptObject, -): Promise> { +export async function logPrompt(msg: string, promptObject: PromptObject): Promise> { const { wordWrap } = await import('@ionic/cli-framework-output'); const { prompt } = await import('prompts'); diff --git a/cli/src/plugin.ts b/cli/src/plugin.ts index e04c63d35..b5b98c996 100644 --- a/cli/src/plugin.ts +++ b/cli/src/plugin.ts @@ -42,10 +42,7 @@ export interface Plugin { }; } -export function getIncludedPluginPackages( - config: Config, - platform: string, -): readonly string[] | undefined { +export function getIncludedPluginPackages(config: Config, platform: string): readonly string[] | undefined { const { extConfig } = config.app; switch (platform) { @@ -56,30 +53,18 @@ export function getIncludedPluginPackages( } } -export async function getPlugins( - config: Config, - platform: string, -): Promise { - const possiblePlugins = - getIncludedPluginPackages(config, platform) ?? getDependencies(config); - const resolvedPlugins = await Promise.all( - possiblePlugins.map(async p => resolvePlugin(config, p)), - ); +export async function getPlugins(config: Config, platform: string): Promise { + const possiblePlugins = getIncludedPluginPackages(config, platform) ?? getDependencies(config); + const resolvedPlugins = await Promise.all(possiblePlugins.map(async (p) => resolvePlugin(config, p))); return resolvedPlugins.filter((p): p is Plugin => !!p); } -export async function resolvePlugin( - config: Config, - name: string, -): Promise { +export async function resolvePlugin(config: Config, name: string): Promise { try { const packagePath = resolveNode(config.app.rootDir, name, 'package.json'); if (!packagePath) { - fatal( - `Unable to find ${c.strong(`node_modules/${name}`)}.\n` + - `Are you sure ${c.strong(name)} is installed?`, - ); + fatal(`Unable to find ${c.strong(`node_modules/${name}`)}.\n` + `Are you sure ${c.strong(name)} is installed?`); } const rootPath = dirname(packagePath); @@ -125,7 +110,7 @@ export function fixName(name: string): string { .replace(/\//g, '_') .replace(/-/g, '_') .replace(/@/g, '') - .replace(/_\w/g, m => m[1].toUpperCase()); + .replace(/_\w/g, (m) => m[1].toUpperCase()); return name.charAt(0).toUpperCase() + name.slice(1); } @@ -144,25 +129,19 @@ export function printPlugins( switch (type) { case 'cordova': - msg = `Found ${plugins.length} Cordova plugin${plural} for ${c.strong( - platform, - )}:\n`; + msg = `Found ${plugins.length} Cordova plugin${plural} for ${c.strong(platform)}:\n`; break; case 'incompatible': - msg = `Found ${ - plugins.length - } incompatible Cordova plugin${plural} for ${c.strong( + msg = `Found ${plugins.length} incompatible Cordova plugin${plural} for ${c.strong( platform, )}, skipped install:\n`; break; case 'capacitor': - msg = `Found ${plugins.length} Capacitor plugin${plural} for ${c.strong( - platform, - )}:\n`; + msg = `Found ${plugins.length} Capacitor plugin${plural} for ${c.strong(platform)}:\n`; break; } - msg += plugins.map(p => `${p.id}${c.weak(`@${p.version}`)}`).join('\n'); + msg += plugins.map((p) => `${p.id}${c.weak(`@${p.version}`)}`).join('\n'); logger.info(msg); } @@ -178,11 +157,7 @@ export function getPluginPlatform(p: Plugin, platform: string): any { return []; } -export function getPlatformElement( - p: Plugin, - platform: string, - elementName: string, -): any { +export function getPlatformElement(p: Plugin, platform: string, elementName: string): any { const platformTag = getPluginPlatform(p, platform); if (platformTag) { const element = platformTag[elementName]; @@ -218,18 +193,11 @@ export function getAssets(p: Plugin, platform: string): any { return getAllElements(p, platform, 'asset'); } -export function getFilePath( - config: Config, - plugin: Plugin, - path: string, -): string { +export function getFilePath(config: Config, plugin: Plugin, path: string): string { if (path.startsWith('node_modules')) { let pathSegments = path.split('/').slice(1); if (pathSegments[0].startsWith('@')) { - pathSegments = [ - pathSegments[0] + '/' + pathSegments[1], - ...pathSegments.slice(2), - ]; + pathSegments = [pathSegments[0] + '/' + pathSegments[1], ...pathSegments.slice(2)]; } const filePath = resolveNode(config.app.rootDir, ...pathSegments); @@ -245,11 +213,7 @@ export function getFilePath( /** * For a given plugin, return all the plugin.xml elements with elementName, checking root and specified platform */ -export function getAllElements( - p: Plugin, - platform: string, - elementName: string, -): any { +export function getAllElements(p: Plugin, platform: string, elementName: string): any { let modules: string[] = []; if (p.xml[elementName]) { modules = modules.concat(p.xml[elementName]); diff --git a/cli/src/tasks/add.ts b/cli/src/tasks/add.ts index e64fc458a..5227650d4 100644 --- a/cli/src/tasks/add.ts +++ b/cli/src/tasks/add.ts @@ -2,10 +2,7 @@ import { pathExists } from '@ionic/utils-fs'; import { prettyPath } from '@ionic/utils-terminal'; import { addAndroid, createLocalProperties } from '../android/add'; -import { - editProjectSettingsAndroid, - checkAndroidPackage, -} from '../android/common'; +import { editProjectSettingsAndroid, checkAndroidPackage } from '../android/common'; import c from '../colors'; import { getKnownPlatforms, @@ -25,29 +22,16 @@ import type { CheckFunction } from '../common'; import type { Config } from '../definitions'; import { fatal, isFatal } from '../errors'; import { addIOS } from '../ios/add'; -import { - editProjectSettingsIOS, - checkBundler, - checkCocoaPods, - checkIOSPackage, -} from '../ios/common'; +import { editProjectSettingsIOS, checkBundler, checkCocoaPods, checkIOSPackage } from '../ios/common'; import { logger, logSuccess, output } from '../log'; import { sync } from './sync'; -export async function addCommand( - config: Config, - selectedPlatformName: string, -): Promise { +export async function addCommand(config: Config, selectedPlatformName: string): Promise { if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) { const platformDir = resolvePlatform(config, selectedPlatformName); if (platformDir) { - await runPlatformHook( - config, - selectedPlatformName, - platformDir, - 'capacitor:add', - ); + await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:add'); } else { let msg = `Platform ${c.input(selectedPlatformName)} not found.`; @@ -78,10 +62,7 @@ export async function addCommand( return; } - const existingPlatformDir = await getProjectPlatformDirectory( - config, - platformName, - ); + const existingPlatformDir = await getProjectPlatformDirectory(config, platformName); if (existingPlatformDir) { fatal( @@ -89,18 +70,12 @@ export async function addCommand( `To re-add this platform, first remove ${c.strong( prettyPath(existingPlatformDir), )}, then run this command again.\n` + - `${c.strong( - 'WARNING', - )}: Your native project will be completely removed.`, + `${c.strong('WARNING')}: Your native project will be completely removed.`, ); } try { - await check([ - () => checkPackage(), - () => checkAppConfig(config), - ...addChecks(config, platformName), - ]); + await check([() => checkPackage(), () => checkAppConfig(config), ...addChecks(config, platformName)]); await doAdd(config, platformName); await editPlatforms(config, platformName); @@ -112,11 +87,7 @@ export async function addCommand( }); } } else { - logger.warn( - `${c.success(c.strong('sync'))} could not run--missing ${c.strong( - config.app.webDir, - )} directory.`, - ); + logger.warn(`${c.success(c.strong('sync'))} could not run--missing ${c.strong(config.app.webDir)} directory.`); } printNextSteps(platformName); @@ -141,10 +112,7 @@ function printNextSteps(platformName: string) { function addChecks(config: Config, platformName: string): CheckFunction[] { if (platformName === config.ios.name) { - return [ - () => checkIOSPackage(config), - () => checkBundler(config) || checkCocoaPods(config), - ]; + return [() => checkIOSPackage(config), () => checkBundler(config) || checkCocoaPods(config)]; } else if (platformName === config.android.name) { return [() => checkAndroidPackage(config)]; } else if (platformName === config.web.name) { diff --git a/cli/src/tasks/build.ts b/cli/src/tasks/build.ts index 0bc1a8053..783600624 100644 --- a/cli/src/tasks/build.ts +++ b/cli/src/tasks/build.ts @@ -35,23 +35,12 @@ export async function buildCommand( const buildCommandOptions: BuildCommandOptions = { scheme: buildOptions.scheme || config.ios.scheme, flavor: buildOptions.flavor || config.android.flavor, - keystorepath: - buildOptions.keystorepath || config.android.buildOptions.keystorePath, - keystorepass: - buildOptions.keystorepass || config.android.buildOptions.keystorePassword, - keystorealias: - buildOptions.keystorealias || config.android.buildOptions.keystoreAlias, - keystorealiaspass: - buildOptions.keystorealiaspass || - config.android.buildOptions.keystoreAliasPassword, - androidreleasetype: - buildOptions.androidreleasetype || - config.android.buildOptions.releaseType || - 'AAB', - signingtype: - buildOptions.signingtype || - config.android.buildOptions.signingType || - 'jarsigner', + keystorepath: buildOptions.keystorepath || config.android.buildOptions.keystorePath, + keystorepass: buildOptions.keystorepass || config.android.buildOptions.keystorePassword, + keystorealias: buildOptions.keystorealias || config.android.buildOptions.keystoreAlias, + keystorealiaspass: buildOptions.keystorealiaspass || config.android.buildOptions.keystoreAliasPassword, + androidreleasetype: buildOptions.androidreleasetype || config.android.buildOptions.releaseType || 'AAB', + signingtype: buildOptions.signingtype || config.android.buildOptions.signingType || 'jarsigner', configuration: buildOptions.configuration || 'Release', }; @@ -65,11 +54,7 @@ export async function buildCommand( } } -export async function build( - config: Config, - platformName: string, - buildOptions: BuildCommandOptions, -): Promise { +export async function build(config: Config, platformName: string, buildOptions: BuildCommandOptions): Promise { if (platformName == config.ios.name) { await buildiOS(config, buildOptions); } else if (platformName === config.android.name) { @@ -81,9 +66,6 @@ export async function build( } } -function createBuildablePlatformFilter( - config: Config, -): (platform: string) => boolean { - return platform => - platform === config.ios.name || platform === config.android.name; +function createBuildablePlatformFilter(config: Config): (platform: string) => boolean { + return (platform) => platform === config.ios.name || platform === config.android.name; } diff --git a/cli/src/tasks/config.ts b/cli/src/tasks/config.ts index 923335aa3..bebdf75ab 100644 --- a/cli/src/tasks/config.ts +++ b/cli/src/tasks/config.ts @@ -3,28 +3,18 @@ import util from 'util'; import type { Config } from '../definitions'; import { output } from '../log'; -export async function configCommand( - config: Config, - json: boolean, -): Promise { +export async function configCommand(config: Config, json: boolean): Promise { const evaluatedConfig = await deepAwait(config); if (json) { process.stdout.write(`${JSON.stringify(evaluatedConfig)}\n`); } else { - output.write( - `${util.inspect(evaluatedConfig, { depth: Infinity, colors: true })}\n`, - ); + output.write(`${util.inspect(evaluatedConfig, { depth: Infinity, colors: true })}\n`); } } async function deepAwait(obj: any): Promise { - if ( - obj && - !Array.isArray(obj) && - typeof obj === 'object' && - obj.constructor === Object - ) { + if (obj && !Array.isArray(obj) && typeof obj === 'object' && obj.constructor === Object) { const o: any = {}; for (const [k, v] of Object.entries(obj)) { diff --git a/cli/src/tasks/copy.ts b/cli/src/tasks/copy.ts index a1b7c4835..bb1f4f2f7 100644 --- a/cli/src/tasks/copy.ts +++ b/cli/src/tasks/copy.ts @@ -11,11 +11,7 @@ import { isValidPlatform, selectPlatforms, } from '../common'; -import { - getCordovaPlugins, - handleCordovaPluginsJS, - writeCordovaAndroidManifest, -} from '../cordova'; +import { getCordovaPlugins, handleCordovaPluginsJS, writeCordovaAndroidManifest } from '../cordova'; import type { Config } from '../definitions'; import { isFatal } from '../errors'; import { getIOSPlugins } from '../ios/common'; @@ -26,29 +22,18 @@ import { allSerial } from '../util/promise'; import { inlineSourceMaps } from './sourcemaps'; -export async function copyCommand( - config: Config, - selectedPlatformName: string, - inline = false, -): Promise { +export async function copyCommand(config: Config, selectedPlatformName: string, inline = false): Promise { if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) { const platformDir = resolvePlatform(config, selectedPlatformName); if (platformDir) { - await runPlatformHook( - config, - selectedPlatformName, - platformDir, - 'capacitor:copy', - ); + await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:copy'); } else { logger.error(`Platform ${c.input(selectedPlatformName)} not found.`); } } else { const platforms = await selectPlatforms(config, selectedPlatformName); try { - await allSerial( - platforms.map(platformName => () => copy(config, platformName, inline)), - ); + await allSerial(platforms.map((platformName) => () => copy(config, platformName, inline))); } catch (e: any) { if (isFatal(e)) { throw e; @@ -59,47 +44,28 @@ export async function copyCommand( } } -export async function copy( - config: Config, - platformName: string, - inline = false, -): Promise { +export async function copy(config: Config, platformName: string, inline = false): Promise { await runTask(c.success(c.strong(`copy ${platformName}`)), async () => { const result = await checkWebDir(config); if (result) { throw result; } - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:copy:before', - ); + await runHooks(config, platformName, config.app.rootDir, 'capacitor:copy:before'); const allPlugins = await getPlugins(config, platformName); let usesFederatedCapacitor = false; - if ( - allPlugins.filter( - plugin => plugin.id === '@ionic-enterprise/federated-capacitor', - ).length > 0 - ) { + if (allPlugins.filter((plugin) => plugin.id === '@ionic-enterprise/federated-capacitor').length > 0) { usesFederatedCapacitor = true; } let usesLiveUpdates = false; - if ( - allPlugins.filter(plugin => plugin.id === '@capacitor/live-updates') - .length > 0 - ) { + if (allPlugins.filter((plugin) => plugin.id === '@capacitor/live-updates').length > 0) { usesLiveUpdates = true; } let usesSSLPinning = false; - if ( - allPlugins.filter(plugin => plugin.id === '@ionic-enterprise/ssl-pinning') - .length > 0 - ) { + if (allPlugins.filter((plugin) => plugin.id === '@ionic-enterprise/ssl-pinning').length > 0) { usesSSLPinning = true; } @@ -114,11 +80,7 @@ export async function copy( ); } } else { - await copyWebDir( - config, - await config.ios.webDirAbs, - config.app.webDirAbs, - ); + await copyWebDir(config, await config.ios.webDirAbs, config.app.webDirAbs); } if (usesLiveUpdates && config.app.extConfig?.plugins?.LiveUpdates?.key) { await copySecureLiveUpdatesKey( @@ -150,11 +112,7 @@ export async function copy( ); } } else { - await copyWebDir( - config, - config.android.webDirAbs, - config.app.webDirAbs, - ); + await copyWebDir(config, config.android.webDirAbs, config.app.webDirAbs); } if (usesLiveUpdates && config.app.extConfig?.plugins?.LiveUpdates?.key) { await copySecureLiveUpdatesKey( @@ -176,9 +134,7 @@ export async function copy( await writeCordovaAndroidManifest(cordovaPlugins, config, platformName); } else if (platformName === config.web.name) { if (usesFederatedCapacitor) { - logger.info( - 'FederatedCapacitor Plugin installed, skipping web bundling...', - ); + logger.info('FederatedCapacitor Plugin installed, skipping web bundling...'); } } else { throw `Platform ${platformName} is not valid.`; @@ -188,12 +144,7 @@ export async function copy( } }); - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:copy:after', - ); + await runHooks(config, platformName, config.app.rootDir, 'capacitor:copy:after'); } async function copyCapacitorConfig(config: Config, nativeAbsDir: string) { @@ -201,33 +152,22 @@ async function copyCapacitorConfig(config: Config, nativeAbsDir: string) { const nativeConfigFile = 'capacitor.config.json'; const nativeConfigFilePath = join(nativeAbsDir, nativeConfigFile); - await runTask( - `Creating ${c.strong(nativeConfigFile)} in ${nativeRelDir}`, - async () => { - delete (config.app.extConfig.android as any)?.buildOptions; - await writeJSON(nativeConfigFilePath, config.app.extConfig, { - spaces: '\t', - }); - }, - ); + await runTask(`Creating ${c.strong(nativeConfigFile)} in ${nativeRelDir}`, async () => { + delete (config.app.extConfig.android as any)?.buildOptions; + await writeJSON(nativeConfigFilePath, config.app.extConfig, { + spaces: '\t', + }); + }); } -async function copyWebDir( - config: Config, - nativeAbsDir: string, - webAbsDir: string, -) { +async function copyWebDir(config: Config, nativeAbsDir: string, webAbsDir: string) { const webRelDir = basename(webAbsDir); const nativeRelDir = relative(config.app.rootDir, nativeAbsDir); if (config.app.extConfig.server?.url && !(await pathExists(webAbsDir))) { logger.warn( - `Cannot copy web assets from ${c.strong( - webRelDir, - )} to ${nativeRelDir}\n` + - `Web asset directory specified by ${c.input( - 'webDir', - )} does not exist. This is not an error because ${c.input( + `Cannot copy web assets from ${c.strong(webRelDir)} to ${nativeRelDir}\n` + + `Web asset directory specified by ${c.input('webDir')} does not exist. This is not an error because ${c.input( 'server.url', )} is set in config.`, ); @@ -235,13 +175,10 @@ async function copyWebDir( return; } - await runTask( - `Copying web assets from ${c.strong(webRelDir)} to ${nativeRelDir}`, - async () => { - await remove(nativeAbsDir); - return fsCopy(webAbsDir, nativeAbsDir); - }, - ); + await runTask(`Copying web assets from ${c.strong(webRelDir)} to ${nativeRelDir}`, async () => { + await remove(nativeAbsDir); + return fsCopy(webAbsDir, nativeAbsDir); + }); } async function copyFederatedWebDirs(config: Config, nativeAbsDir: string) { @@ -262,18 +199,14 @@ async function copyFederatedWebDirs(config: Config, nativeAbsDir: string) { } const copyApps = (): Promise[] => { - return federatedConfig.apps.map(app => { + return federatedConfig.apps.map((app) => { const appDir = resolve(config.app.rootDir, app.webDir); return copyWebDir(config, resolve(nativeAbsDir, app.name), appDir); }); }; const copyShell = (): Promise => { - return copyWebDir( - config, - resolve(nativeAbsDir, federatedConfig.shell.name), - config.app.webDirAbs, - ); + return copyWebDir(config, resolve(nativeAbsDir, federatedConfig.shell.name), config.app.webDirAbs); }; await Promise.all([...copyApps(), copyShell()]); @@ -281,26 +214,17 @@ async function copyFederatedWebDirs(config: Config, nativeAbsDir: string) { } function isFederatedApp(config: any): config is FederatedApp { - return ( - (config as FederatedApp).webDir !== undefined && - (config as FederatedApp).name !== undefined - ); + return (config as FederatedApp).webDir !== undefined && (config as FederatedApp).name !== undefined; } -async function copySecureLiveUpdatesKey( - secureLiveUpdatesKeyFile: string, - rootDir: string, - nativeAbsDir: string, -) { +async function copySecureLiveUpdatesKey(secureLiveUpdatesKeyFile: string, rootDir: string, nativeAbsDir: string) { const keyAbsFromPath = join(rootDir, secureLiveUpdatesKeyFile); const keyAbsToPath = join(nativeAbsDir, basename(keyAbsFromPath)); const keyRelToDir = relative(rootDir, nativeAbsDir); if (!(await pathExists(keyAbsFromPath))) { logger.warn( - `Cannot copy Secure Live Updates signature file from ${c.strong( - keyAbsFromPath, - )} to ${keyRelToDir}\n` + + `Cannot copy Secure Live Updates signature file from ${c.strong(keyAbsFromPath)} to ${keyRelToDir}\n` + `Signature file does not exist at specified key path.`, ); @@ -308,20 +232,14 @@ async function copySecureLiveUpdatesKey( } await runTask( - `Copying Secure Live Updates key from ${c.strong( - secureLiveUpdatesKeyFile, - )} to ${keyRelToDir}`, + `Copying Secure Live Updates key from ${c.strong(secureLiveUpdatesKeyFile)} to ${keyRelToDir}`, async () => { return fsCopy(keyAbsFromPath, keyAbsToPath); }, ); } -async function copySSLCert( - sslCertPaths: string[], - rootDir: string, - targetDir: string, -) { +async function copySSLCert(sslCertPaths: string[], rootDir: string, targetDir: string) { const validCertPaths: string[] = []; for (const sslCertPath of sslCertPaths) { const certAbsFromPath = join(rootDir, sslCertPath); @@ -337,18 +255,13 @@ async function copySSLCert( } const certsDirAbsToPath = join(targetDir, 'certs'); const certsDirRelToDir = relative(rootDir, targetDir); - await runTask( - `Copying SSL Certificates from to ${certsDirRelToDir}`, - async () => { - const promises: Promise[] = []; - for (const certPath of validCertPaths) { - promises.push( - fsCopy(certPath, join(certsDirAbsToPath, basename(certPath))), - ); - } - return Promise.all(promises); - }, - ); + await runTask(`Copying SSL Certificates from to ${certsDirRelToDir}`, async () => { + const promises: Promise[] = []; + for (const certPath of validCertPaths) { + promises.push(fsCopy(certPath, join(certsDirAbsToPath, basename(certPath)))); + } + return Promise.all(promises); + }); } interface LiveUpdateConfig { diff --git a/cli/src/tasks/create.ts b/cli/src/tasks/create.ts index 6ef78b619..a4add5fd0 100644 --- a/cli/src/tasks/create.ts +++ b/cli/src/tasks/create.ts @@ -2,8 +2,5 @@ import c from '../colors'; import { fatal } from '../errors'; export async function createCommand(): Promise { - fatal( - `The create command has been removed.\n` + - `Use ${c.input('npm init @capacitor/app')}`, - ); + fatal(`The create command has been removed.\n` + `Use ${c.input('npm init @capacitor/app')}`); } diff --git a/cli/src/tasks/doctor.ts b/cli/src/tasks/doctor.ts index 53262153a..67cd64099 100644 --- a/cli/src/tasks/doctor.ts +++ b/cli/src/tasks/doctor.ts @@ -10,32 +10,26 @@ import { emoji as _e } from '../util/emoji'; import { resolveNode } from '../util/node'; import { getCommandOutput } from '../util/subprocess'; -export async function doctorCommand( - config: Config, - selectedPlatformName: string, -): Promise { - output.write( - `${_e('๐Ÿ’Š', '')} ${c.strong('Capacitor Doctor')} ${_e('๐Ÿ’Š', '')} \n\n`, - ); +export async function doctorCommand(config: Config, selectedPlatformName: string): Promise { + output.write(`${_e('๐Ÿ’Š', '')} ${c.strong('Capacitor Doctor')} ${_e('๐Ÿ’Š', '')} \n\n`); await doctorCore(config); const platforms = await selectPlatforms(config, selectedPlatformName); await Promise.all( - platforms.map(platformName => { + platforms.map((platformName) => { return doctor(config, platformName); }), ); } export async function doctorCore(config: Config): Promise { - const [cliVersion, coreVersion, androidVersion, iosVersion] = - await Promise.all([ - getCommandOutput('npm', ['info', '@capacitor/cli', 'version']), - getCommandOutput('npm', ['info', '@capacitor/core', 'version']), - getCommandOutput('npm', ['info', '@capacitor/android', 'version']), - getCommandOutput('npm', ['info', '@capacitor/ios', 'version']), - ]); + const [cliVersion, coreVersion, androidVersion, iosVersion] = await Promise.all([ + getCommandOutput('npm', ['info', '@capacitor/cli', 'version']), + getCommandOutput('npm', ['info', '@capacitor/core', 'version']), + getCommandOutput('npm', ['info', '@capacitor/android', 'version']), + getCommandOutput('npm', ['info', '@capacitor/ios', 'version']), + ]); output.write( `${c.strong('Latest Dependencies:')}\n\n` + @@ -52,28 +46,16 @@ export async function doctorCore(config: Config): Promise { } async function printInstalledPackages(config: Config) { - const packageNames = [ - '@capacitor/cli', - '@capacitor/core', - '@capacitor/android', - '@capacitor/ios', - ]; + const packageNames = ['@capacitor/cli', '@capacitor/core', '@capacitor/android', '@capacitor/ios']; await Promise.all( - packageNames.map(async packageName => { - const packagePath = resolveNode( - config.app.rootDir, - packageName, - 'package.json', - ); + packageNames.map(async (packageName) => { + const packagePath = resolveNode(config.app.rootDir, packageName, 'package.json'); await printPackageVersion(packageName, packagePath); }), ); } -async function printPackageVersion( - packageName: string, - packagePath: string | null, -) { +async function printPackageVersion(packageName: string, packagePath: string | null) { let version; if (packagePath) { version = (await readJSON(packagePath)).version; @@ -81,10 +63,7 @@ async function printPackageVersion( output.write(` ${packageName}: ${c.weak(version || 'not installed')}\n`); } -export async function doctor( - config: Config, - platformName: string, -): Promise { +export async function doctor(config: Config, platformName: string): Promise { if (platformName === config.ios.name) { await doctorIOS(config); } else if (platformName === config.android.name) { diff --git a/cli/src/tasks/init.ts b/cli/src/tasks/init.ts index 0ebfe28f2..6160d48ab 100644 --- a/cli/src/tasks/init.ts +++ b/cli/src/tasks/init.ts @@ -3,11 +3,7 @@ import { basename, dirname, resolve } from 'path'; import c from '../colors'; import { check, checkAppId, checkAppName, runTask } from '../common'; -import { - CONFIG_FILE_NAME_JSON, - CONFIG_FILE_NAME_TS, - writeConfig, -} from '../config'; +import { CONFIG_FILE_NAME_JSON, CONFIG_FILE_NAME_TS, writeConfig } from '../config'; import { getCordovaPreferences } from '../cordova'; import type { Config, ExternalConfig } from '../definitions'; import { fatal, isFatal } from '../errors'; @@ -31,9 +27,7 @@ export async function initCommand( if (config.app.extConfigType !== 'json') { fatal( - `Cannot run ${c.input( - 'init', - )} for a project using a non-JSON configuration file.\n` + + `Cannot run ${c.input('init')} for a project using a non-JSON configuration file.\n` + `Delete ${c.strong(config.app.extConfigName)} and try again.`, ); } @@ -44,15 +38,12 @@ export async function initCommand( const appId = await getAppId(config, id); const webDir = isInteractive() ? await getWebDir(config, webDirFromCLI) - : webDirFromCLI ?? config.app.extConfig.webDir ?? 'www'; + : (webDirFromCLI ?? config.app.extConfig.webDir ?? 'www'); if (skipAppIDValidation === true) { await check([() => checkAppName(config, appName)]); } else { - await check([ - () => checkAppName(config, appName), - () => checkAppId(config, appId), - ]); + await check([() => checkAppName(config, appName), () => checkAppId(config, appId)]); } const cordova = await getCordovaPreferences(config); @@ -69,10 +60,7 @@ export async function initCommand( ); } catch (e: any) { if (!isFatal(e)) { - output.write( - 'Usage: npx cap init appName appId\n' + - 'Example: npx cap init "My App" "com.example.myapp"\n\n', - ); + output.write('Usage: npx cap init appName appId\n' + 'Example: npx cap init "My App" "com.example.myapp"\n\n'); fatal(e.stack ?? e); } @@ -90,9 +78,7 @@ async function getName(config: Config, name: string) { type: 'text', name: 'name', message: `Name`, - initial: config.app.appName - ? config.app.appName - : config.app.package.name ?? 'App', + initial: config.app.appName ? config.app.appName : (config.app.package.name ?? 'App'), }, ); return answers.name; @@ -126,9 +112,7 @@ async function getWebDir(config: Config, webDir?: string) { const answers = await logPrompt( `${c.strong(`What is the web asset directory for your app?`)}\n` + - `This directory should contain the final ${c.strong( - 'index.html', - )} of your app.`, + `This directory should contain the final ${c.strong('index.html')} of your app.`, { type: 'text', name: 'webDir', @@ -141,25 +125,13 @@ async function getWebDir(config: Config, webDir?: string) { return webDir; } -async function runMergeConfig( - config: Config, - extConfig: ExternalConfig, - type: 'json' | 'ts', -) { +async function runMergeConfig(config: Config, extConfig: ExternalConfig, type: 'json' | 'ts') { const configDirectory = dirname(config.app.extConfigFilePath); - const newConfigPath = resolve( - configDirectory, - type === 'ts' ? CONFIG_FILE_NAME_TS : CONFIG_FILE_NAME_JSON, - ); + const newConfigPath = resolve(configDirectory, type === 'ts' ? CONFIG_FILE_NAME_TS : CONFIG_FILE_NAME_JSON); - await runTask( - `Creating ${c.strong(basename(newConfigPath))} in ${c.input( - config.app.rootDir, - )}`, - async () => { - await mergeConfig(config, extConfig, newConfigPath); - }, - ); + await runTask(`Creating ${c.strong(basename(newConfigPath))} in ${c.input(config.app.rootDir)}`, async () => { + await mergeConfig(config, extConfig, newConfigPath); + }); printNextSteps(basename(newConfigPath)); if (isInteractive()) { @@ -172,11 +144,7 @@ async function runMergeConfig( } } -async function mergeConfig( - config: Config, - extConfig: ExternalConfig, - newConfigPath: string, -): Promise { +async function mergeConfig(config: Config, extConfig: ExternalConfig, newConfigPath: string): Promise { const oldConfig = { ...config.app.extConfig }; const newConfig = { ...oldConfig, ...extConfig }; @@ -185,11 +153,7 @@ async function mergeConfig( function printNextSteps(newConfigName: string) { logSuccess(`${c.strong(newConfigName)} created!`); - output.write( - `\nNext steps: \n${c.strong( - `https://capacitorjs.com/docs/getting-started#where-to-go-next`, - )}\n`, - ); + output.write(`\nNext steps: \n${c.strong(`https://capacitorjs.com/docs/getting-started#where-to-go-next`)}\n`); } async function promptToSignup(): Promise { diff --git a/cli/src/tasks/list.ts b/cli/src/tasks/list.ts index 4ada0a783..6b731865f 100644 --- a/cli/src/tasks/list.ts +++ b/cli/src/tasks/list.ts @@ -9,15 +9,10 @@ import { PluginType, getPluginType, getPlugins, printPlugins } from '../plugin'; import type { Plugin } from '../plugin'; import { allSerial } from '../util/promise'; -export async function listCommand( - config: Config, - selectedPlatformName: string, -): Promise { +export async function listCommand(config: Config, selectedPlatformName: string): Promise { const platforms = await selectPlatforms(config, selectedPlatformName); try { - await allSerial( - platforms.map(platformName => () => list(config, platformName)), - ); + await allSerial(platforms.map((platformName) => () => list(config, platformName))); } catch (e: any) { if (isFatal(e)) { throw e; @@ -41,16 +36,10 @@ export async function list(config: Config, platform: string): Promise { throw `Platform ${c.input(platform)} is not valid.`; } - const capacitorPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Core, - ); + const capacitorPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Core); printPlugins(capacitorPlugins, platform); - const cordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Cordova, - ); + const cordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Cordova); printPlugins(cordovaPlugins, platform, 'cordova'); - const incompatibleCordovaPlugins = plugins.filter( - p => getPluginType(p, platform) === PluginType.Incompatible, - ); + const incompatibleCordovaPlugins = plugins.filter((p) => getPluginType(p, platform) === PluginType.Incompatible); printPlugins(incompatibleCordovaPlugins, platform, 'incompatible'); } diff --git a/cli/src/tasks/migrate.ts b/cli/src/tasks/migrate.ts index b42fccce9..b6fc89565 100644 --- a/cli/src/tasks/migrate.ts +++ b/cli/src/tasks/migrate.ts @@ -17,12 +17,7 @@ import { extractTemplate } from '../util/template'; // eslint-disable-next-line prefer-const let allDependencies: { [key: string]: any } = {}; -const libs = [ - '@capacitor/core', - '@capacitor/cli', - '@capacitor/ios', - '@capacitor/android', -]; +const libs = ['@capacitor/core', '@capacitor/cli', '@capacitor/ios', '@capacitor/android']; const plugins = [ '@capacitor/action-sheet', '@capacitor/app', @@ -54,20 +49,14 @@ const pluginVersion = '^6.0.0'; const gradleVersion = '8.2.1'; let installFailed = false; -export async function migrateCommand( - config: Config, - noprompt: boolean, - packagemanager: string, -): Promise { +export async function migrateCommand(config: Config, noprompt: boolean, packagemanager: string): Promise { if (config === null) { fatal('Config data missing'); } const capMajor = await checkCapacitorMajorVersion(config); if (capMajor < 5) { - fatal( - 'Migrate can only be used on capacitor 5 and above, please use the CLI in Capacitor 5 to upgrade to 5 first', - ); + fatal('Migrate can only be used on capacitor 5 and above, please use the CLI in Capacitor 5 to upgrade to 5 first'); } const jdkMajor = await checkJDKMajorVersion(); @@ -78,7 +67,7 @@ export async function migrateCommand( const variablesAndClasspaths: | { - 'variables': any; + variables: any; 'com.android.tools.build:gradle': string; 'com.google.gms:google-services': string; } @@ -100,20 +89,14 @@ export async function migrateCommand( const { migrateconfirm } = noprompt ? { migrateconfirm: 'y' } - : await logPrompt( - `Capacitor 6 sets a deployment target of iOS 13 and Android 14 (SDK 34). \n`, - { - type: 'text', - name: 'migrateconfirm', - message: `Are you sure you want to migrate? (Y/n)`, - initial: 'y', - }, - ); - - if ( - typeof migrateconfirm === 'string' && - migrateconfirm.toLowerCase() === 'y' - ) { + : await logPrompt(`Capacitor 6 sets a deployment target of iOS 13 and Android 14 (SDK 34). \n`, { + type: 'text', + name: 'migrateconfirm', + message: `Are you sure you want to migrate? (Y/n)`, + initial: 'y', + }); + + if (typeof migrateconfirm === 'string' && migrateconfirm.toLowerCase() === 'y') { try { const { depInstallConfirm } = noprompt ? { depInstallConfirm: 'y' } @@ -127,9 +110,7 @@ export async function migrateCommand( }, ); - const runNpmInstall = - typeof depInstallConfirm === 'string' && - depInstallConfirm.toLowerCase() === 'y'; + const runNpmInstall = typeof depInstallConfirm === 'string' && depInstallConfirm.toLowerCase() === 'y'; let installerType = 'npm'; if (runNpmInstall) { @@ -151,12 +132,9 @@ export async function migrateCommand( } try { - await runTask( - `Installing Latest Modules using ${installerType}.`, - () => { - return installLatestLibs(installerType, runNpmInstall, config); - }, - ); + await runTask(`Installing Latest Modules using ${installerType}.`, () => { + return installLatestLibs(installerType, runNpmInstall, config); + }); } catch (ex) { logger.error( `${installerType} install failed. Try deleting node_modules folder and running ${c.input( @@ -167,21 +145,12 @@ export async function migrateCommand( } // Update iOS Projects - if ( - allDependencies['@capacitor/ios'] && - existsSync(config.ios.platformDirAbs) - ) { + if (allDependencies['@capacitor/ios'] && existsSync(config.ios.platformDirAbs)) { // ios template changes // Remove NSLocationAlwaysUsageDescription - await runTask( - `Migrating Info.plist by removing NSLocationAlwaysUsageDescription key.`, - () => { - return removeKey( - join(config.ios.nativeTargetDirAbs, 'Info.plist'), - 'NSLocationAlwaysUsageDescription', - ); - }, - ); + await runTask(`Migrating Info.plist by removing NSLocationAlwaysUsageDescription key.`, () => { + return removeKey(join(config.ios.nativeTargetDirAbs, 'Info.plist'), 'NSLocationAlwaysUsageDescription'); + }); } if (!installFailed) { @@ -192,17 +161,9 @@ export async function migrateCommand( logger.warn('Skipped Running cap sync.'); } - if ( - allDependencies['@capacitor/android'] && - existsSync(config.android.platformDirAbs) - ) { + if (allDependencies['@capacitor/android'] && existsSync(config.android.platformDirAbs)) { const gradleWrapperVersion = getGradleWrapperVersion( - join( - config.android.platformDirAbs, - 'gradle', - 'wrapper', - 'gradle-wrapper.properties', - ), + join(config.android.platformDirAbs, 'gradle', 'wrapper', 'gradle-wrapper.properties'), ); if (!installFailed && gt(gradleVersion, gradleWrapperVersion)) { @@ -227,84 +188,56 @@ export async function migrateCommand( logger.warn('Skipped upgrading gradle wrapper files'); } await runTask(`Migrating build.gradle file.`, () => { - return updateBuildGradle( - join(config.android.platformDirAbs, 'build.gradle'), - variablesAndClasspaths, - ); + return updateBuildGradle(join(config.android.platformDirAbs, 'build.gradle'), variablesAndClasspaths); }); // Replace deprecated compileSdkVersion - await runTask( - 'Replacing deprecated compileSdkVersion from build.gradle', - () => { - return (async (): Promise => { - const buildGradleFilename = join( - config.android.platformDirAbs, - 'app', - 'build.gradle', + await runTask('Replacing deprecated compileSdkVersion from build.gradle', () => { + return (async (): Promise => { + const buildGradleFilename = join(config.android.platformDirAbs, 'app', 'build.gradle'); + const buildGradleText = readFile(buildGradleFilename); + + if (!buildGradleText) { + logger.error(`Could not read ${buildGradleFilename}. Check its permissions and if it exists.`); + return; + } + const compileSdk = `compileSdkVersion rootProject.ext.compileSdkVersion`; + if (buildGradleText.includes(compileSdk)) { + const buildGradleReplaced = buildGradleText.replace( + compileSdk, + `compileSdk rootProject.ext.compileSdkVersion`, ); - const buildGradleText = readFile(buildGradleFilename); - if (!buildGradleText) { - logger.error( - `Could not read ${buildGradleFilename}. Check its permissions and if it exists.`, - ); - return; - } - const compileSdk = `compileSdkVersion rootProject.ext.compileSdkVersion`; - if (buildGradleText.includes(compileSdk)) { - const buildGradleReplaced = buildGradleText.replace( - compileSdk, - `compileSdk rootProject.ext.compileSdkVersion`, - ); - - writeFileSync( - buildGradleFilename, - buildGradleReplaced, - 'utf-8', - ); - } - })(); - }, - ); + writeFileSync(buildGradleFilename, buildGradleReplaced, 'utf-8'); + } + })(); + }); // Variables gradle await runTask(`Migrating variables.gradle file.`, () => { return (async (): Promise => { - const variablesPath = join( - config.android.platformDirAbs, - 'variables.gradle', - ); + const variablesPath = join(config.android.platformDirAbs, 'variables.gradle'); let txt = readFile(variablesPath); if (!txt) { return; } txt = txt.replace(/= {2}'/g, `= '`); writeFileSync(variablesPath, txt, { encoding: 'utf-8' }); - for (const variable of Object.keys( - variablesAndClasspaths.variables, - )) { + for (const variable of Object.keys(variablesAndClasspaths.variables)) { let replaceStart = `${variable} = '`; let replaceEnd = `'\n`; - if ( - typeof variablesAndClasspaths.variables[variable] === 'number' - ) { + if (typeof variablesAndClasspaths.variables[variable] === 'number') { replaceStart = `${variable} = `; replaceEnd = `\n`; } if (txt.includes(replaceStart)) { const first = txt.indexOf(replaceStart) + replaceStart.length; - const value = txt.substring( - first, - txt.indexOf(replaceEnd, first), - ); + const value = txt.substring(first, txt.indexOf(replaceEnd, first)); if ( - (typeof variablesAndClasspaths.variables[variable] === - 'number' && + (typeof variablesAndClasspaths.variables[variable] === 'number' && value <= variablesAndClasspaths.variables[variable]) || - (typeof variablesAndClasspaths.variables[variable] === - 'string' && + (typeof variablesAndClasspaths.variables[variable] === 'string' && lt(value, variablesAndClasspaths.variables[variable])) ) { await updateFile( @@ -321,9 +254,7 @@ export async function migrateCommand( if (file) { file = file.replace( '}', - ` ${replaceStart}${variablesAndClasspaths.variables[ - variable - ].toString()}${replaceEnd}}`, + ` ${replaceStart}${variablesAndClasspaths.variables[variable].toString()}${replaceEnd}}`, ); writeFileSync(variablesPath, file); } @@ -344,14 +275,7 @@ export async function migrateCommand( coreSplashScreenVersion: '1.0.1', }; for (const variable of Object.keys(pluginVariables)) { - await updateFile( - config, - variablesPath, - `${variable} = '`, - `'`, - pluginVariables[variable], - true, - ); + await updateFile(config, variablesPath, `${variable} = '`, `'`, pluginVariables[variable], true); } })(); }); @@ -359,16 +283,11 @@ export async function migrateCommand( rimraf.sync(join(config.android.appDirAbs, 'build')); if (!installFailed) { - await runTask( - 'Migrating package from Manifest to build.gradle in Capacitor plugins', - () => { - return patchOldCapacitorPlugins(config); - }, - ); + await runTask('Migrating package from Manifest to build.gradle in Capacitor plugins', () => { + return patchOldCapacitorPlugins(config); + }); } else { - logger.warn( - 'Skipped migrating package from Manifest to build.gradle in Capacitor plugins', - ); + logger.warn('Skipped migrating package from Manifest to build.gradle in Capacitor plugins'); } } @@ -378,9 +297,7 @@ export async function migrateCommand( }); if (!installFailed) { - logSuccess( - `Migration to Capacitor ${coreVersion} is complete. Run and test your app!`, - ); + logSuccess(`Migration to Capacitor ${coreVersion} is complete. Run and test your app!`); } else { logger.warn( `Migration to Capacitor ${coreVersion} is incomplete. Check the log messages for more information.`, @@ -396,17 +313,12 @@ export async function migrateCommand( async function checkCapacitorMajorVersion(config: Config): Promise { const capacitorVersion = await getCoreVersion(config); - const versionArray = - capacitorVersion.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/) ?? []; + const versionArray = capacitorVersion.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/) ?? []; const majorVersion = parseInt(versionArray[1]); return majorVersion; } -async function installLatestLibs( - dependencyManager: string, - runInstall: boolean, - config: Config, -) { +async function installLatestLibs(dependencyManager: string, runInstall: boolean, config: Config) { const pkgJsonPath = join(config.app.rootDir, 'package.json'); const pkgJsonFile = readFile(pkgJsonPath); if (!pkgJsonFile) { @@ -442,9 +354,7 @@ async function installLatestLibs( await runCommand(dependencyManager, ['update']); } } else { - logger.info( - `Please run an install command with your package manager of choice. (ex: yarn install)`, - ); + logger.info(`Please run an install command with your package manager of choice. (ex: yarn install)`); } } @@ -472,41 +382,21 @@ async function writeBreakingChanges() { } async function getAndroidVariablesAndClasspaths(config: Config) { - const tempAndroidTemplateFolder = join( - config.cli.assetsDirAbs, - 'tempAndroidTemplate', - ); - await extractTemplate( - config.cli.assets.android.platformTemplateArchiveAbs, - tempAndroidTemplateFolder, - ); - const variablesGradleFile = readFile( - join(tempAndroidTemplateFolder, 'variables.gradle'), - ); - const buildGradleFile = readFile( - join(tempAndroidTemplateFolder, 'build.gradle'), - ); + const tempAndroidTemplateFolder = join(config.cli.assetsDirAbs, 'tempAndroidTemplate'); + await extractTemplate(config.cli.assets.android.platformTemplateArchiveAbs, tempAndroidTemplateFolder); + const variablesGradleFile = readFile(join(tempAndroidTemplateFolder, 'variables.gradle')); + const buildGradleFile = readFile(join(tempAndroidTemplateFolder, 'build.gradle')); if (!variablesGradleFile || !buildGradleFile) { return; } deleteFolderRecursive(tempAndroidTemplateFolder); - const firstIndxOfCATBGV = - buildGradleFile.indexOf(`classpath 'com.android.tools.build:gradle:`) + 42; - const firstIndxOfCGGGS = - buildGradleFile.indexOf(`com.google.gms:google-services:`) + 31; + const firstIndxOfCATBGV = buildGradleFile.indexOf(`classpath 'com.android.tools.build:gradle:`) + 42; + const firstIndxOfCGGGS = buildGradleFile.indexOf(`com.google.gms:google-services:`) + 31; const comAndroidToolsBuildGradleVersion = - '' + - buildGradleFile.substring( - firstIndxOfCATBGV, - buildGradleFile.indexOf("'", firstIndxOfCATBGV), - ); + '' + buildGradleFile.substring(firstIndxOfCATBGV, buildGradleFile.indexOf("'", firstIndxOfCATBGV)); const comGoogleGmsGoogleServices = - '' + - buildGradleFile.substring( - firstIndxOfCGGGS, - buildGradleFile.indexOf("'", firstIndxOfCGGGS), - ); + '' + buildGradleFile.substring(firstIndxOfCGGGS, buildGradleFile.indexOf("'", firstIndxOfCGGGS)); const variablesGradleAsJSON = JSON.parse( variablesGradleFile @@ -523,7 +413,7 @@ async function getAndroidVariablesAndClasspaths(config: Config) { ); return { - 'variables': variablesGradleAsJSON, + variables: variablesGradleAsJSON, 'com.android.tools.build:gradle': comAndroidToolsBuildGradleVersion, 'com.google.gms:google-services': comGoogleGmsGoogleServices, }; @@ -537,9 +427,7 @@ function readFile(filename: string): string | undefined { } return readFileSync(filename, 'utf-8'); } catch (err) { - logger.error( - `Unable to read ${filename}. Verify it is not already open. ${err}`, - ); + logger.error(`Unable to read ${filename}. Verify it is not already open. ${err}`); } } @@ -548,10 +436,7 @@ function getGradleWrapperVersion(filename: string): string { if (!txt) { return '0.0.0'; } - const version = txt.substring( - txt.indexOf('gradle-') + 7, - txt.indexOf('-all.zip'), - ); + const version = txt.substring(txt.indexOf('gradle-') + 7, txt.indexOf('-all.zip')); const semverVersion = coerce(version)?.version; return semverVersion ? semverVersion : '0.0.0'; } @@ -559,39 +444,24 @@ function getGradleWrapperVersion(filename: string): string { async function updateGradleWrapperFiles(platformDir: string) { await runCommand( `./gradlew`, - [ - 'wrapper', - '--distribution-type', - 'all', - '--gradle-version', - gradleVersion, - '--warning-mode', - 'all', - ], + ['wrapper', '--distribution-type', 'all', '--gradle-version', gradleVersion, '--warning-mode', 'all'], { cwd: platformDir, }, ); } -async function movePackageFromManifestToBuildGradle( - manifestFilename: string, - buildGradleFilename: string, -) { +async function movePackageFromManifestToBuildGradle(manifestFilename: string, buildGradleFilename: string) { const manifestText = readFile(manifestFilename); const buildGradleText = readFile(buildGradleFilename); if (!manifestText) { - logger.error( - `Could not read ${manifestFilename}. Check its permissions and if it exists.`, - ); + logger.error(`Could not read ${manifestFilename}. Check its permissions and if it exists.`); return; } if (!buildGradleText) { - logger.error( - `Could not read ${buildGradleFilename}. Check its permissions and if it exists.`, - ); + logger.error(`Could not read ${buildGradleFilename}. Check its permissions and if it exists.`); return; } @@ -617,25 +487,16 @@ async function movePackageFromManifestToBuildGradle( manifestReplaced = manifestReplaced.replace(manifestRegEx, ''); if (manifestText == manifestReplaced) { - logger.error( - `Unable to update Android Manifest: no changes were detected in Android Manifest file`, - ); + logger.error(`Unable to update Android Manifest: no changes were detected in Android Manifest file`); return; } let buildGradleReplaced = buildGradleText; - buildGradleReplaced = setAllStringIn( - buildGradleText, - 'android {', - '\n', - `\n namespace "${packageName}"`, - ); + buildGradleReplaced = setAllStringIn(buildGradleText, 'android {', '\n', `\n namespace "${packageName}"`); if (buildGradleText == buildGradleReplaced) { - logger.error( - `Unable to update buildGradleText: no changes were detected in Android Manifest file`, - ); + logger.error(`Unable to update buildGradleText: no changes were detected in Android Manifest file`); return; } @@ -646,7 +507,7 @@ async function movePackageFromManifestToBuildGradle( async function updateBuildGradle( filename: string, variablesAndClasspaths: { - 'variables': any; + variables: any; 'com.android.tools.build:gradle': string; 'com.google.gms:google-services': string; }, @@ -656,25 +517,17 @@ async function updateBuildGradle( return; } const neededDeps: { [key: string]: string } = { - 'com.android.tools.build:gradle': - variablesAndClasspaths['com.android.tools.build:gradle'], - 'com.google.gms:google-services': - variablesAndClasspaths['com.google.gms:google-services'], + 'com.android.tools.build:gradle': variablesAndClasspaths['com.android.tools.build:gradle'], + 'com.google.gms:google-services': variablesAndClasspaths['com.google.gms:google-services'], }; let replaced = txt; for (const dep of Object.keys(neededDeps)) { if (replaced.includes(`classpath '${dep}`)) { const firstIndex = replaced.indexOf(dep) + dep.length + 1; - const existingVersion = - '' + replaced.substring(firstIndex, replaced.indexOf("'", firstIndex)); + const existingVersion = '' + replaced.substring(firstIndex, replaced.indexOf("'", firstIndex)); if (gte(neededDeps[dep], existingVersion)) { - replaced = setAllStringIn( - replaced, - `classpath '${dep}:`, - `'`, - neededDeps[dep], - ); + replaced = setAllStringIn(replaced, `classpath '${dep}:`, `'`, neededDeps[dep]); logger.info(`Set ${dep} = ${neededDeps[dep]}.`); } } @@ -726,20 +579,13 @@ async function updateFile( } return true; } else if (!skipIfNotFound) { - logger.error( - `Unable to find "${textStart}" in ${filename}. Try updating it manually`, - ); + logger.error(`Unable to find "${textStart}" in ${filename}. Try updating it manually`); } return false; } -function setAllStringIn( - data: string, - start: string, - end: string, - replacement: string, -): string { +function setAllStringIn(data: string, start: string, end: string, replacement: string): string { let position = 0; let result = data; let replaced = true; @@ -750,29 +596,19 @@ function setAllStringIn( } else { const idx = foundIdx + start.length; position = idx + replacement.length; - result = - result.substring(0, idx) + - replacement + - result.substring(result.indexOf(end, idx)); + result = result.substring(0, idx) + replacement + result.substring(result.indexOf(end, idx)); } } return result; } -export async function patchOldCapacitorPlugins( - config: Config, -): Promise { +export async function patchOldCapacitorPlugins(config: Config): Promise { const allPlugins = await getPlugins(config, 'android'); const androidPlugins = await getAndroidPlugins(allPlugins); return await Promise.all( - androidPlugins.map(async p => { + androidPlugins.map(async (p) => { if (p.manifest?.android?.src) { - const buildGradlePath = resolveNode( - config.app.rootDir, - p.id, - p.manifest.android.src, - 'build.gradle', - ); + const buildGradlePath = resolveNode(config.app.rootDir, p.id, p.manifest.android.src, 'build.gradle'); const manifestPath = resolveNode( config.app.rootDir, p.id, @@ -809,7 +645,7 @@ async function removeKey(filename: string, key: string) { let lines = txt.split('\n'); let removed = false; let removing = false; - lines = lines.filter(line => { + lines = lines.filter((line) => { if (removing && line.includes('')) { removing = false; return false; diff --git a/cli/src/tasks/new-plugin.ts b/cli/src/tasks/new-plugin.ts index 45133bfae..ad07a7e0d 100644 --- a/cli/src/tasks/new-plugin.ts +++ b/cli/src/tasks/new-plugin.ts @@ -2,8 +2,5 @@ import c from '../colors'; import { fatal } from '../errors'; export async function newPluginCommand(): Promise { - fatal( - `The plugin:generate command has been removed.\n` + - `Use ${c.input('npm init @capacitor/plugin')}`, - ); + fatal(`The plugin:generate command has been removed.\n` + `Use ${c.input('npm init @capacitor/plugin')}`); } diff --git a/cli/src/tasks/open.ts b/cli/src/tasks/open.ts index 1afafba06..15675e626 100644 --- a/cli/src/tasks/open.ts +++ b/cli/src/tasks/open.ts @@ -13,19 +13,11 @@ import { fatal, isFatal } from '../errors'; import { openIOS } from '../ios/open'; import { logger } from '../log'; -export async function openCommand( - config: Config, - selectedPlatformName: string, -): Promise { +export async function openCommand(config: Config, selectedPlatformName: string): Promise { if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) { const platformDir = resolvePlatform(config, selectedPlatformName); if (platformDir) { - await runPlatformHook( - config, - selectedPlatformName, - platformDir, - 'capacitor:open', - ); + await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:open'); } else { logger.error(`Platform ${c.input(selectedPlatformName)} not found.`); } @@ -53,17 +45,11 @@ export async function openCommand( } } -function createOpenablePlatformFilter( - config: Config, -): (platform: string) => boolean { - return platform => - platform === config.ios.name || platform === config.android.name; +function createOpenablePlatformFilter(config: Config): (platform: string) => boolean { + return (platform) => platform === config.ios.name || platform === config.android.name; } -export async function open( - config: Config, - platformName: string, -): Promise { +export async function open(config: Config, platformName: string): Promise { if (platformName === config.ios.name) { await runTask('Opening the Xcode workspace...', () => { return openIOS(config); diff --git a/cli/src/tasks/run.ts b/cli/src/tasks/run.ts index 7c789bfe4..2c3afd8a0 100644 --- a/cli/src/tasks/run.ts +++ b/cli/src/tasks/run.ts @@ -38,18 +38,12 @@ export async function runCommand( selectedPlatformName: string, options: RunCommandOptions, ): Promise { - options.host = - options.host ?? CapLiveReloadHelper.getIpAddress() ?? 'localhost'; + options.host = options.host ?? CapLiveReloadHelper.getIpAddress() ?? 'localhost'; options.port = options.port ?? '3000'; if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) { const platformDir = resolvePlatform(config, selectedPlatformName); if (platformDir) { - await runPlatformHook( - config, - selectedPlatformName, - platformDir, - 'capacitor:run', - ); + await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:run'); } else { logger.error(`Platform ${c.input(selectedPlatformName)} not found.`); } @@ -67,7 +61,7 @@ export async function runCommand( if (options.list) { const targets = await getPlatformTargets(platformName); - const outputTargets = targets.map(t => ({ + const outputTargets = targets.map((t) => ({ name: getPlatformTargetName(t), api: `${t.platform === 'ios' ? 'iOS' : 'API'} ${t.sdkVersion}`, id: t.id ?? '?', @@ -77,7 +71,7 @@ export async function runCommand( if (process.argv.includes('--json')) { process.stdout.write(`${JSON.stringify(outputTargets)}\n`); } else { - const rows = outputTargets.map(t => [t.name, t.api, t.id]); + const rows = outputTargets.map((t) => [t.name, t.api, t.id]); output.write( `${columnar(rows, { @@ -96,32 +90,18 @@ export async function runCommand( } const cordovaPlugins = await getCordovaPlugins(config, platformName); if (options.liveReload) { - await CapLiveReloadHelper.editCapConfigForLiveReload( - config, - platformName, - options, - ); + await CapLiveReloadHelper.editCapConfigForLiveReload(config, platformName, options); if (platformName === config.android.name) { - await await writeCordovaAndroidManifest( - cordovaPlugins, - config, - platformName, - true, - ); + await await writeCordovaAndroidManifest(cordovaPlugins, config, platformName, true); } } await run(config, platformName, options); if (options.liveReload) { - new Promise(resolve => process.on('SIGINT', resolve)) + new Promise((resolve) => process.on('SIGINT', resolve)) .then(async () => { await CapLiveReloadHelper.revertCapConfigForLiveReload(); if (platformName === config.android.name) { - await writeCordovaAndroidManifest( - cordovaPlugins, - config, - platformName, - false, - ); + await writeCordovaAndroidManifest(cordovaPlugins, config, platformName, false); } }) .then(() => process.exit()); @@ -140,11 +120,7 @@ export async function runCommand( } } -export async function run( - config: Config, - platformName: string, - options: RunCommandOptions, -): Promise { +export async function run(config: Config, platformName: string, options: RunCommandOptions): Promise { if (platformName == config.ios.name) { await runIOS(config, options); } else if (platformName === config.android.name) { @@ -156,11 +132,8 @@ export async function run( } } -function createRunnablePlatformFilter( - config: Config, -): (platform: string) => boolean { - return platform => - platform === config.ios.name || platform === config.android.name; +function createRunnablePlatformFilter(config: Config): (platform: string) => boolean { + return (platform) => platform === config.ios.name || platform === config.android.name; } async function sleepForever(): Promise { diff --git a/cli/src/tasks/sourcemaps.ts b/cli/src/tasks/sourcemaps.ts index 54b79fe5d..6ebc0fdb1 100644 --- a/cli/src/tasks/sourcemaps.ts +++ b/cli/src/tasks/sourcemaps.ts @@ -1,11 +1,4 @@ -import { - readdirSync, - existsSync, - readFileSync, - writeFileSync, - unlinkSync, - lstatSync, -} from '@ionic/utils-fs'; +import { readdirSync, existsSync, readFileSync, writeFileSync, unlinkSync, lstatSync } from '@ionic/utils-fs'; import { join, extname } from 'path'; import type { Config } from '../definitions'; @@ -13,7 +6,7 @@ import { logger } from '../log'; function walkDirectory(dirPath: string) { const files = readdirSync(dirPath); - files.forEach(file => { + files.forEach((file) => { const targetFile = join(dirPath, file); if (existsSync(targetFile) && lstatSync(targetFile).isDirectory()) { walkDirectory(targetFile); @@ -24,8 +17,7 @@ function walkDirectory(dirPath: string) { const bufFile = readFileSync(targetFile, 'utf8'); const result = bufFile.replace( `sourceMappingURL=${file}.map`, - 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + - bufMap, + 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + bufMap, ); writeFileSync(targetFile, result); unlinkSync(mapFile); @@ -34,10 +26,7 @@ function walkDirectory(dirPath: string) { }); } -export async function inlineSourceMaps( - config: Config, - platformName: string, -): Promise { +export async function inlineSourceMaps(config: Config, platformName: string): Promise { let buildDir = ''; if (platformName == config.ios.name) { diff --git a/cli/src/tasks/sync.ts b/cli/src/tasks/sync.ts index f90c20ead..98660e8b8 100644 --- a/cli/src/tasks/sync.ts +++ b/cli/src/tasks/sync.ts @@ -1,11 +1,4 @@ -import { - check, - checkPackage, - checkWebDir, - selectPlatforms, - isValidPlatform, - runHooks, -} from '../common'; +import { check, checkPackage, checkWebDir, selectPlatforms, isValidPlatform, runHooks } from '../common'; import type { Config } from '../definitions'; import { fatal, isFatal } from '../errors'; import { logger } from '../log'; @@ -34,16 +27,8 @@ export async function syncCommand( const then = +new Date(); const platforms = await selectPlatforms(config, selectedPlatformName); try { - await check([ - () => checkPackage(), - () => checkWebDir(config), - ...updateChecks(config, platforms), - ]); - await allSerial( - platforms.map( - platformName => () => sync(config, platformName, deployment, inline), - ), - ); + await check([() => checkPackage(), () => checkWebDir(config), ...updateChecks(config, platforms)]); + await allSerial(platforms.map((platformName) => () => sync(config, platformName, deployment, inline))); const now = +new Date(); const diff = (now - then) / 1000; logger.info(`Sync finished in ${diff}s`); @@ -57,18 +42,8 @@ export async function syncCommand( } } -export async function sync( - config: Config, - platformName: string, - deployment: boolean, - inline = false, -): Promise { - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:sync:before', - ); +export async function sync(config: Config, platformName: string, deployment: boolean, inline = false): Promise { + await runHooks(config, platformName, config.app.rootDir, 'capacitor:sync:before'); try { await copy(config, platformName, inline); @@ -77,10 +52,5 @@ export async function sync( } await update(config, platformName, deployment); - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:sync:after', - ); + await runHooks(config, platformName, config.app.rootDir, 'capacitor:sync:after'); } diff --git a/cli/src/tasks/telemetry.ts b/cli/src/tasks/telemetry.ts index 437909aea..fba4cafa9 100644 --- a/cli/src/tasks/telemetry.ts +++ b/cli/src/tasks/telemetry.ts @@ -14,9 +14,7 @@ export async function telemetryCommand(onOrOff?: string): Promise { } else { await writeConfig({ ...sysconfig, telemetry: enabled }); logSuccess( - `You have ${c.strong(`opted ${enabled ? 'in' : 'out'}`)} ${ - enabled ? 'for' : 'of' - } telemetry on this machine.`, + `You have ${c.strong(`opted ${enabled ? 'in' : 'out'}`)} ${enabled ? 'for' : 'of'} telemetry on this machine.`, ); if (enabled) { @@ -38,9 +36,5 @@ function interpretEnabled(onOrOff?: string): boolean | undefined { return undefined; } - fatal( - `Argument must be ${c.strong('on')} or ${c.strong( - 'off', - )} (or left unspecified)`, - ); + fatal(`Argument must be ${c.strong('on')} or ${c.strong('off')} (or left unspecified)`); } diff --git a/cli/src/tasks/update.ts b/cli/src/tasks/update.ts index 7a7d22c0e..a2b6cbe0d 100644 --- a/cli/src/tasks/update.ts +++ b/cli/src/tasks/update.ts @@ -18,20 +18,11 @@ import { updateIOS } from '../ios/update'; import { logger } from '../log'; import { allSerial } from '../util/promise'; -export async function updateCommand( - config: Config, - selectedPlatformName: string, - deployment: boolean, -): Promise { +export async function updateCommand(config: Config, selectedPlatformName: string, deployment: boolean): Promise { if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) { const platformDir = resolvePlatform(config, selectedPlatformName); if (platformDir) { - await runPlatformHook( - config, - selectedPlatformName, - platformDir, - 'capacitor:update', - ); + await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:update'); } else { logger.error(`Platform ${c.input(selectedPlatformName)} not found.`); } @@ -41,12 +32,7 @@ export async function updateCommand( try { await check([() => checkPackage(), ...updateChecks(config, platforms)]); - await allSerial( - platforms.map( - platformName => async () => - await update(config, platformName, deployment), - ), - ); + await allSerial(platforms.map((platformName) => async () => await update(config, platformName, deployment))); const now = +new Date(); const diff = (now - then) / 1000; logger.info(`Update finished in ${diff}s`); @@ -60,10 +46,7 @@ export async function updateCommand( } } -export function updateChecks( - config: Config, - platforms: string[], -): CheckFunction[] { +export function updateChecks(config: Config, platforms: string[]): CheckFunction[] { const checks: CheckFunction[] = []; for (const platformName of platforms) { if (platformName === config.ios.name) { @@ -79,18 +62,9 @@ export function updateChecks( return checks; } -export async function update( - config: Config, - platformName: string, - deployment: boolean, -): Promise { +export async function update(config: Config, platformName: string, deployment: boolean): Promise { await runTask(c.success(c.strong(`update ${platformName}`)), async () => { - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:update:before', - ); + await runHooks(config, platformName, config.app.rootDir, 'capacitor:update:before'); if (platformName === config.ios.name) { await updateIOS(config, deployment); @@ -98,11 +72,6 @@ export async function update( await updateAndroid(config); } - await runHooks( - config, - platformName, - config.app.rootDir, - 'capacitor:update:after', - ); + await runHooks(config, platformName, config.app.rootDir, 'capacitor:update:after'); }); } diff --git a/cli/src/telemetry.ts b/cli/src/telemetry.ts index 24588ff7e..d667d783a 100644 --- a/cli/src/telemetry.ts +++ b/cli/src/telemetry.ts @@ -39,17 +39,13 @@ export interface Metric { type CommanderAction = (...args: any[]) => void | Promise; -export function telemetryAction( - config: Config, - action: CommanderAction, -): CommanderAction { +export function telemetryAction(config: Config, action: CommanderAction): CommanderAction { return async (...actionArgs: any[]): Promise => { const start = new Date(); // This is how commanderjs works--the command object is either the last // element or second to last if there are additional options (via `.allowUnknownOption()`) const lastArg = actionArgs[actionArgs.length - 1]; - const cmd: Command = - lastArg instanceof Command ? lastArg : actionArgs[actionArgs.length - 2]; + const cmd: Command = lastArg instanceof Command ? lastArg : actionArgs[actionArgs.length - 2]; const command = getFullCommandName(cmd); let error: any; @@ -69,9 +65,7 @@ export function telemetryAction( // Only collect packages in the capacitor org: // https://www.npmjs.com/org/capacitor - const capacitorPackages = packages.filter(([k]) => - k.startsWith('@capacitor/'), - ); + const capacitorPackages = packages.filter(([k]) => k.startsWith('@capacitor/')); const versions = capacitorPackages.map(([k, v]) => [ `${k.replace(/^@capacitor\//, '').replace(/-/g, '_')}_version`, @@ -128,22 +122,16 @@ export async function sendMetric( await send({ type: 'telemetry', data: message }); } else { - debug( - 'Telemetry is off (user choice, non-interactive terminal, or CI)--not sending metric', - ); + debug('Telemetry is off (user choice, non-interactive terminal, or CI)--not sending metric'); } } async function promptForTelemetry(): Promise { const { confirm } = await logPrompt( - `${c.strong( - 'Would you like to help improve Capacitor by sharing anonymous usage data? ๐Ÿ’–', - )}\n` + + `${c.strong('Would you like to help improve Capacitor by sharing anonymous usage data? ๐Ÿ’–')}\n` + `Read more about what is being collected and why here: ${c.strong( 'https://capacitorjs.com/telemetry', - )}. You can change your mind at any time by using the ${c.input( - 'npx cap telemetry', - )} command.`, + )}. You can change your mind at any time by using the ${c.input('npx cap telemetry')} command.`, { type: 'confirm', name: 'confirm', @@ -166,11 +154,7 @@ async function getAppIdentifier(config: Config): Promise { const { createHash } = await import('crypto'); // get the first commit hash, which should be universally unique - const output = await getCommandOutput( - 'git', - ['rev-list', '--max-parents=0', 'HEAD'], - { cwd: config.app.rootDir }, - ); + const output = await getCommandOutput('git', ['rev-list', '--max-parents=0', 'HEAD'], { cwd: config.app.rootDir }); const firstLine = output?.split('\n')[0]; diff --git a/cli/src/util/fn.ts b/cli/src/util/fn.ts index d18206cdb..91abc4755 100644 --- a/cli/src/util/fn.ts +++ b/cli/src/util/fn.ts @@ -1,7 +1,4 @@ -export const tryFn = async Promise, R>( - fn: T, - ...args: any[] -): Promise => { +export const tryFn = async Promise, R>(fn: T, ...args: any[]): Promise => { try { return await fn(...args); } catch { diff --git a/cli/src/util/fs.ts b/cli/src/util/fs.ts index dc8aeb355..60f60e194 100644 --- a/cli/src/util/fs.ts +++ b/cli/src/util/fs.ts @@ -1,10 +1,4 @@ -import { - existsSync, - lstatSync, - readdirSync, - rmdirSync, - unlinkSync, -} from '@ionic/utils-fs'; +import { existsSync, lstatSync, readdirSync, rmdirSync, unlinkSync } from '@ionic/utils-fs'; import { join } from 'path'; export const convertToUnixPath = (path: string): string => { @@ -13,7 +7,7 @@ export const convertToUnixPath = (path: string): string => { export const deleteFolderRecursive = (directoryPath: any): void => { if (existsSync(directoryPath)) { - readdirSync(directoryPath).forEach(file => { + readdirSync(directoryPath).forEach((file) => { const curPath = join(directoryPath, file); if (lstatSync(curPath).isDirectory()) { deleteFolderRecursive(curPath); diff --git a/cli/src/util/iosplugin.ts b/cli/src/util/iosplugin.ts index 8e490fe39..33bd2829b 100644 --- a/cli/src/util/iosplugin.ts +++ b/cli/src/util/iosplugin.ts @@ -1,10 +1,5 @@ import type { ReaddirPOptions } from '@ionic/utils-fs'; -import { - readFileSync, - readdirp, - readJSONSync, - writeJSONSync, -} from '@ionic/utils-fs'; +import { readFileSync, readdirp, readJSONSync, writeJSONSync } from '@ionic/utils-fs'; import { resolve } from 'path'; import { getCordovaPlugins } from '../cordova'; @@ -16,11 +11,8 @@ export async function getPluginFiles(plugins: Plugin[]): Promise { let filenameList: string[] = []; const options: ReaddirPOptions = { - filter: item => { - if ( - item.stats.isFile() && - (item.path.endsWith('.swift') || item.path.endsWith('.m')) - ) { + filter: (item) => { + if (item.stats.isFile() && (item.path.endsWith('.swift') || item.path.endsWith('.m'))) { return true; } else { return false; @@ -61,23 +53,14 @@ export async function findPluginClasses(files: string[]): Promise { return classList; } -export async function writePluginJSON( - config: Config, - classList: string[], -): Promise { - const capJSONFile = resolve( - config.ios.nativeTargetDirAbs, - 'capacitor.config.json', - ); +export async function writePluginJSON(config: Config, classList: string[]): Promise { + const capJSONFile = resolve(config.ios.nativeTargetDirAbs, 'capacitor.config.json'); const capJSON = readJSONSync(capJSONFile); capJSON['packageClassList'] = classList; writeJSONSync(capJSONFile, capJSON, { spaces: '\t' }); } -export async function generateIOSPackageJSON( - config: Config, - plugins: Plugin[], -): Promise { +export async function generateIOSPackageJSON(config: Config, plugins: Plugin[]): Promise { const fileList = await getPluginFiles(plugins); const classList = await findPluginClasses(fileList); const cordovaPlugins = await getCordovaPlugins(config, 'ios'); diff --git a/cli/src/util/livereload.ts b/cli/src/util/livereload.ts index 384abe0ec..6aed863a4 100644 --- a/cli/src/util/livereload.ts +++ b/cli/src/util/livereload.ts @@ -40,16 +40,10 @@ class CapLiveReload { }; const isPrivate = (addr: string) => { return ( - /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test( - addr, - ) || + /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || - /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test( - addr, - ) || - /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test( - addr, - ) || + /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || + /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^f[cd][0-9a-f]{2}:/i.test(addr) || /^fe80:/i.test(addr) || @@ -94,7 +88,7 @@ class CapLiveReload { } const all = Object.keys(interfaces) - .map(nic => { + .map((nic) => { // // Note: name will only be `public` or `private` // when this is called. @@ -108,9 +102,7 @@ class CapLiveReload { return true; } - return name === 'public' - ? isPrivate(details.address) - : isPublic(details.address); + return name === 'public' ? isPrivate(details.address) : isPublic(details.address); }); return addresses.length ? addresses[0].address : undefined; @@ -131,8 +123,8 @@ class CapLiveReload { platformName == config.ios.name ? config.ios.nativeTargetDirAbs : platformName == config.android.name - ? config.android.assetsDirAbs - : null; + ? config.android.assetsDirAbs + : null; if (platformAbsPath == null) throw new Error('Platform not found.'); const capConfigPath = rootConfigChange ? config.app.extConfigFilePath @@ -159,8 +151,8 @@ class CapLiveReload { platformName == config.ios.name ? config.ios.nativeTargetDirAbs : platformName == config.android.name - ? config.android.assetsDirAbs - : null; + ? config.android.assetsDirAbs + : null; if (platformAbsPath == null) throw new Error('Platform not found.'); const capConfigPath = rootConfigChange ? config.app.extConfigFilePath @@ -177,11 +169,7 @@ class CapLiveReload { } async revertCapConfigForLiveReload(): Promise { - if ( - this.configJsonToRevertTo.json == null || - this.configJsonToRevertTo.platformPath == null - ) - return; + if (this.configJsonToRevertTo.json == null || this.configJsonToRevertTo.platformPath == null) return; const capConfigPath = this.configJsonToRevertTo.platformPath; const configJson = this.configJsonToRevertTo.json; writeJSONSync(capConfigPath, JSON.parse(configJson), { spaces: '\t' }); diff --git a/cli/src/util/monorepotools.ts b/cli/src/util/monorepotools.ts index 726bf1eca..19367aa68 100644 --- a/cli/src/util/monorepotools.ts +++ b/cli/src/util/monorepotools.ts @@ -12,8 +12,7 @@ export function findMonorepoRoot(currentPath: string): string { const pnpmWorkspacePath = join(currentPath, 'pnpm-workspace.yaml'); if ( existsSync(pnpmWorkspacePath) || - (existsSync(packageJsonPath) && - JSON.parse(readFileSync(packageJsonPath, 'utf-8')).workspaces) + (existsSync(packageJsonPath) && JSON.parse(readFileSync(packageJsonPath, 'utf-8')).workspaces) ) { return currentPath; } @@ -73,10 +72,7 @@ export function findPackagePath( * @param currentPath - The current path to start searching from. * @returns The relative path to the package, or null if not found. */ -export function findPackageRelativePathInMonorepo( - packageName: string, - currentPath: string, -): string | null { +export function findPackageRelativePathInMonorepo(packageName: string, currentPath: string): string | null { const monorepoRoot = findMonorepoRoot(currentPath); const packagePath = findPackagePath(packageName, currentPath, monorepoRoot); if (packagePath) { diff --git a/cli/src/util/native-run.ts b/cli/src/util/native-run.ts index d828b9aee..acaca2c6c 100644 --- a/cli/src/util/native-run.ts +++ b/cli/src/util/native-run.ts @@ -8,15 +8,8 @@ import { resolveNode } from './node'; import { runCommand } from './subprocess'; import type { RunCommandOptions } from './subprocess'; -export async function runNativeRun( - args: readonly string[], - options: RunCommandOptions = {}, -): Promise { - const p = resolveNode( - __dirname, - dirname('native-run/package'), - 'bin/native-run', - ); +export async function runNativeRun(args: readonly string[], options: RunCommandOptions = {}): Promise { + const p = resolveNode(__dirname, dirname('native-run/package'), 'bin/native-run'); if (!p) { fatal(`${c.input('native-run')} not found.`); @@ -25,9 +18,7 @@ export async function runNativeRun( return await runCommand(p, args, options); } -export async function getPlatformTargets( - platformName: string, -): Promise { +export async function getPlatformTargets(platformName: string): Promise { const errors = []; try { const output = await runNativeRun([platformName, '--list', '--json']); diff --git a/cli/src/util/node.ts b/cli/src/util/node.ts index 914ca7029..34e2adf16 100644 --- a/cli/src/util/node.ts +++ b/cli/src/util/node.ts @@ -15,10 +15,7 @@ export const requireTS = (ts: typeof typescript, p: string): unknown => { delete require.cache[id]; - require.extensions['.ts'] = ( - module: NodeModuleWithCompile, - fileName: string, - ) => { + require.extensions['.ts'] = (module: NodeModuleWithCompile, fileName: string) => { let sourceText = readFileSync(fileName, 'utf8'); if (fileName.endsWith('.ts')) { @@ -50,10 +47,7 @@ export const requireTS = (ts: typeof typescript, p: string): unknown => { return m; }; -export function resolveNode( - root: string, - ...pathSegments: string[] -): string | null { +export function resolveNode(root: string, ...pathSegments: string[]): string | null { try { return require.resolve(pathSegments.join('/'), { paths: [root] }); } catch (e) { diff --git a/cli/src/util/promise.ts b/cli/src/util/promise.ts index 194595fca..f4566a792 100644 --- a/cli/src/util/promise.ts +++ b/cli/src/util/promise.ts @@ -1,25 +1,15 @@ export function allSerial(funcs: (() => Promise)[]): Promise { return funcs.reduce( - (promise, func) => - promise.then(result => func().then(x => result.concat(x))), + (promise, func) => promise.then((result) => func().then((x) => result.concat(x))), Promise.resolve([]), ); } -export type PromiseExecutor = ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: any) => void, -) => void; +export type PromiseExecutor = (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void; -export type PromiseOnFulfilled = - | ((value: T) => TResult | PromiseLike) - | undefined - | null; +export type PromiseOnFulfilled = ((value: T) => TResult | PromiseLike) | undefined | null; -export type PromiseOnRejected = - | ((reason: any) => TResult | PromiseLike) - | undefined - | null; +export type PromiseOnRejected = ((reason: any) => TResult | PromiseLike) | undefined | null; export class LazyPromise extends Promise { private _executor: PromiseExecutor; @@ -41,9 +31,7 @@ export class LazyPromise extends Promise { return this._promise.then(onfulfilled, onrejected); } - catch( - onrejected?: PromiseOnRejected, - ): Promise { + catch(onrejected?: PromiseOnRejected): Promise { this._promise = this._promise || new Promise(this._executor); return this._promise.catch(onrejected); } diff --git a/cli/src/util/spm.ts b/cli/src/util/spm.ts index 65db5b785..60ef128b1 100644 --- a/cli/src/util/spm.ts +++ b/cli/src/util/spm.ts @@ -10,9 +10,7 @@ export interface SwiftPlugin { path: string; } -export async function checkPackageManager( - config: Config, -): Promise<'Cocoapods' | 'SPM'> { +export async function checkPackageManager(config: Config): Promise<'Cocoapods' | 'SPM'> { const iosDirectory = config.ios.nativeProjectDirAbs; if (existsSync(resolve(iosDirectory, 'CapApp-SPM'))) { return 'SPM'; @@ -22,34 +20,23 @@ export async function checkPackageManager( } export async function findPackageSwiftFile(config: Config): Promise { - const packageDirectory = resolve( - config.ios.nativeProjectDirAbs, - 'CapApp-SPM', - ); + const packageDirectory = resolve(config.ios.nativeProjectDirAbs, 'CapApp-SPM'); return resolve(packageDirectory, 'Package.swift'); } -export async function generatePackageFile( - config: Config, - plugins: Plugin[], -): Promise { +export async function generatePackageFile(config: Config, plugins: Plugin[]): Promise { const packageSwiftFile = await findPackageSwiftFile(config); try { logger.warn('SPM Support is still experimental'); const textToWrite = generatePackageText(config, plugins); writeFileSync(packageSwiftFile, textToWrite); } catch (err) { - logger.error( - `Unable to write to ${packageSwiftFile}. Verify it is not already open. \n Error: ${err}`, - ); + logger.error(`Unable to write to ${packageSwiftFile}. Verify it is not already open. \n Error: ${err}`); } } function generatePackageText(config: Config, plugins: Plugin[]): string { - const pbx = readFileSync( - join(config.ios.nativeXcodeProjDirAbs, 'project.pbxproj'), - 'utf-8', - ); + const pbx = readFileSync(join(config.ios.nativeXcodeProjDirAbs, 'project.pbxproj'), 'utf-8'); const searchString = 'IPHONEOS_DEPLOYMENT_TARGET = '; const iosVersion = pbx.substring( pbx.indexOf(searchString) + searchString.length, diff --git a/cli/src/util/subprocess.ts b/cli/src/util/subprocess.ts index 2b8015e8b..b6067c4ec 100644 --- a/cli/src/util/subprocess.ts +++ b/cli/src/util/subprocess.ts @@ -16,13 +16,7 @@ export async function runCommand( } catch (e) { if (e instanceof SubprocessError) { // old behavior of just throwing the stdout/stderr strings - throw e.output - ? e.output - : e.code - ? e.code - : e.error - ? e.error.message - : 'Unknown error'; + throw e.output ? e.output : e.code ? e.code : e.error ? e.error.message : 'Unknown error'; } throw e; diff --git a/cli/src/util/term.ts b/cli/src/util/term.ts index 596b7ae3b..dcbed63f5 100644 --- a/cli/src/util/term.ts +++ b/cli/src/util/term.ts @@ -18,17 +18,14 @@ export const checkInteractive = (...args: string[]): boolean => { // Make sure none of the provided args are empty, otherwise print the interactive // warning and return false - if (args.filter(arg => !arg).length) { + if (args.filter((arg) => !arg).length) { logger.error( `Non-interactive shell detected.\n` + - `Run the command with ${c.input( - '--help', - )} to see a list of arguments that must be provided.`, + `Run the command with ${c.input('--help')} to see a list of arguments that must be provided.`, ); return false; } return true; }; -export const isInteractive = (): boolean => - TERMINAL_INFO.tty && !TERMINAL_INFO.ci; +export const isInteractive = (): boolean => TERMINAL_INFO.tty && !TERMINAL_INFO.ci; diff --git a/cli/src/util/uuid.ts b/cli/src/util/uuid.ts index 9e66b50f0..b07357bb2 100644 --- a/cli/src/util/uuid.ts +++ b/cli/src/util/uuid.ts @@ -1,5 +1,5 @@ export function uuidv4(): string { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c == 'x' ? r : (r & 0x3) | 0x8; diff --git a/cli/src/util/xml.ts b/cli/src/util/xml.ts index 7cd39a66c..3425bbfb1 100644 --- a/cli/src/util/xml.ts +++ b/cli/src/util/xml.ts @@ -15,10 +15,7 @@ export async function readXML(path: string): Promise { } export function parseXML(xmlStr: string, options?: xml2js.OptionsV2): any { - const parser = - options !== undefined - ? new xml2js.Parser({ ...options }) - : new xml2js.Parser(); + const parser = options !== undefined ? new xml2js.Parser({ ...options }) : new xml2js.Parser(); let xmlObj; parser.parseString(xmlStr, (err: any, result: any) => { if (!err) { @@ -29,7 +26,7 @@ export function parseXML(xmlStr: string, options?: xml2js.OptionsV2): any { } export async function writeXML(object: any): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { const builder = new xml2js.Builder({ headless: true, explicitRoot: false, diff --git a/cli/test/add.android.spec.ts b/cli/test/add.android.spec.ts index a003ec939..f8e6ae0ec 100644 --- a/cli/test/add.android.spec.ts +++ b/cli/test/add.android.spec.ts @@ -1,86 +1,60 @@ -import { - APP_ID, - APP_NAME, - run, - makeAppDir, - MappedFS, - installPlatform, -} from './util'; - -describe.each([false, true])( - 'Add: Android (monoRepoLike: %p)', - monoRepoLike => { - let appDirObj: any; - let FS: MappedFS; - - beforeAll(async () => { - // These commands are slowww... - jest.setTimeout(150000); - appDirObj = await makeAppDir(monoRepoLike); - const appDir = appDirObj.appDir; - // Init in this directory so we can test add - await run(appDir, `init "${APP_NAME}" "${APP_ID}"`); - await installPlatform(appDir, 'android'); - await run(appDir, `add android`); - FS = new MappedFS(appDir); - }); - - afterAll(() => { - appDirObj.cleanupCallback(); - }); - - it('Should add', async () => { - expect(await FS.exists('android/')).toBe(true); - }); - - it('Should have Cordova JS copied', async () => { - expect( - await FS.exists('android/app/src/main/assets/public/cordova.js'), - ).toBe(true); - expect( - await FS.exists( - 'android/app/src/main/assets/public/cordova_plugins.js', - ), - ).toBe(true); - }); - - it('Should rename package', async () => { - expect( - await FS.exists( - 'android/app/src/main/java/com/getcapacitor/cli/test/MainActivity.java', - ), - ).toBe(true); - }); - - it('Should rename package in main activity', async () => { - const activityContent = await FS.read( - 'android/app/src/main/java/com/getcapacitor/cli/test/MainActivity.java', - ); - const regex = new RegExp(`package ${APP_ID};`); - expect(regex.test(activityContent)).toBe(true); - }); - - it('Should rename app id in build.gradle', async () => { - const gradleContent = await FS.read('android/app/build.gradle'); - const regex = new RegExp(`applicationId "${APP_ID}"`); - expect(regex.test(gradleContent)).toBe(true); - }); - - it('Should update strings.xml', async () => { - const stringsContent = await FS.read( - 'android/app/src/main/res/values/strings.xml', - ); - let regex = new RegExp(`${APP_NAME}`); - expect(regex.test(stringsContent)).toBe(true); - regex = new RegExp( - `${APP_NAME}`, - ); - expect(regex.test(stringsContent)).toBe(true); - regex = new RegExp(`${APP_ID}`); - expect(regex.test(stringsContent)).toBe(true); - }); - - // Other test ideas: - // should install/copy pre-existing cordova/capacitor plugins in package.json - }, -); +import { APP_ID, APP_NAME, run, makeAppDir, MappedFS, installPlatform } from './util'; + +describe.each([false, true])('Add: Android (monoRepoLike: %p)', (monoRepoLike) => { + let appDirObj: any; + let FS: MappedFS; + + beforeAll(async () => { + // These commands are slowww... + jest.setTimeout(150000); + appDirObj = await makeAppDir(monoRepoLike); + const appDir = appDirObj.appDir; + // Init in this directory so we can test add + await run(appDir, `init "${APP_NAME}" "${APP_ID}"`); + await installPlatform(appDir, 'android'); + await run(appDir, `add android`); + FS = new MappedFS(appDir); + }); + + afterAll(() => { + appDirObj.cleanupCallback(); + }); + + it('Should add', async () => { + expect(await FS.exists('android/')).toBe(true); + }); + + it('Should have Cordova JS copied', async () => { + expect(await FS.exists('android/app/src/main/assets/public/cordova.js')).toBe(true); + expect(await FS.exists('android/app/src/main/assets/public/cordova_plugins.js')).toBe(true); + }); + + it('Should rename package', async () => { + expect(await FS.exists('android/app/src/main/java/com/getcapacitor/cli/test/MainActivity.java')).toBe(true); + }); + + it('Should rename package in main activity', async () => { + const activityContent = await FS.read('android/app/src/main/java/com/getcapacitor/cli/test/MainActivity.java'); + const regex = new RegExp(`package ${APP_ID};`); + expect(regex.test(activityContent)).toBe(true); + }); + + it('Should rename app id in build.gradle', async () => { + const gradleContent = await FS.read('android/app/build.gradle'); + const regex = new RegExp(`applicationId "${APP_ID}"`); + expect(regex.test(gradleContent)).toBe(true); + }); + + it('Should update strings.xml', async () => { + const stringsContent = await FS.read('android/app/src/main/res/values/strings.xml'); + let regex = new RegExp(`${APP_NAME}`); + expect(regex.test(stringsContent)).toBe(true); + regex = new RegExp(`${APP_NAME}`); + expect(regex.test(stringsContent)).toBe(true); + regex = new RegExp(`${APP_ID}`); + expect(regex.test(stringsContent)).toBe(true); + }); + + // Other test ideas: + // should install/copy pre-existing cordova/capacitor plugins in package.json +}); diff --git a/cli/test/add.ios.spec.ts b/cli/test/add.ios.spec.ts index 2aea2d536..21b210894 100644 --- a/cli/test/add.ios.spec.ts +++ b/cli/test/add.ios.spec.ts @@ -1,13 +1,6 @@ -import { - APP_ID, - APP_NAME, - run, - makeAppDir, - MappedFS, - installPlatform, -} from './util'; +import { APP_ID, APP_NAME, run, makeAppDir, MappedFS, installPlatform } from './util'; -describe.each([false, true])('Add: iOS (monoRepoLike: %p)', monoRepoLike => { +describe.each([false, true])('Add: iOS (monoRepoLike: %p)', (monoRepoLike) => { let appDirObj: any; let FS: MappedFS; @@ -33,9 +26,7 @@ describe.each([false, true])('Add: iOS (monoRepoLike: %p)', monoRepoLike => { it('Should update Info.plist', async () => { const infoContent = await FS.read('ios/App/App/Info.plist'); - const regex = new RegExp( - `CFBundleDisplayName[^<]*${APP_NAME}`, - ); + const regex = new RegExp(`CFBundleDisplayName[^<]*${APP_NAME}`); expect(regex.test(infoContent)).toBe(true); }); diff --git a/cli/test/framework-detection.spec.ts b/cli/test/framework-detection.spec.ts index e2d07f306..46727753c 100644 --- a/cli/test/framework-detection.spec.ts +++ b/cli/test/framework-detection.spec.ts @@ -156,7 +156,6 @@ describe('framework detection', () => { }); function addDep(config: Config, depName: string) { - (config.app.package as any).dependencies = - config.app.package.dependencies || {}; + (config.app.package as any).dependencies = config.app.package.dependencies || {}; (config.app.package.dependencies as any)[depName] = '0.0.0'; } diff --git a/cli/test/update.android.spec.ts b/cli/test/update.android.spec.ts index aa2e8518c..bfa8ba5b3 100644 --- a/cli/test/update.android.spec.ts +++ b/cli/test/update.android.spec.ts @@ -1,45 +1,32 @@ -import { - APP_ID, - APP_NAME, - CORDOVA_PLUGIN_ID, - MappedFS, - makeAppDir, - run, - installPlatform, -} from './util'; +import { APP_ID, APP_NAME, CORDOVA_PLUGIN_ID, MappedFS, makeAppDir, run, installPlatform } from './util'; -describe.each([false, true])( - 'Update: Android (monoRepoLike: %p)', - monoRepoLike => { - let appDirObj: any; - let appDir: string; - let FS: MappedFS; +describe.each([false, true])('Update: Android (monoRepoLike: %p)', (monoRepoLike) => { + let appDirObj: any; + let appDir: string; + let FS: MappedFS; - beforeAll(async () => { - // These commands are slowww... - jest.setTimeout(150000); - appDirObj = await makeAppDir(monoRepoLike); - appDir = appDirObj.appDir; - // Init in this directory so we can test add - await run(appDir, `init "${APP_NAME}" "${APP_ID}"`); - await installPlatform(appDir, 'android'); - await run(appDir, `add android`); - FS = new MappedFS(appDir); - }); + beforeAll(async () => { + // These commands are slowww... + jest.setTimeout(150000); + appDirObj = await makeAppDir(monoRepoLike); + appDir = appDirObj.appDir; + // Init in this directory so we can test add + await run(appDir, `init "${APP_NAME}" "${APP_ID}"`); + await installPlatform(appDir, 'android'); + await run(appDir, `add android`); + FS = new MappedFS(appDir); + }); - afterAll(() => { - //appDirObj.cleanupCallback(); - }); + afterAll(() => { + //appDirObj.cleanupCallback(); + }); - it('Should install Cordova plugin JS', async () => { - const cordovaPluginJSContent = await FS.read( - 'android/app/src/main/assets/public/cordova_plugins.js', - ); - const regex = new RegExp(CORDOVA_PLUGIN_ID); - expect(regex.test(cordovaPluginJSContent)).toBe(true); - }); + it('Should install Cordova plugin JS', async () => { + const cordovaPluginJSContent = await FS.read('android/app/src/main/assets/public/cordova_plugins.js'); + const regex = new RegExp(CORDOVA_PLUGIN_ID); + expect(regex.test(cordovaPluginJSContent)).toBe(true); + }); - // Other test ideas: - // should install/copy pre-existing cordova/capacitor plugins in package.json - }, -); + // Other test ideas: + // should install/copy pre-existing cordova/capacitor plugins in package.json +}); diff --git a/cli/test/update.ios.spec.ts b/cli/test/update.ios.spec.ts index 317e5cce5..37684e938 100644 --- a/cli/test/update.ios.spec.ts +++ b/cli/test/update.ios.spec.ts @@ -1,14 +1,6 @@ -import { - APP_ID, - APP_NAME, - CORDOVA_PLUGIN_ID, - MappedFS, - makeAppDir, - run, - installPlatform, -} from './util'; +import { APP_ID, APP_NAME, CORDOVA_PLUGIN_ID, MappedFS, makeAppDir, run, installPlatform } from './util'; -describe.each([false, true])('Update: iOS (monoRepoLike: %p)', monoRepoLike => { +describe.each([false, true])('Update: iOS (monoRepoLike: %p)', (monoRepoLike) => { let appDirObj: any; let appDir: string; let FS: MappedFS; @@ -30,9 +22,7 @@ describe.each([false, true])('Update: iOS (monoRepoLike: %p)', monoRepoLike => { }); it('Should install Cordova plugin JS', async () => { - const cordovaPluginJSContent = await FS.read( - 'ios/App/App/public/cordova_plugins.js', - ); + const cordovaPluginJSContent = await FS.read('ios/App/App/public/cordova_plugins.js'); const regex = new RegExp(CORDOVA_PLUGIN_ID); expect(regex.test(cordovaPluginJSContent)).toBe(true); }); diff --git a/cli/test/util.ts b/cli/test/util.ts index 4111296ec..6f605d776 100644 --- a/cli/test/util.ts +++ b/cli/test/util.ts @@ -1,10 +1,4 @@ -import { - mkdir, - mkdirp, - readFile, - pathExists, - writeFile, -} from '@ionic/utils-fs'; +import { mkdir, mkdirp, readFile, pathExists, writeFile } from '@ionic/utils-fs'; import { exec } from 'child_process'; import { join, resolve } from 'path'; import tmp from 'tmp'; @@ -27,21 +21,15 @@ export async function makeConfig(appRoot: string): Promise { return config; } -export async function run( - appRoot: string, - capCommand: string, -): Promise { +export async function run(appRoot: string, capCommand: string): Promise { return new Promise((resolve, reject) => { - exec( - `cd "${appRoot}" && "${cwd}/bin/capacitor" ${capCommand}`, - (error, stdout, stderr) => { - if (error) { - reject(stdout + stderr); - } else { - resolve(stdout); - } - }, - ); + exec(`cd "${appRoot}" && "${cwd}/bin/capacitor" ${capCommand}`, (error, stdout, stderr) => { + if (error) { + reject(stdout + stderr); + } else { + resolve(stdout); + } + }); }); } @@ -49,7 +37,7 @@ export function mktmp(): Promise<{ cleanupCallback: DirCallback; path: string; }> { - return new Promise(resolve => { + return new Promise((resolve) => { tmp.dir((err, path, cleanupCallback) => { if (err) { throw err; @@ -76,10 +64,7 @@ const APP_INDEX = ` `; -export async function installPlatform( - appDir: string, - platform: string, -): Promise { +export async function installPlatform(appDir: string, platform: string): Promise { const platformPath = resolve(cwd, '..', platform); await runCommand('npm', ['install', platformPath], { cwd: appDir }); } @@ -87,9 +72,7 @@ export async function installPlatform( export async function makeAppDir(monoRepoLike = false): Promise { const appDirObj: any = await mktmp(); const tmpDir = appDirObj.path; - const rootDir = monoRepoLike - ? join(tmpDir, 'test-root') - : join(tmpDir, 'test-app'); + const rootDir = monoRepoLike ? join(tmpDir, 'test-root') : join(tmpDir, 'test-app'); if (monoRepoLike) { await mkdir(rootDir); } @@ -194,10 +177,7 @@ async function makeCordovaPlugin(cordovaPluginPath: string) { await mkdirp(cordovaPluginPath); await writeFile(join(cordovaPluginPath, 'plugin.js'), CODOVA_PLUGIN_JS); await writeFile(join(cordovaPluginPath, 'plugin.xml'), CORDOVA_PLUGIN_XML); - await writeFile( - join(cordovaPluginPath, 'package.json'), - CORDOVA_PLUGIN_PACKAGE, - ); + await writeFile(join(cordovaPluginPath, 'package.json'), CORDOVA_PLUGIN_PACKAGE); await mkdirp(iosPath); await mkdirp(androidPath); await writeFile(join(iosPath, 'CoolPlugin.m'), ''); diff --git a/core/cordova.js b/core/cordova.js index 3c42fcab5..230a57462 100644 --- a/core/cordova.js +++ b/core/cordova.js @@ -41,10 +41,7 @@ var resultantId = id; // Its a relative path, so lop off the last portion and add the id (minus "./") if (id.charAt(0) === '.') { - resultantId = - module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + - SEPARATOR + - id.slice(2); + resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2); } return require(resultantId); }; @@ -58,8 +55,7 @@ if (!modules[id]) { throw 'module ' + id + ' not found'; } else if (id in inProgressModules) { - var cycle = - requireStack.slice(inProgressModules[id]).join('->') + '->' + id; + var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id; throw 'Cycle in require graph: ' + cycle; } if (modules[id].factory) { @@ -259,13 +255,7 @@ * Called by native code when returning successful result from an action. */ callbackSuccess: function (callbackId, args) { - cordova.callbackFromNative( - callbackId, - true, - args.status, - [args.message], - args.keepCallback, - ); + cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback); }, /** @@ -274,25 +264,13 @@ callbackError: function (callbackId, args) { // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative. // Derive success from status. - cordova.callbackFromNative( - callbackId, - false, - args.status, - [args.message], - args.keepCallback, - ); + cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback); }, /** * Called by native code when returning the result from an action. */ - callbackFromNative: function ( - callbackId, - isSuccess, - status, - args, - keepCallback, - ) { + callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) { try { var callback = cordova.callbacks[callbackId]; if (callback) { @@ -314,13 +292,7 @@ } } } catch (err) { - var msg = - 'Error in ' + - (isSuccess ? 'Success' : 'Error') + - ' callbackId: ' + - callbackId + - ' : ' + - err; + var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err; console && console.log && console.log(msg); cordova.fireWindowEvent('cordovacallbackerror', { message: msg }); throw err; @@ -418,10 +390,7 @@ }; base64.toArrayBuffer = function (str) { - var decodedStr = - typeof atob !== 'undefined' - ? atob(str) - : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undef + var decodedStr = typeof atob !== 'undefined' ? atob(str) : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undef var arrayBuffer = new ArrayBuffer(decodedStr.length); var array = new Uint8Array(arrayBuffer); for (var i = 0, len = decodedStr.length; i < len; i++) { @@ -437,8 +406,7 @@ * platforms tested. */ - var b64_6bit = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64_12bit; var b64_12bitTable = function () { @@ -527,35 +495,20 @@ if (clobber) { // Clobber if it doesn't exist. if (typeof parent[key] === 'undefined') { - assignOrWrapInDeprecateGetter( - parent, - key, - result, - obj.deprecated, - ); + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else if (typeof obj.path !== 'undefined') { // If merging, merge properties onto parent, otherwise, clobber. if (merge) { recursiveMerge(parent[key], result); } else { - assignOrWrapInDeprecateGetter( - parent, - key, - result, - obj.deprecated, - ); + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } } result = parent[key]; } else { // Overwrite if not currently defined. if (typeof parent[key] === 'undefined') { - assignOrWrapInDeprecateGetter( - parent, - key, - result, - obj.deprecated, - ); + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else { // Set result to what already exists, so we can build children into it if they exist. result = parent[key]; @@ -566,13 +519,7 @@ include(result, obj.children, clobber, merge); } } catch (e) { - utils.alert( - 'Exception building Cordova JS globals: ' + - e + - ' for key "' + - key + - '"', - ); + utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"'); } }); } @@ -591,10 +538,7 @@ // If the target object is a constructor override off prototype. clobber(target.prototype, prop, src[prop]); } else { - if ( - typeof src[prop] === 'object' && - typeof target[prop] === 'object' - ) { + if (typeof src[prop] === 'object' && typeof target[prop] === 'object') { recursiveMerge(target[prop], src[prop]); } else { clobber(target, prop, src[prop]); @@ -737,13 +681,9 @@ }; function checkSubscriptionArgument(argument) { - if ( - typeof argument !== 'function' && - typeof argument.handleEvent !== 'function' - ) { + if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') { throw new Error( - 'Must provide a function or an EventListener object ' + - 'implementing the handleEvent interface.', + 'Must provide a function or an EventListener object ' + 'implementing the handleEvent interface.', ); } } @@ -755,17 +695,11 @@ * and a guid that can be used to stop subscribing to the channel. * Returns the guid. */ - Channel.prototype.subscribe = function ( - eventListenerOrFunction, - eventListener, - ) { + Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) { checkSubscriptionArgument(eventListenerOrFunction); var handleEvent, guid; - if ( - eventListenerOrFunction && - typeof eventListenerOrFunction === 'object' - ) { + if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') { // Received an EventListener object implementing the handleEvent interface handleEvent = eventListenerOrFunction.handleEvent; eventListener = eventListenerOrFunction; @@ -808,10 +742,7 @@ checkSubscriptionArgument(eventListenerOrFunction); var handleEvent, guid, handler; - if ( - eventListenerOrFunction && - typeof eventListenerOrFunction === 'object' - ) { + if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') { // Received an EventListener object implementing the handleEvent interface handleEvent = eventListenerOrFunction.handleEvent; } else { @@ -1013,11 +944,7 @@ }; if (window.androidBridge) { window.androidBridge.postMessage(JSON.stringify(command)); - } else if ( - window.webkit && - window.webkit.messageHandlers && - window.webkit.messageHandlers.bridge - ) { + } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.bridge) { window.webkit.messageHandlers.bridge.postMessage(command); } }; @@ -1043,13 +970,7 @@ var actionArgs = command[3]; var callbacks = cordova.callbacks[callbackId] || {}; - execProxy( - callbacks.success, - callbacks.fail, - service, - action, - actionArgs, - ); + execProxy(callbacks.success, callbacks.fail, service, action, actionArgs); commandString = commandQueue.shift(); } @@ -1107,23 +1028,11 @@ return json; }; - capacitorExec.nativeCallback = function ( - callbackId, - status, - message, - keepCallback, - debug, - ) { + capacitorExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) { var success = status === 0 || status === 1; var args = convertMessageToArgsNativeToJs(message); Promise.resolve().then(function () { - cordova.callbackFromNative( - callbackId, - success, - status, - args, - keepCallback, - ); // eslint-disable-line + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line }); }; @@ -1186,9 +1095,7 @@ }, get: function (service, action) { - return CommandProxyMap[service] - ? CommandProxyMap[service][action] - : null; + return CommandProxyMap[service] ? CommandProxyMap[service][action] : null; }, }; }); @@ -1202,10 +1109,7 @@ var pluginloader = require('cordova/pluginloader'); var utils = require('cordova/utils'); - var platformInitChannelsArray = [ - channel.onNativeReady, - channel.onPluginsReady, - ]; + var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady]; function logUnfiredChannels(arr) { for (var i = 0; i < arr.length; ++i) { @@ -1255,14 +1159,10 @@ channel.onPause = cordova.addDocumentEventHandler('pause'); channel.onResume = cordova.addDocumentEventHandler('resume'); channel.onActivated = cordova.addDocumentEventHandler('activated'); - channel.onDeviceReady = - cordova.addStickyDocumentEventHandler('deviceready'); + channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); // Listen for DOMContentLoaded and notify our channel subscribers. - if ( - document.readyState === 'complete' || - document.readyState === 'interactive' - ) { + if (document.readyState === 'complete' || document.readyState === 'interactive') { channel.onDOMContentLoaded.fire(); } else { document.addEventListener( @@ -1328,12 +1228,7 @@ deprecationMap = {}; }; - function addEntry( - strategy, - moduleName, - symbolPath, - opt_deprecationMessage, - ) { + function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) { if (!(moduleName in moduleMap)) { throw new Error('Module ' + moduleName + ' does not exist.'); } @@ -1344,11 +1239,7 @@ } // Note: Android 2.3 does have Function.bind(). - exports.clobbers = function ( - moduleName, - symbolPath, - opt_deprecationMessage, - ) { + exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) { addEntry('c', moduleName, symbolPath, opt_deprecationMessage); }; @@ -1356,11 +1247,7 @@ addEntry('m', moduleName, symbolPath, opt_deprecationMessage); }; - exports.defaults = function ( - moduleName, - symbolPath, - opt_deprecationMessage, - ) { + exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) { addEntry('d', moduleName, symbolPath, opt_deprecationMessage); }; @@ -1399,10 +1286,7 @@ var deprecationMsg = symbolPath in deprecationMap - ? 'Access made to deprecated symbol: ' + - symbolPath + - '. ' + - deprecationMsg + ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null; var parentObj = prepareNamespace(namespace, context); var target = parentObj[lastName]; @@ -1413,12 +1297,7 @@ if (!(symbolPath in origSymbols)) { origSymbols[symbolPath] = target; } - builder.assignOrWrapInDeprecateGetter( - parentObj, - lastName, - module, - deprecationMsg, - ); + builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg); } } }; @@ -1578,12 +1457,7 @@ * Does a deep clone of the object. */ utils.clone = function (obj) { - if ( - !obj || - typeof obj === 'function' || - utils.isDate(obj) || - typeof obj !== 'object' - ) { + if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') { return obj; } @@ -1602,11 +1476,7 @@ // https://issues.apache.org/jira/browse/CB-11522 'unknown' type may be returned in // custom protocol activation case on Windows Phone 8.1 causing "No such interface supported" exception // on cloning. - if ( - (!(i in retVal) || retVal[i] !== obj[i]) && - typeof obj[i] !== 'undefined' && - typeof obj[i] !== 'unknown' - ) { + if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') { // eslint-disable-line valid-typeof retVal[i] = utils.clone(obj[i]); } diff --git a/core/native-bridge.ts b/core/native-bridge.ts index f224a7fa6..4095f35e5 100644 --- a/core/native-bridge.ts +++ b/core/native-bridge.ts @@ -65,9 +65,7 @@ const convertBody = async ( if (done) break; chunks.push(value); } - const concatenated = new Uint8Array( - chunks.reduce((acc, chunk) => acc + chunk.length, 0), - ); + const concatenated = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0)); let position = 0; for (const chunk of chunks) { concatenated.set(chunk, position); @@ -130,9 +128,7 @@ const CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM = 'u'; // TODO: export as Cap function const isRelativeOrProxyUrl = (url: string | undefined): boolean => - !url || - !(url.startsWith('http:') || url.startsWith('https:')) || - url.indexOf(CAPACITOR_HTTP_INTERCEPTOR) > -1; + !url || !(url.startsWith('http:') || url.startsWith('https:')) || url.indexOf(CAPACITOR_HTTP_INTERCEPTOR) > -1; // TODO: export as Cap function const createProxyUrl = (url: string, win: WindowCapacitor): string => { @@ -155,22 +151,14 @@ const initBridge = (w: any): void => { } }; - const convertFileSrcServerUrl = ( - webviewServerUrl: string, - filePath: string, - ): string => { + const convertFileSrcServerUrl = (webviewServerUrl: string, filePath: string): string => { if (typeof filePath === 'string') { if (filePath.startsWith('/')) { return webviewServerUrl + '/_capacitor_file_' + filePath; } else if (filePath.startsWith('file://')) { - return ( - webviewServerUrl + filePath.replace('file://', '/_capacitor_file_') - ); + return webviewServerUrl + filePath.replace('file://', '/_capacitor_file_'); } else if (filePath.startsWith('content://')) { - return ( - webviewServerUrl + - filePath.replace('content:/', '/_capacitor_content_') - ); + return webviewServerUrl + filePath.replace('content:/', '/_capacitor_content_'); } } return filePath; @@ -330,81 +318,56 @@ const initBridge = (w: any): void => { }; const initLogger = (win: WindowCapacitor, cap: CapacitorInstance) => { - const BRIDGED_CONSOLE_METHODS: (keyof Console)[] = [ - 'debug', - 'error', - 'info', - 'log', - 'trace', - 'warn', - ]; - - const createLogFromNative = - (c: Partial) => (result: PluginResult) => { - if (isFullConsole(c)) { - const success = result.success === true; - - const tagStyles = success - ? 'font-style: italic; font-weight: lighter; color: gray' - : 'font-style: italic; font-weight: lighter; color: red'; - - c.groupCollapsed( - '%cresult %c' + - result.pluginId + - '.' + - result.methodName + - ' (#' + - result.callbackId + - ')', - tagStyles, - 'font-style: italic; font-weight: bold; color: #444', - ); - if (result.success === false) { - c.error(result.error); - } else { - c.dir(result.data); - } - c.groupEnd(); + const BRIDGED_CONSOLE_METHODS: (keyof Console)[] = ['debug', 'error', 'info', 'log', 'trace', 'warn']; + + const createLogFromNative = (c: Partial) => (result: PluginResult) => { + if (isFullConsole(c)) { + const success = result.success === true; + + const tagStyles = success + ? 'font-style: italic; font-weight: lighter; color: gray' + : 'font-style: italic; font-weight: lighter; color: red'; + + c.groupCollapsed( + '%cresult %c' + result.pluginId + '.' + result.methodName + ' (#' + result.callbackId + ')', + tagStyles, + 'font-style: italic; font-weight: bold; color: #444', + ); + if (result.success === false) { + c.error(result.error); } else { - if (result.success === false) { - c.error('LOG FROM NATIVE', result.error); - } else { - c.log('LOG FROM NATIVE', result.data); - } + c.dir(result.data); } - }; - - const createLogToNative = - (c: Partial) => (call: MessageCallData) => { - if (isFullConsole(c)) { - c.groupCollapsed( - '%cnative %c' + - call.pluginId + - '.' + - call.methodName + - ' (#' + - call.callbackId + - ')', - 'font-weight: lighter; color: gray', - 'font-weight: bold; color: #000', - ); - c.dir(call); - c.groupEnd(); + c.groupEnd(); + } else { + if (result.success === false) { + c.error('LOG FROM NATIVE', result.error); } else { - c.log('LOG TO NATIVE: ', call); + c.log('LOG FROM NATIVE', result.data); } - }; + } + }; + + const createLogToNative = (c: Partial) => (call: MessageCallData) => { + if (isFullConsole(c)) { + c.groupCollapsed( + '%cnative %c' + call.pluginId + '.' + call.methodName + ' (#' + call.callbackId + ')', + 'font-weight: lighter; color: gray', + 'font-weight: bold; color: #000', + ); + c.dir(call); + c.groupEnd(); + } else { + c.log('LOG TO NATIVE: ', call); + } + }; const isFullConsole = (c: Partial): c is Console => { if (!c) { return false; } - return ( - typeof c.groupCollapsed === 'function' || - typeof c.groupEnd === 'function' || - typeof c.dir === 'function' - ); + return typeof c.groupCollapsed === 'function' || typeof c.groupEnd === 'function' || typeof c.dir === 'function'; }; const serializeConsoleMessage = (msg: any): string => { @@ -442,8 +405,7 @@ const initBridge = (w: any): void => { doPatchCookies = true; } } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { - const isCookiesEnabled = - win.CapacitorCookiesAndroidInterface.isEnabled(); + const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); if (isCookiesEnabled === true) { doPatchCookies = true; } @@ -462,9 +424,7 @@ const initBridge = (w: any): void => { const res = prompt(JSON.stringify(payload)); return res; - } else if ( - typeof win.CapacitorCookiesAndroidInterface !== 'undefined' - ) { + } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { // return original document.cookie since Android does not support filtering of `httpOnly` cookies return win.CapacitorCookiesDescriptor?.get?.call(document) ?? ''; } @@ -473,9 +433,7 @@ const initBridge = (w: any): void => { const cookiePairs = val.split(';'); const domainSection = val.toLowerCase().split('domain=')[1]; const domain = - cookiePairs.length > 1 && - domainSection != null && - domainSection.length > 0 + cookiePairs.length > 1 && domainSection != null && domainSection.length > 0 ? domainSection.split(';')[0].trim() : ''; @@ -490,9 +448,7 @@ const initBridge = (w: any): void => { }; prompt(JSON.stringify(payload)); - } else if ( - typeof win.CapacitorCookiesAndroidInterface !== 'undefined' - ) { + } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { win.CapacitorCookiesAndroidInterface.setCookie(domain, val); } }, @@ -506,8 +462,7 @@ const initBridge = (w: any): void => { abort: window.XMLHttpRequest.prototype.abort, constructor: window.XMLHttpRequest.prototype.constructor, fullObject: window.XMLHttpRequest, - getAllResponseHeaders: - window.XMLHttpRequest.prototype.getAllResponseHeaders, + getAllResponseHeaders: window.XMLHttpRequest.prototype.getAllResponseHeaders, getResponseHeader: window.XMLHttpRequest.prototype.getResponseHeader, open: window.XMLHttpRequest.prototype.open, prototype: window.XMLHttpRequest.prototype, @@ -539,10 +494,7 @@ const initBridge = (w: any): void => { if (doPatchHttp) { // fetch patch - window.fetch = async ( - resource: RequestInfo | URL, - options?: RequestInit, - ) => { + window.fetch = async (resource: RequestInfo | URL, options?: RequestInit) => { const request = new Request(resource, options); if (request.url.startsWith(`${cap.getServerUrl()}/`)) { return win.CapacitorWebFetch(resource, options); @@ -555,15 +507,9 @@ const initBridge = (w: any): void => { method.toLocaleUpperCase() === 'TRACE' ) { if (typeof resource === 'string') { - return await win.CapacitorWebFetch( - createProxyUrl(resource, win), - options, - ); + return await win.CapacitorWebFetch(createProxyUrl(resource, win), options); } else if (resource instanceof Request) { - const modifiedRequest = new Request( - createProxyUrl(resource.url, win), - resource, - ); + const modifiedRequest = new Request(createProxyUrl(resource.url, win), resource); return await win.CapacitorWebFetch(modifiedRequest, options); } } @@ -583,24 +529,18 @@ const initBridge = (w: any): void => { optionHeaders['Content-Type'] || optionHeaders['content-type'], ); - const nativeResponse: HttpResponse = await cap.nativePromise( - 'CapacitorHttp', - 'request', - { - url: request.url, - method: method, - data: requestData, - dataType: type, - headers: { - ...headers, - ...optionHeaders, - }, + const nativeResponse: HttpResponse = await cap.nativePromise('CapacitorHttp', 'request', { + url: request.url, + method: method, + data: requestData, + dataType: type, + headers: { + ...headers, + ...optionHeaders, }, - ); + }); - const contentType = - nativeResponse.headers['Content-Type'] || - nativeResponse.headers['content-type']; + const contentType = nativeResponse.headers['Content-Type'] || nativeResponse.headers['content-type']; let data = contentType?.startsWith('application/json') ? JSON.stringify(nativeResponse.data) : nativeResponse.data; @@ -654,8 +594,7 @@ const initBridge = (w: any): void => { const prototype = win.CapacitorWebXMLHttpRequest.prototype; const isProgressEventAvailable = () => - typeof ProgressEvent !== 'undefined' && - ProgressEvent.prototype instanceof Event; + typeof ProgressEvent !== 'undefined' && ProgressEvent.prototype instanceof Event; // XHR patch abort prototype.abort = function () { @@ -682,20 +621,12 @@ const initBridge = (w: any): void => { this._method === 'TRACE' ) { if (isRelativeOrProxyUrl(url)) { - return win.CapacitorWebXMLHttpRequest.open.call( - this, - method, - url, - ); + return win.CapacitorWebXMLHttpRequest.open.call(this, method, url); } this._url = createProxyUrl(this._url, win); - return win.CapacitorWebXMLHttpRequest.open.call( - this, - method, - this._url, - ); + return win.CapacitorWebXMLHttpRequest.open.call(this, method, this._url); } Object.defineProperties(this, { readyState: { @@ -717,16 +648,9 @@ const initBridge = (w: any): void => { }; // XHR patch set request header - prototype.setRequestHeader = function ( - header: string, - value: string, - ) { + prototype.setRequestHeader = function (header: string, value: string) { if (isRelativeOrProxyUrl(this._url)) { - return win.CapacitorWebXMLHttpRequest.setRequestHeader.call( - this, - header, - value, - ); + return win.CapacitorWebXMLHttpRequest.setRequestHeader.call(this, header, value); } this._headers[header] = value; }; @@ -737,9 +661,7 @@ const initBridge = (w: any): void => { return win.CapacitorWebXMLHttpRequest.send.call(this, body); } - const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${ - this._url - }`; + const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${this._url}`; console.time(tag); try { @@ -766,9 +688,7 @@ const initBridge = (w: any): void => { convertBody(body).then(({ data, type, headers }) => { const otherHeaders = - this._headers != null && Object.keys(this._headers).length > 0 - ? this._headers - : undefined; + this._headers != null && Object.keys(this._headers).length > 0 ? this._headers : undefined; // intercept request & pass to the bridge cap @@ -797,10 +717,7 @@ const initBridge = (w: any): void => { } this._headers = nativeResponse.headers; this.status = nativeResponse.status; - if ( - this.responseType === '' || - this.responseType === 'text' - ) { + if (this.responseType === '' || this.responseType === 'text') { this.response = typeof nativeResponse.data !== 'string' ? JSON.stringify(nativeResponse.data) @@ -809,8 +726,7 @@ const initBridge = (w: any): void => { this.response = nativeResponse.data; } this.responseText = ( - nativeResponse.headers['Content-Type'] || - nativeResponse.headers['content-type'] + nativeResponse.headers['Content-Type'] || nativeResponse.headers['content-type'] )?.startsWith('application/json') ? JSON.stringify(nativeResponse.data) : nativeResponse.data; @@ -873,9 +789,7 @@ const initBridge = (w: any): void => { // XHR patch getAllResponseHeaders prototype.getAllResponseHeaders = function () { if (isRelativeOrProxyUrl(this._url)) { - return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call( - this, - ); + return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call(this); } let returnString = ''; @@ -890,10 +804,7 @@ const initBridge = (w: any): void => { // XHR patch getResponseHeader prototype.getResponseHeader = function (name: string) { if (isRelativeOrProxyUrl(this._url)) { - return win.CapacitorWebXMLHttpRequest.getResponseHeader.call( - this, - name, - ); + return win.CapacitorWebXMLHttpRequest.getResponseHeader.call(this, name); } return this._headers[name]; }; @@ -902,10 +813,7 @@ const initBridge = (w: any): void => { return xhr; } as unknown as PatchedXMLHttpRequestConstructor; - Object.assign( - window.XMLHttpRequest, - win.CapacitorWebXMLHttpRequest.fullObject, - ); + Object.assign(window.XMLHttpRequest, win.CapacitorWebXMLHttpRequest.fullObject); } } @@ -950,7 +858,7 @@ const initBridge = (w: any): void => { cap.logToNative = createLogToNative(win.console); cap.logFromNative = createLogFromNative(win.console); - cap.handleError = err => win.console.error(err); + cap.handleError = (err) => win.console.error(err); win.Capacitor = cap; }; @@ -961,11 +869,9 @@ const initBridge = (w: any): void => { // keep a collection of callbacks for native response data const callbacks = new Map(); - const webviewServerUrl = - typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : ''; + const webviewServerUrl = typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : ''; cap.getServerUrl = () => webviewServerUrl; - cap.convertFileSrc = filePath => - convertFileSrcServerUrl(webviewServerUrl, filePath); + cap.convertFileSrc = (filePath) => convertFileSrcServerUrl(webviewServerUrl, filePath); // Counter of callback ids, randomized to avoid // any issues during reloads if a call comes back with @@ -978,14 +884,13 @@ const initBridge = (w: any): void => { const getPlatform = () => getPlatformId(win); cap.getPlatform = getPlatform; - cap.isPluginAvailable = name => - Object.prototype.hasOwnProperty.call(cap.Plugins, name); + cap.isPluginAvailable = (name) => Object.prototype.hasOwnProperty.call(cap.Plugins, name); cap.isNativePlatform = isNativePlatform; // create the postToNative() fn if needed if (getPlatformId(win) === 'android') { // android platform - postToNative = data => { + postToNative = (data) => { try { win.androidBridge.postMessage(JSON.stringify(data)); } catch (e) { @@ -994,7 +899,7 @@ const initBridge = (w: any): void => { }; } else if (getPlatformId(win) === 'ios') { // ios platform - postToNative = data => { + postToNative = (data) => { try { data.type = data.type ? data.type : 'message'; win.webkit.messageHandlers.bridge.postMessage(data); @@ -1047,8 +952,7 @@ const initBridge = (w: any): void => { if ( storedCallback && - (typeof storedCallback.callback === 'function' || - typeof storedCallback.resolve === 'function') + (typeof storedCallback.callback === 'function' || typeof storedCallback.resolve === 'function') ) { // store the call for later lookup callbackId = String(++callbackIdCount); @@ -1089,7 +993,7 @@ const initBridge = (w: any): void => { /** * Process a response from the native layer. */ - cap.fromNative = result => { + cap.fromNative = (result) => { returnResult(result); }; @@ -1153,9 +1057,7 @@ const initBridge = (w: any): void => { cap.nativeCallback = (pluginName, methodName, options, callback) => { if (typeof options === 'function') { - console.warn( - `Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`, - ); + console.warn(`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`); callback = options as any; options = null; @@ -1192,12 +1094,12 @@ initBridge( typeof globalThis !== 'undefined' ? (globalThis as WindowCapacitor) : typeof self !== 'undefined' - ? (self as WindowCapacitor) - : typeof window !== 'undefined' - ? (window as WindowCapacitor) - : typeof global !== 'undefined' - ? (global as WindowCapacitor) - : ({} as WindowCapacitor), + ? (self as WindowCapacitor) + : typeof window !== 'undefined' + ? (window as WindowCapacitor) + : typeof global !== 'undefined' + ? (global as WindowCapacitor) + : ({} as WindowCapacitor), ); // Export only for tests diff --git a/core/rollup.bridge.config.js b/core/rollup.bridge.config.js index ed686a701..9f8d90e97 100644 --- a/core/rollup.bridge.config.js +++ b/core/rollup.bridge.config.js @@ -31,7 +31,7 @@ export default { 'module.exports': 'dummy', 'exports.__esModule': 'dummy', 'exports.initBridge': 'dummy', - 'preventAssignment': false, + preventAssignment: false, }), ], }; diff --git a/core/src/core-plugins.ts b/core/src/core-plugins.ts index 4a2b21055..84cfd5fca 100644 --- a/core/src/core-plugins.ts +++ b/core/src/core-plugins.ts @@ -31,8 +31,7 @@ const encode = (str: string) => * Safely web decode a string value (inspired by js-cookie) * @param str The string value to decode */ -const decode = (str: string): string => - str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); +const decode = (str: string): string => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); export interface CapacitorCookiesPlugin { getCookies(options?: GetCookieOptions): Promise; @@ -89,14 +88,11 @@ export type SetCookieOptions = HttpCookie & HttpCookieExtras; export type DeleteCookieOptions = Omit; export type ClearCookieOptions = Omit; -export class CapacitorCookiesPluginWeb - extends WebPlugin - implements CapacitorCookiesPlugin -{ +export class CapacitorCookiesPluginWeb extends WebPlugin implements CapacitorCookiesPlugin { async getCookies(): Promise { const cookies = document.cookie; const cookieMap: HttpCookieMap = {}; - cookies.split(';').forEach(cookie => { + cookies.split(';').forEach((cookie) => { if (cookie.length <= 0) return; // Replace first "=" with CAP_COOKIE to prevent splitting on additional "=" let [key, value] = cookie.replace(/=/, 'CAP_COOKIE').split('CAP_COOKIE'); @@ -114,20 +110,12 @@ export class CapacitorCookiesPluginWeb const encodedValue = encode(options.value); // Clean & sanitize options - const expires = `; expires=${(options.expires || '').replace( - 'expires=', - '', - )}`; // Default is "; expires=" + const expires = `; expires=${(options.expires || '').replace('expires=', '')}`; // Default is "; expires=" const path = (options.path || '/').replace('path=', ''); // Default is "path=/" - const domain = - options.url != null && options.url.length > 0 - ? `domain=${options.url}` - : ''; - - document.cookie = `${encodedKey}=${ - encodedValue || '' - }${expires}; path=${path}; ${domain};`; + const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : ''; + + document.cookie = `${encodedKey}=${encodedValue || ''}${expires}; path=${path}; ${domain};`; } catch (error) { return Promise.reject(error); } @@ -145,9 +133,7 @@ export class CapacitorCookiesPluginWeb try { const cookies = document.cookie.split(';') || []; for (const cookie of cookies) { - document.cookie = cookie - .replace(/^ +/, '') - .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`); + document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`); } } catch (error) { return Promise.reject(error); @@ -163,12 +149,9 @@ export class CapacitorCookiesPluginWeb } } -export const CapacitorCookies = registerPlugin( - 'CapacitorCookies', - { - web: () => new CapacitorCookiesPluginWeb(), - }, -); +export const CapacitorCookies = registerPlugin('CapacitorCookies', { + web: () => new CapacitorCookiesPluginWeb(), +}); /******** END COOKIES PLUGIN ********/ @@ -203,12 +186,7 @@ export interface CapacitorHttpPlugin { /** * How to parse the Http response before returning it to the client. */ -export type HttpResponseType = - | 'arraybuffer' - | 'blob' - | 'json' - | 'text' - | 'document'; +export type HttpResponseType = 'arraybuffer' | 'blob' | 'json' | 'text' | 'document'; export interface HttpOptions { /** @@ -315,11 +293,7 @@ export const readBlobAsBase64 = async (blob: Blob): Promise => reader.onload = () => { const base64String = reader.result as string; // remove prefix "data:application/pdf;base64," - resolve( - base64String.indexOf(',') >= 0 - ? base64String.split(',')[1] - : base64String, - ); + resolve(base64String.indexOf(',') >= 0 ? base64String.split(',')[1] : base64String); }; reader.onerror = (error: any) => reject(error); reader.readAsDataURL(blob); @@ -331,7 +305,7 @@ export const readBlobAsBase64 = async (blob: Blob): Promise => */ const normalizeHttpHeaders = (headers: HttpHeaders = {}): HttpHeaders => { const originalKeys = Object.keys(headers); - const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase()); + const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase()); const normalized = loweredKeys.reduce((acc, key, index) => { acc[key] = headers[originalKeys[index]]; return acc; @@ -344,10 +318,7 @@ const normalizeHttpHeaders = (headers: HttpHeaders = {}): HttpHeaders => { * @param params A map of url parameters * @param shouldEncode true if you should encodeURIComponent() the values (true by default) */ -const buildUrlParams = ( - params?: HttpParams, - shouldEncode = true, -): string | null => { +const buildUrlParams = (params?: HttpParams, shouldEncode = true): string | null => { if (!params) return null; const output = Object.entries(params).reduce((accumulator, entry) => { @@ -357,7 +328,7 @@ const buildUrlParams = ( let item: string; if (Array.isArray(value)) { item = ''; - value.forEach(str => { + value.forEach((str) => { encodedValue = shouldEncode ? encodeURIComponent(str) : str; item += `${key}=${encodedValue}&`; }); @@ -380,10 +351,7 @@ const buildUrlParams = ( * @param options The Http plugin options * @param extra Any extra RequestInit values */ -export const buildRequestInit = ( - options: HttpOptions, - extra: RequestInit = {}, -): RequestInit => { +export const buildRequestInit = (options: HttpOptions, extra: RequestInit = {}): RequestInit => { const output: RequestInit = { method: options.method || 'GET', headers: options.headers, @@ -405,10 +373,7 @@ export const buildRequestInit = ( params.set(key, value as any); } output.body = params.toString(); - } else if ( - type.includes('multipart/form-data') || - options.data instanceof FormData - ) { + } else if (type.includes('multipart/form-data') || options.data instanceof FormData) { const form = new FormData(); if (options.data instanceof FormData) { options.data.forEach((value, key) => { @@ -423,10 +388,7 @@ export const buildRequestInit = ( const headers = new Headers(output.headers); headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary output.headers = headers; - } else if ( - type.includes('application/json') || - typeof options.data === 'object' - ) { + } else if (type.includes('application/json') || typeof options.data === 'object') { output.body = JSON.stringify(options.data); } @@ -434,20 +396,14 @@ export const buildRequestInit = ( }; // WEB IMPLEMENTATION -export class CapacitorHttpPluginWeb - extends WebPlugin - implements CapacitorHttpPlugin -{ +export class CapacitorHttpPluginWeb extends WebPlugin implements CapacitorHttpPlugin { /** * Perform an Http request given a set of options * @param options Options to build the HTTP request */ async request(options: HttpOptions): Promise { const requestInit = buildRequestInit(options, options.webFetchExtra); - const urlParams = buildUrlParams( - options.params, - options.shouldEncodeUrlParams, - ); + const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); const url = urlParams ? `${options.url}?${urlParams}` : options.url; const response = await fetch(url, requestInit); @@ -533,11 +489,8 @@ export class CapacitorHttpPluginWeb } } -export const CapacitorHttp = registerPlugin( - 'CapacitorHttp', - { - web: () => new CapacitorHttpPluginWeb(), - }, -); +export const CapacitorHttp = registerPlugin('CapacitorHttp', { + web: () => new CapacitorHttpPluginWeb(), +}); /******** END HTTP PLUGIN ********/ diff --git a/core/src/definitions-internal.ts b/core/src/definitions-internal.ts index 332409d97..a9179b5f4 100644 --- a/core/src/definitions-internal.ts +++ b/core/src/definitions-internal.ts @@ -1,9 +1,4 @@ -import type { - CapacitorGlobal, - PluginCallback, - PluginResultData, - PluginResultError, -} from './definitions'; +import type { CapacitorGlobal, PluginCallback, PluginResultData, PluginResultError } from './definitions'; import type { CapacitorPlatformsInstance } from './platforms'; export interface PluginHeaderMethod { @@ -47,34 +42,20 @@ export interface CapacitorInstance extends CapacitorGlobal { * Prefer using `nativeCallback()` or `nativePromise()` instead. * Returns the Callback Id. */ - toNative?: ( - pluginName: string, - methodName: string, - options: any, - storedCallback?: StoredCallback, - ) => string; + toNative?: (pluginName: string, methodName: string, options: any, storedCallback?: StoredCallback) => string; /** * Sends data over the bridge to the native layer. * Returns the Callback Id. */ - nativeCallback: ( - pluginName: string, - methodName: string, - options?: O, - callback?: PluginCallback, - ) => string; + nativeCallback: (pluginName: string, methodName: string, options?: O, callback?: PluginCallback) => string; /** * Sends data over the bridge to the native layer and * resolves the promise when it receives the data from * the native implementation. */ - nativePromise: ( - pluginName: string, - methodName: string, - options?: O, - ) => Promise; + nativePromise: (pluginName: string, methodName: string, options?: O) => Promise; /** * Low-level API used by the native layers to send @@ -90,21 +71,11 @@ export interface CapacitorInstance extends CapacitorGlobal { /** * Low-level API triggered from native implementations. */ - triggerEvent?: ( - eventName: string, - target: string, - eventData?: any, - ) => boolean; + triggerEvent?: (eventName: string, target: string, eventData?: any) => boolean; handleError: (err: Error) => void; - handleWindowError: ( - msg: string | Event, - url: string, - lineNo: number, - columnNo: number, - err: Error, - ) => void; + handleWindowError: (msg: string | Event, url: string, lineNo: number, columnNo: number, err: Error) => void; /** * Low-level API used by the native bridge to log messages. diff --git a/core/src/definitions.ts b/core/src/definitions.ts index 1471becab..1dc5d8f20 100644 --- a/core/src/definitions.ts +++ b/core/src/definitions.ts @@ -35,21 +35,12 @@ export interface CapacitorGlobal { /** * Add a listener for a plugin event. */ - addListener?: ( - pluginName: string, - eventName: string, - callback: PluginCallback, - ) => PluginListenerHandle; + addListener?: (pluginName: string, eventName: string, callback: PluginCallback) => PluginListenerHandle; /** * Remove a listener to a plugin event. */ - removeListener?: ( - pluginName: string, - callbackId: string, - eventName: string, - callback: PluginCallback, - ) => void; + removeListener?: (pluginName: string, callbackId: string, eventName: string, callback: PluginCallback) => void; DEBUG?: boolean; isLoggingEnabled?: boolean; @@ -67,11 +58,7 @@ export interface CapacitorGlobal { * logging a warning. Provided for backwards compatibility. * @deprecated Deprecated in v3, will be removed from v4 */ - pluginMethodNoop: ( - target: any, - key: PropertyKey, - pluginName: string, - ) => Promise; + pluginMethodNoop: (target: any, key: PropertyKey, pluginName: string) => Promise; /** * @deprecated Use `isNativePlatform()` instead @@ -97,10 +84,7 @@ export interface CapacitorGlobal { * @param pluginName The unique CamelCase name of this plugin. * @param implementations The map of plugin implementations. */ -export type RegisterPlugin = ( - pluginName: string, - implementations?: Readonly, -) => T; +export type RegisterPlugin = (pluginName: string, implementations?: Readonly) => T; /** * A map of plugin implementations. @@ -114,18 +98,11 @@ export type PluginImplementations = { }; export interface Plugin { - addListener( - eventName: string, - listenerFunc: (...args: any[]) => any, - ): Promise; + addListener(eventName: string, listenerFunc: (...args: any[]) => any): Promise; removeAllListeners(): Promise; } -export type PermissionState = - | 'prompt' - | 'prompt-with-rationale' - | 'granted' - | 'denied'; +export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'; export interface PluginListenerHandle { remove: () => Promise; @@ -139,7 +116,4 @@ export interface PluginResultError { message: string; } -export type PluginCallback = ( - data: PluginResultData, - error?: PluginResultError, -) => void; +export type PluginCallback = (data: PluginResultData, error?: PluginResultError) => void; diff --git a/core/src/global.ts b/core/src/global.ts index 067d2bda1..e710f6e0a 100644 --- a/core/src/global.ts +++ b/core/src/global.ts @@ -6,12 +6,12 @@ export const Capacitor = /*#__PURE__*/ initCapacitorGlobal( typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' - ? self - : typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}, + ? self + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}, ); export const registerPlugin = Capacitor.registerPlugin; @@ -34,5 +34,4 @@ export const Plugins = Capacitor.Plugins; * * @deprecated Deprecated in v3, will be removed from v4. */ -export const registerWebPlugin = (plugin: WebPlugin): void => - legacyRegisterWebPlugin(Capacitor, plugin); +export const registerWebPlugin = (plugin: WebPlugin): void => legacyRegisterWebPlugin(Capacitor, plugin); diff --git a/core/src/index.ts b/core/src/index.ts index d1a8d3fbf..64eec9307 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -20,12 +20,7 @@ export { Capacitor, registerPlugin } from './global'; export { WebPlugin, WebPluginConfig, ListenerCallback } from './web-plugin'; // Core Plugins APIs -export { - CapacitorCookies, - CapacitorHttp, - WebView, - buildRequestInit, -} from './core-plugins'; +export { CapacitorCookies, CapacitorHttp, WebView, buildRequestInit } from './core-plugins'; // Core Plugin definitions export type { diff --git a/core/src/legacy/legacy-web-plugin-merge.ts b/core/src/legacy/legacy-web-plugin-merge.ts index f60b28e8c..a27c4df36 100644 --- a/core/src/legacy/legacy-web-plugin-merge.ts +++ b/core/src/legacy/legacy-web-plugin-merge.ts @@ -1,10 +1,7 @@ import type { CapacitorGlobal } from '../definitions'; import type { WebPlugin } from '../web-plugin'; -export const legacyRegisterWebPlugin = ( - cap: CapacitorGlobal, - webPlugin: WebPlugin, -): void => { +export const legacyRegisterWebPlugin = (cap: CapacitorGlobal, webPlugin: WebPlugin): void => { const config = webPlugin.config; const Plugins = cap.Plugins; @@ -16,9 +13,7 @@ export const legacyRegisterWebPlugin = ( } // TODO: add link to upgrade guide - console.warn( - `Capacitor plugin "${config.name}" is using the deprecated "registerWebPlugin()" function`, - ); + console.warn(`Capacitor plugin "${config.name}" is using the deprecated "registerWebPlugin()" function`); if (!Plugins[config.name] || config?.platforms?.includes(cap.getPlatform())) { // Add the web plugin into the plugins registry if there already isn't diff --git a/core/src/platforms.ts b/core/src/platforms.ts index 54460f7e6..abe738504 100644 --- a/core/src/platforms.ts +++ b/core/src/platforms.ts @@ -6,10 +6,7 @@ export interface CapacitorPlatform { getPlatform?(): string; isPluginAvailable?(pluginName: string): boolean; getPluginHeader?(pluginName: string): PluginHeader | undefined; - registerPlugin?( - pluginName: string, - jsImplementations: PluginImplementations, - ): any; + registerPlugin?(pluginName: string, jsImplementations: PluginImplementations): any; isNativePlatform?(): boolean; } @@ -45,8 +42,7 @@ const createCapacitorPlatforms = (win: any): CapacitorPlatformsInstance => { return capPlatforms; }; -const initPlatforms = (win: any) => - (win.CapacitorPlatforms = createCapacitorPlatforms(win)); +const initPlatforms = (win: any) => (win.CapacitorPlatforms = createCapacitorPlatforms(win)); /** * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead @@ -55,12 +51,12 @@ export const CapacitorPlatforms = /*#__PURE__*/ initPlatforms( (typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' - ? self - : typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}) as any, + ? self + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}) as any, ); /** * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead diff --git a/core/src/runtime.ts b/core/src/runtime.ts index b196269ad..ee7a70cd0 100644 --- a/core/src/runtime.ts +++ b/core/src/runtime.ts @@ -15,8 +15,7 @@ export interface RegisteredPlugin { } export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { - const capCustomPlatform: CapacitorCustomPlatformInstance = - win.CapacitorCustomPlatform || null; + const capCustomPlatform: CapacitorCustomPlatformInstance = win.CapacitorCustomPlatform || null; const cap: CapacitorInstance = win.Capacitor || ({} as any); const Plugins = (cap.Plugins = cap.Plugins || ({} as any)); /** @@ -25,16 +24,12 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { const capPlatforms: CapacitorPlatformsInstance = win.CapacitorPlatforms; const defaultGetPlatform = () => { - return capCustomPlatform !== null - ? capCustomPlatform.name - : getPlatformId(win); + return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win); }; - const getPlatform = - capPlatforms?.currentPlatform?.getPlatform || defaultGetPlatform; + const getPlatform = capPlatforms?.currentPlatform?.getPlatform || defaultGetPlatform; const defaultIsNativePlatform = () => getPlatform() !== 'web'; - const isNativePlatform = - capPlatforms?.currentPlatform?.isNativePlatform || defaultIsNativePlatform; + const isNativePlatform = capPlatforms?.currentPlatform?.isNativePlatform || defaultIsNativePlatform; const defaultIsPluginAvailable = (pluginName: string): boolean => { const plugin = registeredPlugins.get(pluginName); @@ -51,40 +46,24 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { return false; }; - const isPluginAvailable = - capPlatforms?.currentPlatform?.isPluginAvailable || - defaultIsPluginAvailable; + const isPluginAvailable = capPlatforms?.currentPlatform?.isPluginAvailable || defaultIsPluginAvailable; - const defaultGetPluginHeader = ( - pluginName: string, - ): PluginHeader | undefined => - cap.PluginHeaders?.find(h => h.name === pluginName); - const getPluginHeader = - capPlatforms?.currentPlatform?.getPluginHeader || defaultGetPluginHeader; + const defaultGetPluginHeader = (pluginName: string): PluginHeader | undefined => + cap.PluginHeaders?.find((h) => h.name === pluginName); + const getPluginHeader = capPlatforms?.currentPlatform?.getPluginHeader || defaultGetPluginHeader; const handleError = (err: Error) => win.console.error(err); - const pluginMethodNoop = ( - _target: any, - prop: PropertyKey, - pluginName: string, - ) => { - return Promise.reject( - `${pluginName} does not have an implementation of "${prop as any}".`, - ); + const pluginMethodNoop = (_target: any, prop: PropertyKey, pluginName: string) => { + return Promise.reject(`${pluginName} does not have an implementation of "${prop as any}".`); }; const registeredPlugins = new Map(); - const defaultRegisterPlugin = ( - pluginName: string, - jsImplementations: PluginImplementations = {}, - ): any => { + const defaultRegisterPlugin = (pluginName: string, jsImplementations: PluginImplementations = {}): any => { const registeredPlugin = registeredPlugins.get(pluginName); if (registeredPlugin) { - console.warn( - `Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`, - ); + console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`); return registeredPlugin.proxy; } @@ -99,11 +78,7 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { typeof jsImplementations[platform] === 'function' ? (jsImplementation = await jsImplementations[platform]()) : (jsImplementation = jsImplementations[platform]); - } else if ( - capCustomPlatform !== null && - !jsImplementation && - 'web' in jsImplementations - ) { + } else if (capCustomPlatform !== null && !jsImplementation && 'web' in jsImplementations) { jsImplementation = typeof jsImplementations['web'] === 'function' ? (jsImplementation = await jsImplementations['web']()) @@ -113,24 +88,14 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { return jsImplementation; }; - const createPluginMethod = ( - impl: any, - prop: PropertyKey, - ): ((...args: any[]) => any) => { + const createPluginMethod = (impl: any, prop: PropertyKey): ((...args: any[]) => any) => { if (pluginHeader) { - const methodHeader = pluginHeader?.methods.find(m => prop === m.name); + const methodHeader = pluginHeader?.methods.find((m) => prop === m.name); if (methodHeader) { if (methodHeader.rtype === 'promise') { - return (options: any) => - cap.nativePromise(pluginName, prop.toString(), options); + return (options: any) => cap.nativePromise(pluginName, prop.toString(), options); } else { - return (options: any, callback: any) => - cap.nativeCallback( - pluginName, - prop.toString(), - options, - callback, - ); + return (options: any, callback: any) => cap.nativeCallback(pluginName, prop.toString(), options, callback); } } else if (impl) { return impl[prop]?.bind(impl); @@ -148,7 +113,7 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { const createPluginMethodWrapper = (prop: PropertyKey) => { let remove: (() => void) | undefined; const wrapper = (...args: any[]) => { - const p = loadPluginImplementation().then(impl => { + const p = loadPluginImplementation().then((impl) => { const fn = createPluginMethod(impl, prop); if (fn) { @@ -157,9 +122,7 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { return p; } else { throw new CapacitorException( - `"${pluginName}.${ - prop as any - }()" is not implemented on ${platform}`, + `"${pluginName}.${prop as any}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented, ); } @@ -199,7 +162,7 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { ); }; - const p = new Promise(resolve => call.then(() => resolve({ remove }))); + const p = new Promise((resolve) => call.then(() => resolve({ remove }))); (p as any).remove = async () => { console.warn(`Using addListener() without 'await' is deprecated.`); @@ -235,20 +198,16 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { registeredPlugins.set(pluginName, { name: pluginName, proxy, - platforms: new Set([ - ...Object.keys(jsImplementations), - ...(pluginHeader ? [platform] : []), - ]), + platforms: new Set([...Object.keys(jsImplementations), ...(pluginHeader ? [platform] : [])]), }); return proxy; }; - const registerPlugin = - capPlatforms?.currentPlatform?.registerPlugin || defaultRegisterPlugin; + const registerPlugin = capPlatforms?.currentPlatform?.registerPlugin || defaultRegisterPlugin; // Add in convertFileSrc for web, it will already be available in native context if (!cap.convertFileSrc) { - cap.convertFileSrc = filePath => filePath; + cap.convertFileSrc = (filePath) => filePath; } cap.getPlatform = getPlatform; @@ -268,5 +227,4 @@ export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => { return cap; }; -export const initCapacitorGlobal = (win: any): CapacitorGlobal => - (win.Capacitor = createCapacitor(win)); +export const initCapacitorGlobal = (win: any): CapacitorGlobal => (win.Capacitor = createCapacitor(win)); diff --git a/core/src/tests/bridge.spec.ts b/core/src/tests/bridge.spec.ts index 5e05abda2..daf7f0328 100644 --- a/core/src/tests/bridge.spec.ts +++ b/core/src/tests/bridge.spec.ts @@ -3,11 +3,7 @@ */ import { initBridge } from '../../native-bridge'; -import type { - CapacitorInstance, - PluginResult, - WindowCapacitor, -} from '../definitions-internal'; +import type { CapacitorInstance, PluginResult, WindowCapacitor } from '../definitions-internal'; import { createCapacitor } from '../runtime'; describe('bridge', () => { @@ -23,7 +19,7 @@ describe('bridge', () => { window.prompt = () => {}; }); - it('android nativePromise error', done => { + it('android nativePromise error', (done) => { mockAndroidPluginResult({ success: false, data: null, @@ -40,7 +36,7 @@ describe('bridge', () => { .then(() => { done('should throw error'); }) - .catch(err => { + .catch((err) => { try { expect(err.message).toBe('darn it'); done(); @@ -50,7 +46,7 @@ describe('bridge', () => { }); }); - it('android nativePromise success', done => { + it('android nativePromise success', (done) => { mockAndroidPluginResult({ success: true, data: { mph: 88 }, @@ -63,7 +59,7 @@ describe('bridge', () => { cap .nativePromise('id', 'method') - .then(data => { + .then((data) => { try { expect(data).toEqual({ mph: 88 }); done(); @@ -74,7 +70,7 @@ describe('bridge', () => { .catch(done); }); - it('ios nativeCallback w/ callback error', done => { + it('ios nativeCallback w/ callback error', (done) => { mockIosPluginResult({ data: null, success: false, @@ -97,7 +93,7 @@ describe('bridge', () => { }); }); - it('ios nativeCallback w/ options and callback, success', done => { + it('ios nativeCallback w/ options and callback, success', (done) => { mockIosPluginResult({ data: { mph: 88 }, success: true, @@ -121,7 +117,7 @@ describe('bridge', () => { const mockAndroidPluginResult = (pluginResult: PluginResult) => { win.androidBridge = { - postMessage: m => { + postMessage: (m) => { const d = JSON.parse(m); Promise.resolve().then(() => { pluginResult.callbackId = d.callbackId; @@ -136,7 +132,7 @@ describe('bridge', () => { win.webkit = { messageHandlers: { bridge: { - postMessage: m => { + postMessage: (m) => { Promise.resolve().then(() => { pluginResult.callbackId = m.callbackId; pluginResult.methodName = m.methodName; diff --git a/core/src/tests/build-treeshaking.js b/core/src/tests/build-treeshaking.js index 6c0896a8a..b5336f50d 100644 --- a/core/src/tests/build-treeshaking.js +++ b/core/src/tests/build-treeshaking.js @@ -56,15 +56,13 @@ async function validateBuildTreeshaking() { if (outputCode !== '') { console.error(`\nTreeshake output: ${outputFile}\n`); - throw new Error( - `๐Ÿงจ Not all code was not treeshaken (treeshooken? treeshaked?) Review the ${outputFile} file.`, - ); + throw new Error(`๐Ÿงจ Not all code was not treeshaken (treeshooken? treeshaked?) Review the ${outputFile} file.`); } console.log(`๐ŸŒณ validated treeshaking: ${entryModulePath}`); } -validateBuildTreeshaking().catch(err => { +validateBuildTreeshaking().catch((err) => { console.error(err); process.exit(1); }); diff --git a/core/src/tests/convert-file-src.spec.ts b/core/src/tests/convert-file-src.spec.ts index 6cb630f15..e2a57aff8 100644 --- a/core/src/tests/convert-file-src.spec.ts +++ b/core/src/tests/convert-file-src.spec.ts @@ -1,8 +1,5 @@ import { initBridge } from '../../native-bridge'; -import type { - CapacitorInstance, - WindowCapacitor, -} from '../definitions-internal'; +import type { CapacitorInstance, WindowCapacitor } from '../definitions-internal'; import { createCapacitor } from '../runtime'; describe('convertFileSrc', () => { @@ -18,21 +15,15 @@ describe('convertFileSrc', () => { }); it('starts with content://', () => { - expect(cap.convertFileSrc('content://myfile')).toBe( - 'webviewSeverUrl/_capacitor_content_/myfile', - ); + expect(cap.convertFileSrc('content://myfile')).toBe('webviewSeverUrl/_capacitor_content_/myfile'); }); it('starts with file://', () => { - expect(cap.convertFileSrc('file://myfile')).toBe( - 'webviewSeverUrl/_capacitor_file_myfile', - ); + expect(cap.convertFileSrc('file://myfile')).toBe('webviewSeverUrl/_capacitor_file_myfile'); }); it('starts with /', () => { - expect(cap.convertFileSrc('/myfile')).toBe( - 'webviewSeverUrl/_capacitor_file_/myfile', - ); + expect(cap.convertFileSrc('/myfile')).toBe('webviewSeverUrl/_capacitor_file_/myfile'); }); it('non string', () => { diff --git a/core/src/tests/events.spec.ts b/core/src/tests/events.spec.ts index ccf2cb40b..3486c1ab7 100644 --- a/core/src/tests/events.spec.ts +++ b/core/src/tests/events.spec.ts @@ -1,8 +1,5 @@ import { initBridge } from '../../native-bridge'; -import type { - CapacitorInstance, - WindowCapacitor, -} from '../definitions-internal'; +import type { CapacitorInstance, WindowCapacitor } from '../definitions-internal'; import { createCapacitor } from '../runtime'; describe('plugin', () => { diff --git a/core/src/tests/legacy.spec.ts b/core/src/tests/legacy.spec.ts index a9902a853..c9c567cef 100644 --- a/core/src/tests/legacy.spec.ts +++ b/core/src/tests/legacy.spec.ts @@ -107,7 +107,7 @@ describe('legacy', () => { ); }); - it('doc.addEventListener backbutton', done => { + it('doc.addEventListener backbutton', (done) => { const AppWeb = class { async addListener(eventName: string) { expect(eventName).toBe('backButton'); @@ -135,7 +135,7 @@ describe('legacy', () => { win.document.addEventListener('backbutton', bbCallback); }); - it('doc.addEventListener deviceready', done => { + it('doc.addEventListener deviceready', (done) => { win = { document: { addEventListener() { diff --git a/core/src/tests/plugin.spec.ts b/core/src/tests/plugin.spec.ts index 9c0164451..e9d6a4f5c 100644 --- a/core/src/tests/plugin.spec.ts +++ b/core/src/tests/plugin.spec.ts @@ -4,10 +4,7 @@ import { initBridge } from '../../native-bridge'; import type { CapacitorGlobal, Plugin } from '../definitions'; -import type { - WindowCapacitor, - CapacitorInstance, -} from '../definitions-internal'; +import type { WindowCapacitor, CapacitorInstance } from '../definitions-internal'; import { initCapacitorGlobal } from '../runtime'; import { ExceptionCode } from '../util'; import { WebPlugin } from '../web-plugin'; @@ -23,7 +20,7 @@ describe('plugin', () => { global.setImmediate = global.setTimeout; }); - it('error from missing method from native implementation', async done => { + it('error from missing method from native implementation', async (done) => { // mock the global with the android bridge mockAndroidBridge(); initBridge(win); @@ -76,7 +73,7 @@ describe('plugin', () => { expect(results2).toBe(88); }); - it('error from missing native implementation', async done => { + it('error from missing native implementation', async (done) => { // mock the global with the android bridge mockAndroidBridge(); initBridge(win); @@ -105,7 +102,7 @@ describe('plugin', () => { } }); - it('error lazy loading implementation', async done => { + it('error lazy loading implementation', async (done) => { mockAndroidBridge(); initBridge(win); @@ -204,7 +201,7 @@ describe('plugin', () => { expect(async () => cap.Plugins.Awesome.mph()).rejects.toThrowError('nope!'); }); - it('missing method on lazy loaded implementation', async done => { + it('missing method on lazy loaded implementation', async (done) => { cap = initCapacitorGlobal(win); const Awesome = cap.registerPlugin('Awesome', { @@ -229,7 +226,7 @@ describe('plugin', () => { } }); - it('missing method on already loaded implementation', async done => { + it('missing method on already loaded implementation', async (done) => { mockAndroidBridge(); initBridge(win); @@ -257,7 +254,7 @@ describe('plugin', () => { } }); - it('no web platform implementation', async done => { + it('no web platform implementation', async (done) => { cap = initCapacitorGlobal(win); expect(cap.getPlatform()).toBe('web'); @@ -281,7 +278,7 @@ describe('plugin', () => { } }); - it('no native platform implementation', async done => { + it('no native platform implementation', async (done) => { mockAndroidBridge(); initBridge(win); @@ -324,7 +321,7 @@ describe('plugin', () => { expect(Awesome1).toBe(Awesome2); }); - it('addListener, w/out addListener on implementation', async done => { + it('addListener, w/out addListener on implementation', async (done) => { const LazyWeb = class { val = 88; async addListener(_eventName: string, fn: any) { @@ -337,7 +334,7 @@ describe('plugin', () => { web: async () => new LazyWeb(), }); - Awesome.addListener('eventName', data => { + Awesome.addListener('eventName', (data) => { try { expect(data).toEqual(88); done(); @@ -381,7 +378,7 @@ describe('plugin', () => { expect(typeof (rtn as any).remove === 'function').toBe(true); }); - it('async removeAllListeners on web, lazy load and call implementation', async done => { + it('async removeAllListeners on web, lazy load and call implementation', async (done) => { const AwesomeWeb = class extends WebPlugin { async removeAllListeners() { setImmediate(() => done()); diff --git a/core/src/tests/runtime.spec.ts b/core/src/tests/runtime.spec.ts index 1b8a7a964..c39843b8d 100644 --- a/core/src/tests/runtime.spec.ts +++ b/core/src/tests/runtime.spec.ts @@ -1,8 +1,5 @@ import { initBridge } from '../../native-bridge'; -import type { - CapacitorInstance, - WindowCapacitor, -} from '../definitions-internal'; +import type { CapacitorInstance, WindowCapacitor } from '../definitions-internal'; import { createCapacitor } from '../runtime'; describe('runtime', () => { diff --git a/core/src/tests/web-plugin.spec.ts b/core/src/tests/web-plugin.spec.ts index 30bae7c0c..cb4a65ba0 100644 --- a/core/src/tests/web-plugin.spec.ts +++ b/core/src/tests/web-plugin.spec.ts @@ -137,10 +137,7 @@ describe('Web Plugin', () => { }); it('Should register and remove window listeners', async () => { - const pluginAddWindowListener = jest.spyOn( - MockPlugin.prototype as any, - 'addWindowListener', - ); + const pluginAddWindowListener = jest.spyOn(MockPlugin.prototype as any, 'addWindowListener'); plugin.registerFakeWindowListener(); const lf = jest.fn(); diff --git a/core/src/util.ts b/core/src/util.ts index a4063b0f0..61ba7a61d 100644 --- a/core/src/util.ts +++ b/core/src/util.ts @@ -33,9 +33,7 @@ export class CapacitorException extends Error { } } -export const getPlatformId = ( - win: WindowCapacitor, -): 'android' | 'ios' | 'web' => { +export const getPlatformId = (win: WindowCapacitor): 'android' | 'ios' | 'web' => { if (win?.androidBridge) { return 'android'; } else if (win?.webkit?.messageHandlers?.bridge) { diff --git a/core/src/web-plugin.ts b/core/src/web-plugin.ts index 46ebe4598..144c32fa3 100644 --- a/core/src/web-plugin.ts +++ b/core/src/web-plugin.ts @@ -26,10 +26,7 @@ export class WebPlugin implements Plugin { } } - addListener( - eventName: string, - listenerFunc: ListenerCallback, - ): Promise { + addListener(eventName: string, listenerFunc: ListenerCallback): Promise { let firstListener = false; const listeners = this.listeners[eventName]; @@ -66,11 +63,7 @@ export class WebPlugin implements Plugin { this.windowListeners = {}; } - protected notifyListeners( - eventName: string, - data: any, - retainUntilConsumed?: boolean, - ): void { + protected notifyListeners(eventName: string, data: any, retainUntilConsumed?: boolean): void { const listeners = this.listeners[eventName]; if (!listeners) { if (retainUntilConsumed) { @@ -87,22 +80,19 @@ export class WebPlugin implements Plugin { return; } - listeners.forEach(listener => listener(data)); + listeners.forEach((listener) => listener(data)); } protected hasListeners(eventName: string): boolean { return !!this.listeners[eventName].length; } - protected registerWindowListener( - windowEventName: string, - pluginEventName: string, - ): void { + protected registerWindowListener(windowEventName: string, pluginEventName: string): void { this.windowListeners[pluginEventName] = { registered: false, windowEventName, pluginEventName, - handler: event => { + handler: (event) => { this.notifyListeners(pluginEventName, event); }, }; @@ -116,10 +106,7 @@ export class WebPlugin implements Plugin { return new Capacitor.Exception(msg, ExceptionCode.Unavailable); } - private async removeListener( - eventName: string, - listenerFunc: ListenerCallback, - ): Promise { + private async removeListener(eventName: string, listenerFunc: ListenerCallback): Promise { const listeners = this.listeners[eventName]; if (!listeners) { return; @@ -157,7 +144,7 @@ export class WebPlugin implements Plugin { delete this.retainedEventArguments[eventName]; - args.forEach(arg => { + args.forEach((arg) => { this.notifyListeners(eventName, arg); }); } diff --git a/package.json b/package.json index 6ee9ba54a..82c776881 100644 --- a/package.json +++ b/package.json @@ -19,28 +19,28 @@ "sync-peer-dependencies": "node scripts/sync-peer-dependencies.mjs", "lint": "npm run eslint && npm run prettier -- --check && npm run swiftlint -- lint", "fmt": "npm run eslint -- --fix && npm run prettier -- --write && npm run swiftlint -- --fix --format", - "prettier": "prettier \"**/*.{css,html,java,js,mjs,ts}\"", + "prettier": "prettier \"**/*.{css,html,java,js,mjs,ts}\" --plugin=prettier-plugin-java", "eslint": "eslint . --ext ts", "swiftlint": "node-swiftlint", "version": "npm run sync-peer-dependencies" }, "prettier": "@ionic/prettier-config", + "eslintConfig": { + "extends": "@ionic/eslint-config/recommended" + }, "devDependencies": { - "@ionic/prettier-config": "~1.0.1", - "@ionic/swiftlint-config": "^1.1.2", + "@ionic/eslint-config": "^0.4.0", + "@ionic/prettier-config": "^4.0.0", + "@ionic/swiftlint-config": "^2.0.0", "@types/node": "18.18.6", "@types/tar": "^6.1.2", - "@typescript-eslint/eslint-plugin": "^5.58.0", - "@typescript-eslint/parser": "^5.58.0", - "eslint": "~8.38.0", - "eslint-config-prettier": "^8.8.0", - "eslint-plugin-import": "^2.27.0", + "eslint": "^8.57.0", "lerna": "^7.1.3", - "prettier": "~2.3.0", - "prettier-plugin-java": "~1.1.1", + "prettier": "^3.3.0", + "prettier-plugin-java": "^2.6.4", "rimraf": "^4.4.1", "semver": "^7.3.7", - "swiftlint": "^1.0.1", + "swiftlint": "^2.0.0", "tar": "^6.1.11" } } diff --git a/scripts/lib/cli.mjs b/scripts/lib/cli.mjs index 37dc9ee4f..6b2df9276 100644 --- a/scripts/lib/cli.mjs +++ b/scripts/lib/cli.mjs @@ -1,5 +1,5 @@ -export const execute = fn => { - fn().catch(e => { +export const execute = (fn) => { + fn().catch((e) => { process.stderr.write(e.stack ?? e); process.exit(1); }); diff --git a/scripts/lib/fn.mjs b/scripts/lib/fn.mjs index 3f0d7d0ea..9876705e4 100644 --- a/scripts/lib/fn.mjs +++ b/scripts/lib/fn.mjs @@ -1,5 +1,5 @@ -export const identity = v => v; +export const identity = (v) => v; export const pipe = (...fns) => - v => + (v) => fns.reduce((r, fn) => fn(r), v); diff --git a/scripts/lib/fs.mjs b/scripts/lib/fs.mjs index 491ede76c..adab5bea0 100644 --- a/scripts/lib/fs.mjs +++ b/scripts/lib/fs.mjs @@ -3,7 +3,7 @@ import * as util from 'util'; export const mkdir = util.promisify(fs.mkdir); export const readFile = util.promisify(fs.readFile); -export const readJSON = async p => JSON.parse(await readFile(p)); +export const readJSON = async (p) => JSON.parse(await readFile(p)); export const writeFile = util.promisify(fs.writeFile); export const writeJSON = async (p, contents, space = 2) => writeFile(p, JSON.stringify(contents, undefined, space) + '\n'); diff --git a/scripts/lib/git.mjs b/scripts/lib/git.mjs index abd15df6e..d2860970d 100644 --- a/scripts/lib/git.mjs +++ b/scripts/lib/git.mjs @@ -3,8 +3,6 @@ import { root } from './repo.mjs'; const cwd = root; -const execGit = async (command, options) => - await cp.exec(`git ${command}`, { cwd, ...options }); +const execGit = async (command, options) => await cp.exec(`git ${command}`, { cwd, ...options }); -export const lsfiles = async (p, options) => - (await execGit(`ls-files "${p}"`, options)).stdout.trim().split('\n'); +export const lsfiles = async (p, options) => (await execGit(`ls-files "${p}"`, options)).stdout.trim().split('\n'); diff --git a/scripts/lib/lerna.mjs b/scripts/lib/lerna.mjs index 386a09c07..f6c30b574 100644 --- a/scripts/lib/lerna.mjs +++ b/scripts/lib/lerna.mjs @@ -4,10 +4,8 @@ import * as cp from './subprocess.mjs'; const stdio = 'inherit'; const cwd = root; -const execLerna = async command => - await cp.exec(`npx lerna ${command}`, { cwd }); -const runLerna = async (args = []) => - await cp.run('npx', ['lerna', ...args], { cwd, stdio }); +const execLerna = async (command) => await cp.exec(`npx lerna ${command}`, { cwd }); +const runLerna = async (args = []) => await cp.run('npx', ['lerna', ...args], { cwd, stdio }); export const ls = async () => JSON.parse((await execLerna('ls --json')).stdout); export const exec = async (args = []) => await runLerna(['exec', ...args]); diff --git a/scripts/lib/repo.mjs b/scripts/lib/repo.mjs index be2842563..54f2aada0 100644 --- a/scripts/lib/repo.mjs +++ b/scripts/lib/repo.mjs @@ -3,7 +3,4 @@ import { dirname } from 'path'; import { pipe } from './fn.mjs'; -export const root = pipe( - fileURLToPath, - ...Array(3).fill(dirname), -)(import.meta.url); +export const root = pipe(fileURLToPath, ...Array(3).fill(dirname))(import.meta.url); diff --git a/scripts/lib/subprocess.mjs b/scripts/lib/subprocess.mjs index c446b8f0d..8a5da6c8e 100644 --- a/scripts/lib/subprocess.mjs +++ b/scripts/lib/subprocess.mjs @@ -4,7 +4,7 @@ import * as util from 'util'; export const exec = util.promisify(cp.exec); export const spawn = cp.spawn; export const run = (cmd, args, options) => wait(spawn(cmd, args, options)); -export const wait = async p => { +export const wait = async (p) => { return new Promise((resolve, reject) => { p.on('error', reject); @@ -12,9 +12,7 @@ export const wait = async p => { if (code === 0) { resolve(); } else { - reject( - new Error(`bad subprocess exit (code=${code}, signal=${signal})`), - ); + reject(new Error(`bad subprocess exit (code=${code}, signal=${signal})`)); } }); }); diff --git a/scripts/lib/version.mjs b/scripts/lib/version.mjs index b763fd29b..d4d6c5ab0 100644 --- a/scripts/lib/version.mjs +++ b/scripts/lib/version.mjs @@ -1,10 +1,6 @@ import { readJSON, writeJSON } from './fs.mjs'; -export const setPackageJsonDependencies = async ( - path, - packages, - key = 'dependencies', -) => { +export const setPackageJsonDependencies = async (path, packages, key = 'dependencies') => { const pkg = await readJSON(path); for (const [dep, version] of Object.entries(packages)) { diff --git a/scripts/sync-peer-dependencies.mjs b/scripts/sync-peer-dependencies.mjs index 34f9ccfd1..63600b19e 100644 --- a/scripts/sync-peer-dependencies.mjs +++ b/scripts/sync-peer-dependencies.mjs @@ -9,20 +9,14 @@ execute(async () => { const CORE_DEPENDENTS = ['@capacitor/android', '@capacitor/ios']; const pkgs = await ls(); - const corePkg = pkgs.find(p => p.name === '@capacitor/core'); + const corePkg = pkgs.find((p) => p.name === '@capacitor/core'); const { major, minor, prerelease } = semver.parse(corePkg.version); - const range = `^${major}.${minor}.0${ - prerelease.length > 0 ? `-${prerelease.join('.')}` : '' - }`; + const range = `^${major}.${minor}.0${prerelease.length > 0 ? `-${prerelease.join('.')}` : ''}`; - for (const pkg of pkgs.filter(p => CORE_DEPENDENTS.includes(p.name))) { + for (const pkg of pkgs.filter((p) => CORE_DEPENDENTS.includes(p.name))) { const p = resolve(pkg.location, 'package.json'); - await setPackageJsonDependencies( - p, - { '@capacitor/core': range }, - 'peerDependencies', - ); + await setPackageJsonDependencies(p, { '@capacitor/core': range }, 'peerDependencies'); } }); diff --git a/swiftlint.config.js b/swiftlint.config.js index 5d7a8d489..59e40b890 100644 --- a/swiftlint.config.js +++ b/swiftlint.config.js @@ -1,13 +1,5 @@ module.exports = { ...require('@ionic/swiftlint-config'), - included: [ - '${PWD}/ios', - '${PWD}/ios-pods-template', - '${PWD}/ios-spm-template', - ], - excluded: [ - '${PWD}/ios/Capacitor/CapacitorTests', - '${PWD}/ios/Capacitor/TestsHostApp', - '${PWD}/ios/Frameworks', - ], + included: ['${PWD}/ios', '${PWD}/ios-pods-template', '${PWD}/ios-spm-template'], + excluded: ['${PWD}/ios/Capacitor/CapacitorTests', '${PWD}/ios/Capacitor/TestsHostApp', '${PWD}/ios/Frameworks'], };